entity.inc 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  1. <?php
  2. /**
  3. * Interface for entity controller classes.
  4. *
  5. * All entity controller classes specified via the 'controller class' key
  6. * returned by hook_entity_info() or hook_entity_info_alter() have to implement
  7. * this interface.
  8. *
  9. * Most simple, SQL-based entity controllers will do better by extending
  10. * DrupalDefaultEntityController instead of implementing this interface
  11. * directly.
  12. */
  13. interface DrupalEntityControllerInterface {
  14. /**
  15. * Constructor.
  16. *
  17. * @param $entityType
  18. * The entity type for which the instance is created.
  19. */
  20. public function __construct($entityType);
  21. /**
  22. * Resets the internal, static entity cache.
  23. *
  24. * @param $ids
  25. * (optional) If specified, the cache is reset for the entities with the
  26. * given ids only.
  27. */
  28. public function resetCache(array $ids = NULL);
  29. /**
  30. * Loads one or more entities.
  31. *
  32. * @param $ids
  33. * An array of entity IDs, or FALSE to load all entities.
  34. * @param $conditions
  35. * An array of conditions in the form 'field' => $value.
  36. *
  37. * @return
  38. * An array of entity objects indexed by their ids. When no results are
  39. * found, an empty array is returned.
  40. */
  41. public function load($ids = array(), $conditions = array());
  42. }
  43. /**
  44. * Default implementation of DrupalEntityControllerInterface.
  45. *
  46. * This class can be used as-is by most simple entity types. Entity types
  47. * requiring special handling can extend the class.
  48. */
  49. class DrupalDefaultEntityController implements DrupalEntityControllerInterface {
  50. /**
  51. * Static cache of entities.
  52. *
  53. * @var array
  54. */
  55. protected $entityCache;
  56. /**
  57. * Entity type for this controller instance.
  58. *
  59. * @var string
  60. */
  61. protected $entityType;
  62. /**
  63. * Array of information about the entity.
  64. *
  65. * @var array
  66. *
  67. * @see entity_get_info()
  68. */
  69. protected $entityInfo;
  70. /**
  71. * Additional arguments to pass to hook_TYPE_load().
  72. *
  73. * Set before calling DrupalDefaultEntityController::attachLoad().
  74. *
  75. * @var array
  76. */
  77. protected $hookLoadArguments;
  78. /**
  79. * Name of the entity's ID field in the entity database table.
  80. *
  81. * @var string
  82. */
  83. protected $idKey;
  84. /**
  85. * Name of entity's revision database table field, if it supports revisions.
  86. *
  87. * Has the value FALSE if this entity does not use revisions.
  88. *
  89. * @var string
  90. */
  91. protected $revisionKey;
  92. /**
  93. * The table that stores revisions, if the entity supports revisions.
  94. *
  95. * @var string
  96. */
  97. protected $revisionTable;
  98. /**
  99. * Whether this entity type should use the static cache.
  100. *
  101. * Set by entity info.
  102. *
  103. * @var boolean
  104. */
  105. protected $cache;
  106. /**
  107. * Constructor: sets basic variables.
  108. */
  109. public function __construct($entityType) {
  110. $this->entityType = $entityType;
  111. $this->entityInfo = entity_get_info($entityType);
  112. $this->entityCache = array();
  113. $this->hookLoadArguments = array();
  114. $this->idKey = $this->entityInfo['entity keys']['id'];
  115. // Check if the entity type supports revisions.
  116. if (!empty($this->entityInfo['entity keys']['revision'])) {
  117. $this->revisionKey = $this->entityInfo['entity keys']['revision'];
  118. $this->revisionTable = $this->entityInfo['revision table'];
  119. }
  120. else {
  121. $this->revisionKey = FALSE;
  122. }
  123. // Check if the entity type supports static caching of loaded entities.
  124. $this->cache = !empty($this->entityInfo['static cache']);
  125. }
  126. /**
  127. * Implements DrupalEntityControllerInterface::resetCache().
  128. */
  129. public function resetCache(array $ids = NULL) {
  130. if (isset($ids)) {
  131. foreach ($ids as $id) {
  132. unset($this->entityCache[$id]);
  133. }
  134. }
  135. else {
  136. $this->entityCache = array();
  137. }
  138. }
  139. /**
  140. * Implements DrupalEntityControllerInterface::load().
  141. */
  142. public function load($ids = array(), $conditions = array()) {
  143. $entities = array();
  144. # PATCH http://drupal.org/node/1003788#comment-5195682
  145. // Clean the $ids array to remove non-integer values that can be passed
  146. // in from various sources, including menu callbacks.
  147. if (is_array($ids)) {
  148. foreach ($ids as $key => $id) {
  149. if (empty($id) || ((string) $id !== (string) (int) $id)) {
  150. unset($ids[$key]);
  151. }
  152. }
  153. }
  154. # endpatch
  155. // Revisions are not statically cached, and require a different query to
  156. // other conditions, so separate the revision id into its own variable.
  157. if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
  158. $revision_id = $conditions[$this->revisionKey];
  159. unset($conditions[$this->revisionKey]);
  160. }
  161. else {
  162. $revision_id = FALSE;
  163. }
  164. // Create a new variable which is either a prepared version of the $ids
  165. // array for later comparison with the entity cache, or FALSE if no $ids
  166. // were passed. The $ids array is reduced as items are loaded from cache,
  167. // and we need to know if it's empty for this reason to avoid querying the
  168. // database when all requested entities are loaded from cache.
  169. $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
  170. // Try to load entities from the static cache, if the entity type supports
  171. // static caching.
  172. if ($this->cache && !$revision_id) {
  173. $entities += $this->cacheGet($ids, $conditions);
  174. // If any entities were loaded, remove them from the ids still to load.
  175. if ($passed_ids) {
  176. $ids = array_keys(array_diff_key($passed_ids, $entities));
  177. }
  178. }
  179. // Load any remaining entities from the database. This is the case if $ids
  180. // is set to FALSE (so we load all entities), if there are any ids left to
  181. // load, if loading a revision, or if $conditions was passed without $ids.
  182. if ($ids === FALSE || $ids || $revision_id || ($conditions && !$passed_ids)) {
  183. // Build the query.
  184. $query = $this->buildQuery($ids, $conditions, $revision_id);
  185. $queried_entities = $query
  186. ->execute()
  187. ->fetchAllAssoc($this->idKey);
  188. }
  189. // Pass all entities loaded from the database through $this->attachLoad(),
  190. // which attaches fields (if supported by the entity type) and calls the
  191. // entity type specific load callback, for example hook_node_load().
  192. if (!empty($queried_entities)) {
  193. $this->attachLoad($queried_entities, $revision_id);
  194. $entities += $queried_entities;
  195. }
  196. if ($this->cache) {
  197. // Add entities to the cache if we are not loading a revision.
  198. if (!empty($queried_entities) && !$revision_id) {
  199. $this->cacheSet($queried_entities);
  200. }
  201. }
  202. // Ensure that the returned array is ordered the same as the original
  203. // $ids array if this was passed in and remove any invalid ids.
  204. if ($passed_ids) {
  205. // Remove any invalid ids from the array.
  206. $passed_ids = array_intersect_key($passed_ids, $entities);
  207. foreach ($entities as $entity) {
  208. $passed_ids[$entity->{$this->idKey}] = $entity;
  209. }
  210. $entities = $passed_ids;
  211. }
  212. return $entities;
  213. }
  214. /**
  215. * Builds the query to load the entity.
  216. *
  217. * This has full revision support. For entities requiring special queries,
  218. * the class can be extended, and the default query can be constructed by
  219. * calling parent::buildQuery(). This is usually necessary when the object
  220. * being loaded needs to be augmented with additional data from another
  221. * table, such as loading node type into comments or vocabulary machine name
  222. * into terms, however it can also support $conditions on different tables.
  223. * See CommentController::buildQuery() or TaxonomyTermController::buildQuery()
  224. * for examples.
  225. *
  226. * @param $ids
  227. * An array of entity IDs, or FALSE to load all entities.
  228. * @param $conditions
  229. * An array of conditions in the form 'field' => $value.
  230. * @param $revision_id
  231. * The ID of the revision to load, or FALSE if this query is asking for the
  232. * most current revision(s).
  233. *
  234. * @return SelectQuery
  235. * A SelectQuery object for loading the entity.
  236. */
  237. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  238. $query = db_select($this->entityInfo['base table'], 'base');
  239. $query->addTag($this->entityType . '_load_multiple');
  240. if ($revision_id) {
  241. $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} = :revisionId", array(':revisionId' => $revision_id));
  242. }
  243. elseif ($this->revisionKey) {
  244. $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
  245. }
  246. // Add fields from the {entity} table.
  247. $entity_fields = $this->entityInfo['schema_fields_sql']['base table'];
  248. if ($this->revisionKey) {
  249. // Add all fields from the {entity_revision} table.
  250. $entity_revision_fields = drupal_map_assoc($this->entityInfo['schema_fields_sql']['revision table']);
  251. // The id field is provided by entity, so remove it.
  252. unset($entity_revision_fields[$this->idKey]);
  253. // Remove all fields from the base table that are also fields by the same
  254. // name in the revision table.
  255. $entity_field_keys = array_flip($entity_fields);
  256. foreach ($entity_revision_fields as $key => $name) {
  257. if (isset($entity_field_keys[$name])) {
  258. unset($entity_fields[$entity_field_keys[$name]]);
  259. }
  260. }
  261. $query->fields('revision', $entity_revision_fields);
  262. }
  263. $query->fields('base', $entity_fields);
  264. if ($ids) {
  265. $query->condition("base.{$this->idKey}", $ids, 'IN');
  266. }
  267. if ($conditions) {
  268. foreach ($conditions as $field => $value) {
  269. $query->condition('base.' . $field, $value);
  270. }
  271. }
  272. return $query;
  273. }
  274. /**
  275. * Attaches data to entities upon loading.
  276. * This will attach fields, if the entity is fieldable. It calls
  277. * hook_entity_load() for modules which need to add data to all entities.
  278. * It also calls hook_TYPE_load() on the loaded entities. For example
  279. * hook_node_load() or hook_user_load(). If your hook_TYPE_load()
  280. * expects special parameters apart from the queried entities, you can set
  281. * $this->hookLoadArguments prior to calling the method.
  282. * See NodeController::attachLoad() for an example.
  283. *
  284. * @param $queried_entities
  285. * Associative array of query results, keyed on the entity ID.
  286. * @param $revision_id
  287. * ID of the revision that was loaded, or FALSE if the most current revision
  288. * was loaded.
  289. */
  290. protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
  291. // Attach fields.
  292. if ($this->entityInfo['fieldable']) {
  293. if ($revision_id) {
  294. field_attach_load_revision($this->entityType, $queried_entities);
  295. }
  296. else {
  297. field_attach_load($this->entityType, $queried_entities);
  298. }
  299. }
  300. // Call hook_entity_load().
  301. foreach (module_implements('entity_load') as $module) {
  302. $function = $module . '_entity_load';
  303. $function($queried_entities, $this->entityType);
  304. }
  305. // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
  306. // always the queried entities, followed by additional arguments set in
  307. // $this->hookLoadArguments.
  308. $args = array_merge(array($queried_entities), $this->hookLoadArguments);
  309. foreach (module_implements($this->entityInfo['load hook']) as $module) {
  310. call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
  311. }
  312. }
  313. /**
  314. * Gets entities from the static cache.
  315. *
  316. * @param $ids
  317. * If not empty, return entities that match these IDs.
  318. * @param $conditions
  319. * If set, return entities that match all of these conditions.
  320. *
  321. * @return
  322. * Array of entities from the entity cache.
  323. */
  324. protected function cacheGet($ids, $conditions = array()) {
  325. $entities = array();
  326. // Load any available entities from the internal cache.
  327. if (!empty($this->entityCache)) {
  328. if ($ids) {
  329. $entities += array_intersect_key($this->entityCache, array_flip($ids));
  330. }
  331. // If loading entities only by conditions, fetch all available entities
  332. // from the cache. Entities which don't match are removed later.
  333. elseif ($conditions) {
  334. $entities = $this->entityCache;
  335. }
  336. }
  337. // Exclude any entities loaded from cache if they don't match $conditions.
  338. // This ensures the same behavior whether loading from memory or database.
  339. if ($conditions) {
  340. foreach ($entities as $entity) {
  341. $entity_values = (array) $entity;
  342. if (array_diff_assoc($conditions, $entity_values)) {
  343. unset($entities[$entity->{$this->idKey}]);
  344. }
  345. }
  346. }
  347. return $entities;
  348. }
  349. /**
  350. * Stores entities in the static entity cache.
  351. *
  352. * @param $entities
  353. * Entities to store in the cache.
  354. */
  355. protected function cacheSet($entities) {
  356. $this->entityCache += $entities;
  357. }
  358. }
  359. /**
  360. * Exception thrown by EntityFieldQuery() on unsupported query syntax.
  361. *
  362. * Some storage modules might not support the full range of the syntax for
  363. * conditions, and will raise an EntityFieldQueryException when an unsupported
  364. * condition was specified.
  365. */
  366. class EntityFieldQueryException extends Exception {}
  367. /**
  368. * Retrieves entities matching a given set of conditions.
  369. *
  370. * This class allows finding entities based on entity properties (for example,
  371. * node->changed), field values, and generic entity meta data (bundle,
  372. * entity type, entity id, and revision ID). It is not possible to query across
  373. * multiple entity types. For example, there is no facility to find published
  374. * nodes written by users created in the last hour, as this would require
  375. * querying both node->status and user->created.
  376. *
  377. * Normally we would not want to have public properties on the object, as that
  378. * allows the object's state to become inconsistent too easily. However, this
  379. * class's standard use case involves primarily code that does need to have
  380. * direct access to the collected properties in order to handle alternate
  381. * execution routines. We therefore use public properties for simplicity. Note
  382. * that code that is simply creating and running a field query should still use
  383. * the appropriate methods to add conditions on the query.
  384. *
  385. * Storage engines are not required to support every type of query. By default,
  386. * an EntityFieldQueryException will be raised if an unsupported condition is
  387. * specified or if the query has field conditions or sorts that are stored in
  388. * different field storage engines. However, this logic can be overridden in
  389. * hook_entity_query().
  390. *
  391. * Also note that this query does not automatically respect entity access
  392. * restrictions. Node access control is performed by the SQL storage engine but
  393. * other storage engines might not do this.
  394. */
  395. class EntityFieldQuery {
  396. /**
  397. * Indicates that both deleted and non-deleted fields should be returned.
  398. *
  399. * @see EntityFieldQuery::deleted()
  400. */
  401. const RETURN_ALL = NULL;
  402. /**
  403. * TRUE if the query has already been altered, FALSE if it hasn't.
  404. *
  405. * Used in alter hooks to check for cloned queries that have already been
  406. * altered prior to the clone (for example, the pager count query).
  407. *
  408. * @var boolean
  409. */
  410. public $altered = FALSE;
  411. /**
  412. * Associative array of entity-generic metadata conditions.
  413. *
  414. * @var array
  415. *
  416. * @see EntityFieldQuery::entityCondition()
  417. */
  418. public $entityConditions = array();
  419. /**
  420. * List of field conditions.
  421. *
  422. * @var array
  423. *
  424. * @see EntityFieldQuery::fieldCondition()
  425. */
  426. public $fieldConditions = array();
  427. /**
  428. * List of field meta conditions (language and delta).
  429. *
  430. * Field conditions operate on columns specified by hook_field_schema(),
  431. * the meta conditions operate on columns added by the system: delta
  432. * and language. These can not be mixed with the field conditions because
  433. * field columns can have any name including delta and language.
  434. *
  435. * @var array
  436. *
  437. * @see EntityFieldQuery::fieldLanguageCondition()
  438. * @see EntityFieldQuery::fieldDeltaCondition()
  439. */
  440. public $fieldMetaConditions = array();
  441. /**
  442. * List of property conditions.
  443. *
  444. * @var array
  445. *
  446. * @see EntityFieldQuery::propertyCondition()
  447. */
  448. public $propertyConditions = array();
  449. /**
  450. * List of order clauses.
  451. *
  452. * @var array
  453. */
  454. public $order = array();
  455. /**
  456. * The query range.
  457. *
  458. * @var array
  459. *
  460. * @see EntityFieldQuery::range()
  461. */
  462. public $range = array();
  463. /**
  464. * The query pager data.
  465. *
  466. * @var array
  467. *
  468. * @see EntityFieldQuery::pager()
  469. */
  470. public $pager = array();
  471. /**
  472. * Query behavior for deleted data.
  473. *
  474. * TRUE to return only deleted data, FALSE to return only non-deleted data,
  475. * EntityFieldQuery::RETURN_ALL to return everything.
  476. *
  477. * @see EntityFieldQuery::deleted()
  478. */
  479. public $deleted = FALSE;
  480. /**
  481. * A list of field arrays used.
  482. *
  483. * Field names passed to EntityFieldQuery::fieldCondition() and
  484. * EntityFieldQuery::fieldOrderBy() are run through field_info_field() before
  485. * stored in this array. This way, the elements of this array are field
  486. * arrays.
  487. *
  488. * @var array
  489. */
  490. public $fields = array();
  491. /**
  492. * TRUE if this is a count query, FALSE if it isn't.
  493. *
  494. * @var boolean
  495. */
  496. public $count = FALSE;
  497. /**
  498. * Flag indicating whether this is querying current or all revisions.
  499. *
  500. * @var int
  501. *
  502. * @see EntityFieldQuery::age()
  503. */
  504. public $age = FIELD_LOAD_CURRENT;
  505. /**
  506. * A list of the tags added to this query.
  507. *
  508. * @var array
  509. *
  510. * @see EntityFieldQuery::addTag()
  511. */
  512. public $tags = array();
  513. /**
  514. * A list of metadata added to this query.
  515. *
  516. * @var array
  517. *
  518. * @see EntityFieldQuery::addMetaData()
  519. */
  520. public $metaData = array();
  521. /**
  522. * The ordered results.
  523. *
  524. * @var array
  525. *
  526. * @see EntityFieldQuery::execute().
  527. */
  528. public $orderedResults = array();
  529. /**
  530. * The method executing the query, if it is overriding the default.
  531. *
  532. * @var string
  533. *
  534. * @see EntityFieldQuery::execute().
  535. */
  536. public $executeCallback = '';
  537. /**
  538. * Adds a condition on entity-generic metadata.
  539. *
  540. * If the overall query contains only entity conditions or ordering, or if
  541. * there are property conditions, then specifying the entity type is
  542. * mandatory. If there are field conditions or ordering but no property
  543. * conditions or ordering, then specifying an entity type is optional. While
  544. * the field storage engine might support field conditions on more than one
  545. * entity type, there is no way to query across multiple entity base tables by
  546. * default. To specify the entity type, pass in 'entity_type' for $name,
  547. * the type as a string for $value, and no $operator (it's disregarded).
  548. *
  549. * 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
  550. *
  551. * Note: The "comment" and "taxonomy_term" entity types don't support bundle
  552. * conditions. For "taxonomy_term", propertyCondition('vid') can be used
  553. * instead.
  554. *
  555. * @param $name
  556. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  557. * @param $value
  558. * The value for $name. In most cases, this is a scalar. For more complex
  559. * options, it is an array. The meaning of each element in the array is
  560. * dependent on $operator.
  561. * @param $operator
  562. * Possible values:
  563. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  564. * operators expect $value to be a literal of the same type as the
  565. * column.
  566. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  567. * literals of the same type as the column.
  568. * - 'BETWEEN': This operator expects $value to be an array of two literals
  569. * of the same type as the column.
  570. * The operator can be omitted, and will default to 'IN' if the value is an
  571. * array, or to '=' otherwise.
  572. *
  573. * @return EntityFieldQuery
  574. * The called object.
  575. */
  576. public function entityCondition($name, $value, $operator = NULL) {
  577. // The '!=' operator is deprecated in favour of the '<>' operator since the
  578. // latter is ANSI SQL compatible.
  579. if ($operator == '!=') {
  580. $operator = '<>';
  581. }
  582. $this->entityConditions[$name] = array(
  583. 'value' => $value,
  584. 'operator' => $operator,
  585. );
  586. return $this;
  587. }
  588. /**
  589. * Adds a condition on field values.
  590. *
  591. * Note that entities with empty field values will be excluded from the
  592. * EntityFieldQuery results when using this method.
  593. *
  594. * @param $field
  595. * Either a field name or a field array.
  596. * @param $column
  597. * The column that should hold the value to be matched.
  598. * @param $value
  599. * The value to test the column value against.
  600. * @param $operator
  601. * The operator to be used to test the given value.
  602. * @param $delta_group
  603. * An arbitrary identifier: conditions in the same group must have the same
  604. * $delta_group.
  605. * @param $language_group
  606. * An arbitrary identifier: conditions in the same group must have the same
  607. * $language_group.
  608. *
  609. * @return EntityFieldQuery
  610. * The called object.
  611. *
  612. * @see EntityFieldQuery::addFieldCondition
  613. * @see EntityFieldQuery::deleted
  614. */
  615. public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  616. return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
  617. }
  618. /**
  619. * Adds a condition on the field language column.
  620. *
  621. * @param $field
  622. * Either a field name or a field array.
  623. * @param $value
  624. * The value to test the column value against.
  625. * @param $operator
  626. * The operator to be used to test the given value.
  627. * @param $delta_group
  628. * An arbitrary identifier: conditions in the same group must have the same
  629. * $delta_group.
  630. * @param $language_group
  631. * An arbitrary identifier: conditions in the same group must have the same
  632. * $language_group.
  633. *
  634. * @return EntityFieldQuery
  635. * The called object.
  636. *
  637. * @see EntityFieldQuery::addFieldCondition
  638. * @see EntityFieldQuery::deleted
  639. */
  640. public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  641. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
  642. }
  643. /**
  644. * Adds a condition on the field delta column.
  645. *
  646. * @param $field
  647. * Either a field name or a field array.
  648. * @param $value
  649. * The value to test the column value against.
  650. * @param $operator
  651. * The operator to be used to test the given value.
  652. * @param $delta_group
  653. * An arbitrary identifier: conditions in the same group must have the same
  654. * $delta_group.
  655. * @param $language_group
  656. * An arbitrary identifier: conditions in the same group must have the same
  657. * $language_group.
  658. *
  659. * @return EntityFieldQuery
  660. * The called object.
  661. *
  662. * @see EntityFieldQuery::addFieldCondition
  663. * @see EntityFieldQuery::deleted
  664. */
  665. public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  666. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
  667. }
  668. /**
  669. * Adds the given condition to the proper condition array.
  670. *
  671. * @param $conditions
  672. * A reference to an array of conditions.
  673. * @param $field
  674. * Either a field name or a field array.
  675. * @param $column
  676. * A column defined in the hook_field_schema() of this field. If this is
  677. * omitted then the query will find only entities that have data in this
  678. * field, using the entity and property conditions if there are any.
  679. * @param $value
  680. * The value to test the column value against. In most cases, this is a
  681. * scalar. For more complex options, it is an array. The meaning of each
  682. * element in the array is dependent on $operator.
  683. * @param $operator
  684. * Possible values:
  685. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  686. * operators expect $value to be a literal of the same type as the
  687. * column.
  688. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  689. * literals of the same type as the column.
  690. * - 'BETWEEN': This operator expects $value to be an array of two literals
  691. * of the same type as the column.
  692. * The operator can be omitted, and will default to 'IN' if the value is an
  693. * array, or to '=' otherwise.
  694. * @param $delta_group
  695. * An arbitrary identifier: conditions in the same group must have the same
  696. * $delta_group. For example, let's presume a multivalue field which has
  697. * two columns, 'color' and 'shape', and for entity id 1, there are two
  698. * values: red/square and blue/circle. Entity ID 1 does not have values
  699. * corresponding to 'red circle', however if you pass 'red' and 'circle' as
  700. * conditions, it will appear in the results - by default queries will run
  701. * against any combination of deltas. By passing the conditions with the
  702. * same $delta_group it will ensure that only values attached to the same
  703. * delta are matched, and entity 1 would then be excluded from the results.
  704. * @param $language_group
  705. * An arbitrary identifier: conditions in the same group must have the same
  706. * $language_group.
  707. *
  708. * @return EntityFieldQuery
  709. * The called object.
  710. */
  711. protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  712. // The '!=' operator is deprecated in favour of the '<>' operator since the
  713. // latter is ANSI SQL compatible.
  714. if ($operator == '!=') {
  715. $operator = '<>';
  716. }
  717. if (is_scalar($field)) {
  718. $field_definition = field_info_field($field);
  719. if (empty($field_definition)) {
  720. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  721. }
  722. $field = $field_definition;
  723. }
  724. // Ensure the same index is used for field conditions as for fields.
  725. $index = count($this->fields);
  726. $this->fields[$index] = $field;
  727. if (isset($column)) {
  728. $conditions[$index] = array(
  729. 'field' => $field,
  730. 'column' => $column,
  731. 'value' => $value,
  732. 'operator' => $operator,
  733. 'delta_group' => $delta_group,
  734. 'language_group' => $language_group,
  735. );
  736. }
  737. return $this;
  738. }
  739. /**
  740. * Adds a condition on an entity-specific property.
  741. *
  742. * An $entity_type must be specified by calling
  743. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  744. * executing the query. Also, by default only entities stored in SQL are
  745. * supported; however, EntityFieldQuery::executeCallback can be set to handle
  746. * different entity storage.
  747. *
  748. * @param $column
  749. * A column defined in the hook_schema() of the base table of the entity.
  750. * @param $value
  751. * The value to test the field against. In most cases, this is a scalar. For
  752. * more complex options, it is an array. The meaning of each element in the
  753. * array is dependent on $operator.
  754. * @param $operator
  755. * Possible values:
  756. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  757. * operators expect $value to be a literal of the same type as the
  758. * column.
  759. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  760. * literals of the same type as the column.
  761. * - 'BETWEEN': This operator expects $value to be an array of two literals
  762. * of the same type as the column.
  763. * The operator can be omitted, and will default to 'IN' if the value is an
  764. * array, or to '=' otherwise.
  765. *
  766. * @return EntityFieldQuery
  767. * The called object.
  768. */
  769. public function propertyCondition($column, $value, $operator = NULL) {
  770. // The '!=' operator is deprecated in favour of the '<>' operator since the
  771. // latter is ANSI SQL compatible.
  772. if ($operator == '!=') {
  773. $operator = '<>';
  774. }
  775. $this->propertyConditions[] = array(
  776. 'column' => $column,
  777. 'value' => $value,
  778. 'operator' => $operator,
  779. );
  780. return $this;
  781. }
  782. /**
  783. * Orders the result set by entity-generic metadata.
  784. *
  785. * If called multiple times, the query will order by each specified column in
  786. * the order this method is called.
  787. *
  788. * Note: The "comment" and "taxonomy_term" entity types don't support ordering
  789. * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
  790. *
  791. * @param $name
  792. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  793. * @param $direction
  794. * The direction to sort. Legal values are "ASC" and "DESC".
  795. *
  796. * @return EntityFieldQuery
  797. * The called object.
  798. */
  799. public function entityOrderBy($name, $direction = 'ASC') {
  800. $this->order[] = array(
  801. 'type' => 'entity',
  802. 'specifier' => $name,
  803. 'direction' => $direction,
  804. );
  805. return $this;
  806. }
  807. /**
  808. * Orders the result set by a given field column.
  809. *
  810. * If called multiple times, the query will order by each specified column in
  811. * the order this method is called. Note that entities with empty field
  812. * values will be excluded from the EntityFieldQuery results when using this
  813. * method.
  814. *
  815. * @param $field
  816. * Either a field name or a field array.
  817. * @param $column
  818. * A column defined in the hook_field_schema() of this field. entity_id and
  819. * bundle can also be used.
  820. * @param $direction
  821. * The direction to sort. Legal values are "ASC" and "DESC".
  822. *
  823. * @return EntityFieldQuery
  824. * The called object.
  825. */
  826. public function fieldOrderBy($field, $column, $direction = 'ASC') {
  827. if (is_scalar($field)) {
  828. $field_definition = field_info_field($field);
  829. if (empty($field_definition)) {
  830. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  831. }
  832. $field = $field_definition;
  833. }
  834. // Save the index used for the new field, for later use in field storage.
  835. $index = count($this->fields);
  836. $this->fields[$index] = $field;
  837. $this->order[] = array(
  838. 'type' => 'field',
  839. 'specifier' => array(
  840. 'field' => $field,
  841. 'index' => $index,
  842. 'column' => $column,
  843. ),
  844. 'direction' => $direction,
  845. );
  846. return $this;
  847. }
  848. /**
  849. * Orders the result set by an entity-specific property.
  850. *
  851. * An $entity_type must be specified by calling
  852. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  853. * executing the query.
  854. *
  855. * If called multiple times, the query will order by each specified column in
  856. * the order this method is called.
  857. *
  858. * @param $column
  859. * The column on which to order.
  860. * @param $direction
  861. * The direction to sort. Legal values are "ASC" and "DESC".
  862. *
  863. * @return EntityFieldQuery
  864. * The called object.
  865. */
  866. public function propertyOrderBy($column, $direction = 'ASC') {
  867. $this->order[] = array(
  868. 'type' => 'property',
  869. 'specifier' => $column,
  870. 'direction' => $direction,
  871. );
  872. return $this;
  873. }
  874. /**
  875. * Sets the query to be a count query only.
  876. *
  877. * @return EntityFieldQuery
  878. * The called object.
  879. */
  880. public function count() {
  881. $this->count = TRUE;
  882. return $this;
  883. }
  884. /**
  885. * Restricts a query to a given range in the result set.
  886. *
  887. * @param $start
  888. * The first entity from the result set to return. If NULL, removes any
  889. * range directives that are set.
  890. * @param $length
  891. * The number of entities to return from the result set.
  892. *
  893. * @return EntityFieldQuery
  894. * The called object.
  895. */
  896. public function range($start = NULL, $length = NULL) {
  897. $this->range = array(
  898. 'start' => $start,
  899. 'length' => $length,
  900. );
  901. return $this;
  902. }
  903. /**
  904. * Enable a pager for the query.
  905. *
  906. * @param $limit
  907. * An integer specifying the number of elements per page. If passed a false
  908. * value (FALSE, 0, NULL), the pager is disabled.
  909. * @param $element
  910. * An optional integer to distinguish between multiple pagers on one page.
  911. * If not provided, one is automatically calculated.
  912. *
  913. * @return EntityFieldQuery
  914. * The called object.
  915. */
  916. public function pager($limit = 10, $element = NULL) {
  917. if (!isset($element)) {
  918. $element = PagerDefault::$maxElement++;
  919. }
  920. elseif ($element >= PagerDefault::$maxElement) {
  921. PagerDefault::$maxElement = $element + 1;
  922. }
  923. $this->pager = array(
  924. 'limit' => $limit,
  925. 'element' => $element,
  926. );
  927. return $this;
  928. }
  929. /**
  930. * Enable sortable tables for this query.
  931. *
  932. * @param $headers
  933. * An EFQ Header array based on which the order clause is added to the query.
  934. *
  935. * @return EntityFieldQuery
  936. * The called object.
  937. */
  938. public function tableSort(&$headers) {
  939. // If 'field' is not initialized, the header columns aren't clickable
  940. foreach ($headers as $key =>$header) {
  941. if (is_array($header) && isset($header['specifier'])) {
  942. $headers[$key]['field'] = '';
  943. }
  944. }
  945. $order = tablesort_get_order($headers);
  946. $direction = tablesort_get_sort($headers);
  947. foreach ($headers as $header) {
  948. if (is_array($header) && ($header['data'] == $order['name'])) {
  949. if ($header['type'] == 'field') {
  950. $this->fieldOrderBy($header['specifier']['field'], $header['specifier']['column'], $direction);
  951. }
  952. else {
  953. $header['direction'] = $direction;
  954. $this->order[] = $header;
  955. }
  956. }
  957. }
  958. return $this;
  959. }
  960. /**
  961. * Filters on the data being deleted.
  962. *
  963. * @param $deleted
  964. * TRUE to only return deleted data, FALSE to return non-deleted data,
  965. * EntityFieldQuery::RETURN_ALL to return everything. Defaults to FALSE.
  966. *
  967. * @return EntityFieldQuery
  968. * The called object.
  969. */
  970. public function deleted($deleted = TRUE) {
  971. $this->deleted = $deleted;
  972. return $this;
  973. }
  974. /**
  975. * Queries the current or every revision.
  976. *
  977. * Note that this only affects field conditions. Property conditions always
  978. * apply to the current revision.
  979. * @TODO: Once revision tables have been cleaned up, revisit this.
  980. *
  981. * @param $age
  982. * - FIELD_LOAD_CURRENT (default): Query the most recent revisions for all
  983. * entities. The results will be keyed by entity type and entity ID.
  984. * - FIELD_LOAD_REVISION: Query all revisions. The results will be keyed by
  985. * entity type and entity revision ID.
  986. *
  987. * @return EntityFieldQuery
  988. * The called object.
  989. */
  990. public function age($age) {
  991. $this->age = $age;
  992. return $this;
  993. }
  994. /**
  995. * Adds a tag to the query.
  996. *
  997. * Tags are strings that mark a query so that hook_query_alter() and
  998. * hook_query_TAG_alter() implementations may decide if they wish to alter
  999. * the query. A query may have any number of tags, and they must be valid PHP
  1000. * identifiers (composed of letters, numbers, and underscores). For example,
  1001. * queries involving nodes that will be displayed for a user need to add the
  1002. * tag 'node_access', so that the node module can add access restrictions to
  1003. * the query.
  1004. *
  1005. * If an entity field query has tags, it must also have an entity type
  1006. * specified, because the alter hook will need the entity base table.
  1007. *
  1008. * @param string $tag
  1009. * The tag to add.
  1010. *
  1011. * @return EntityFieldQuery
  1012. * The called object.
  1013. */
  1014. public function addTag($tag) {
  1015. $this->tags[$tag] = $tag;
  1016. return $this;
  1017. }
  1018. /**
  1019. * Adds additional metadata to the query.
  1020. *
  1021. * Sometimes a query may need to provide additional contextual data for the
  1022. * alter hook. The alter hook implementations may then use that information
  1023. * to decide if and how to take action.
  1024. *
  1025. * @param $key
  1026. * The unique identifier for this piece of metadata. Must be a string that
  1027. * follows the same rules as any other PHP identifier.
  1028. * @param $object
  1029. * The additional data to add to the query. May be any valid PHP variable.
  1030. *
  1031. * @return EntityFieldQuery
  1032. * The called object.
  1033. */
  1034. public function addMetaData($key, $object) {
  1035. $this->metaData[$key] = $object;
  1036. return $this;
  1037. }
  1038. /**
  1039. * Executes the query.
  1040. *
  1041. * After executing the query, $this->orderedResults will contain a list of
  1042. * the same stub entities in the order returned by the query. This is only
  1043. * relevant if there are multiple entity types in the returned value and
  1044. * a field ordering was requested. In every other case, the returned value
  1045. * contains everything necessary for processing.
  1046. *
  1047. * @return
  1048. * Either a number if count() was called or an array of associative arrays
  1049. * of stub entities. The outer array keys are entity types, and the inner
  1050. * array keys are the relevant ID. (In most cases this will be the entity
  1051. * ID. The only exception is when age=FIELD_LOAD_REVISION is used and field
  1052. * conditions or sorts are present -- in this case, the key will be the
  1053. * revision ID.) The entity type will only exist in the outer array if
  1054. * results were found. The inner array values are always stub entities, as
  1055. * returned by entity_create_stub_entity(). To traverse the returned array:
  1056. * @code
  1057. * foreach ($query->execute() as $entity_type => $entities) {
  1058. * foreach ($entities as $entity_id => $entity) {
  1059. * @endcode
  1060. * Note if the entity type is known, then the following snippet will load
  1061. * the entities found:
  1062. * @code
  1063. * $result = $query->execute();
  1064. * if (!empty($result[$my_type])) {
  1065. * $entities = entity_load($my_type, array_keys($result[$my_type]));
  1066. * }
  1067. * @endcode
  1068. */
  1069. public function execute() {
  1070. // Give a chance to other modules to alter the query.
  1071. drupal_alter('entity_query', $this);
  1072. $this->altered = TRUE;
  1073. // Initialize the pager.
  1074. $this->initializePager();
  1075. // Execute the query using the correct callback.
  1076. $result = call_user_func($this->queryCallback(), $this);
  1077. return $result;
  1078. }
  1079. /**
  1080. * Determines the query callback to use for this entity query.
  1081. *
  1082. * @return
  1083. * A callback that can be used with call_user_func().
  1084. */
  1085. public function queryCallback() {
  1086. // Use the override from $this->executeCallback. It can be set either
  1087. // while building the query, or using hook_entity_query_alter().
  1088. if (function_exists($this->executeCallback)) {
  1089. return $this->executeCallback;
  1090. }
  1091. // If there are no field conditions and sorts, and no execute callback
  1092. // then we default to querying entity tables in SQL.
  1093. if (empty($this->fields)) {
  1094. return array($this, 'propertyQuery');
  1095. }
  1096. // If no override, find the storage engine to be used.
  1097. foreach ($this->fields as $field) {
  1098. if (!isset($storage)) {
  1099. $storage = $field['storage']['module'];
  1100. }
  1101. elseif ($storage != $field['storage']['module']) {
  1102. throw new EntityFieldQueryException(t("Can't handle more than one field storage engine"));
  1103. }
  1104. }
  1105. if ($storage) {
  1106. // Use hook_field_storage_query() from the field storage.
  1107. return $storage . '_field_storage_query';
  1108. }
  1109. else {
  1110. throw new EntityFieldQueryException(t("Field storage engine not found."));
  1111. }
  1112. }
  1113. /**
  1114. * Queries entity tables in SQL for property conditions and sorts.
  1115. *
  1116. * This method is only used if there are no field conditions and sorts.
  1117. *
  1118. * @return
  1119. * See EntityFieldQuery::execute().
  1120. */
  1121. protected function propertyQuery() {
  1122. if (empty($this->entityConditions['entity_type'])) {
  1123. throw new EntityFieldQueryException(t('For this query an entity type must be specified.'));
  1124. }
  1125. $entity_type = $this->entityConditions['entity_type']['value'];
  1126. $entity_info = entity_get_info($entity_type);
  1127. if (empty($entity_info['base table'])) {
  1128. throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
  1129. }
  1130. $base_table = $entity_info['base table'];
  1131. $base_table_schema = drupal_get_schema($base_table);
  1132. $select_query = db_select($base_table);
  1133. $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
  1134. // Process the property conditions.
  1135. foreach ($this->propertyConditions as $property_condition) {
  1136. $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
  1137. }
  1138. // Process the four possible entity condition.
  1139. // The id field is always present in entity keys.
  1140. $sql_field = $entity_info['entity keys']['id'];
  1141. $id_map['entity_id'] = $sql_field;
  1142. $select_query->addField($base_table, $sql_field, 'entity_id');
  1143. if (isset($this->entityConditions['entity_id'])) {
  1144. $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['entity_id']);
  1145. }
  1146. // If there is a revision key defined, use it.
  1147. if (!empty($entity_info['entity keys']['revision'])) {
  1148. $sql_field = $entity_info['entity keys']['revision'];
  1149. $select_query->addField($base_table, $sql_field, 'revision_id');
  1150. if (isset($this->entityConditions['revision_id'])) {
  1151. $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['revision_id']);
  1152. }
  1153. }
  1154. else {
  1155. $sql_field = 'revision_id';
  1156. $select_query->addExpression('NULL', 'revision_id');
  1157. }
  1158. $id_map['revision_id'] = $sql_field;
  1159. // Handle bundles.
  1160. if (!empty($entity_info['entity keys']['bundle'])) {
  1161. $sql_field = $entity_info['entity keys']['bundle'];
  1162. $having = FALSE;
  1163. if (!empty($base_table_schema['fields'][$sql_field])) {
  1164. $select_query->addField($base_table, $sql_field, 'bundle');
  1165. }
  1166. }
  1167. else {
  1168. $sql_field = 'bundle';
  1169. $select_query->addExpression(':bundle', 'bundle', array(':bundle' => $entity_type));
  1170. $having = TRUE;
  1171. }
  1172. $id_map['bundle'] = $sql_field;
  1173. if (isset($this->entityConditions['bundle'])) {
  1174. if (!empty($entity_info['entity keys']['bundle'])) {
  1175. $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['bundle'], $having);
  1176. }
  1177. else {
  1178. // This entity has no bundle, so invalidate the query.
  1179. $select_query->where('1 = 0');
  1180. }
  1181. }
  1182. // Order the query.
  1183. foreach ($this->order as $order) {
  1184. if ($order['type'] == 'entity') {
  1185. $key = $order['specifier'];
  1186. if (!isset($id_map[$key])) {
  1187. throw new EntityFieldQueryException(t('Do not know how to order on @key for @entity_type', array('@key' => $key, '@entity_type' => $entity_type)));
  1188. }
  1189. $select_query->orderBy($id_map[$key], $order['direction']);
  1190. }
  1191. elseif ($order['type'] == 'property') {
  1192. $select_query->orderBy($base_table . '.' . $order['specifier'], $order['direction']);
  1193. }
  1194. }
  1195. return $this->finishQuery($select_query);
  1196. }
  1197. /**
  1198. * Get the total number of results and initialize a pager for the query.
  1199. *
  1200. * The pager can be disabled by either setting the pager limit to 0, or by
  1201. * setting this query to be a count query.
  1202. */
  1203. function initializePager() {
  1204. if ($this->pager && !empty($this->pager['limit']) && !$this->count) {
  1205. $page = pager_find_page($this->pager['element']);
  1206. $count_query = clone $this;
  1207. $this->pager['total'] = $count_query->count()->execute();
  1208. $this->pager['start'] = $page * $this->pager['limit'];
  1209. pager_default_initialize($this->pager['total'], $this->pager['limit'], $this->pager['element']);
  1210. $this->range($this->pager['start'], $this->pager['limit']);
  1211. }
  1212. }
  1213. /**
  1214. * Finishes the query.
  1215. *
  1216. * Adds tags, metaData, range and returns the requested list or count.
  1217. *
  1218. * @param SelectQuery $select_query
  1219. * A SelectQuery which has entity_type, entity_id, revision_id and bundle
  1220. * fields added.
  1221. * @param $id_key
  1222. * Which field's values to use as the returned array keys.
  1223. *
  1224. * @return
  1225. * See EntityFieldQuery::execute().
  1226. */
  1227. function finishQuery($select_query, $id_key = 'entity_id') {
  1228. foreach ($this->tags as $tag) {
  1229. $select_query->addTag($tag);
  1230. }
  1231. foreach ($this->metaData as $key => $object) {
  1232. $select_query->addMetaData($key, $object);
  1233. }
  1234. $select_query->addMetaData('entity_field_query', $this);
  1235. if ($this->range) {
  1236. $select_query->range($this->range['start'], $this->range['length']);
  1237. }
  1238. if ($this->count) {
  1239. return $select_query->countQuery()->execute()->fetchField();
  1240. }
  1241. $return = array();
  1242. foreach ($select_query->execute() as $partial_entity) {
  1243. $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
  1244. $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
  1245. $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
  1246. $this->ordered_results[] = $partial_entity;
  1247. }
  1248. return $return;
  1249. }
  1250. /**
  1251. * Adds a condition to an already built SelectQuery (internal function).
  1252. *
  1253. * This is a helper for hook_entity_query() and hook_field_storage_query().
  1254. *
  1255. * @param SelectQuery $select_query
  1256. * A SelectQuery object.
  1257. * @param $sql_field
  1258. * The name of the field.
  1259. * @param $condition
  1260. * A condition as described in EntityFieldQuery::fieldCondition() and
  1261. * EntityFieldQuery::entityCondition().
  1262. * @param $having
  1263. * HAVING or WHERE. This is necessary because SQL can't handle WHERE
  1264. * conditions on aliased columns.
  1265. */
  1266. public function addCondition(SelectQuery $select_query, $sql_field, $condition, $having = FALSE) {
  1267. $method = $having ? 'havingCondition' : 'condition';
  1268. $like_prefix = '';
  1269. switch ($condition['operator']) {
  1270. case 'CONTAINS':
  1271. $like_prefix = '%';
  1272. case 'STARTS_WITH':
  1273. $select_query->$method($sql_field, $like_prefix . db_like($condition['value']) . '%', 'LIKE');
  1274. break;
  1275. default:
  1276. $select_query->$method($sql_field, $condition['value'], $condition['operator']);
  1277. }
  1278. }
  1279. }
  1280. /**
  1281. * Exception thrown when a malformed entity is passed.
  1282. */
  1283. class EntityMalformedException extends Exception { }