entity.inc 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  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. *
  277. * This will attach fields, if the entity is fieldable. It calls
  278. * hook_entity_load() for modules which need to add data to all entities.
  279. * It also calls hook_TYPE_load() on the loaded entities. For example
  280. * hook_node_load() or hook_user_load(). If your hook_TYPE_load()
  281. * expects special parameters apart from the queried entities, you can set
  282. * $this->hookLoadArguments prior to calling the method.
  283. * See NodeController::attachLoad() for an example.
  284. *
  285. * @param $queried_entities
  286. * Associative array of query results, keyed on the entity ID.
  287. * @param $revision_id
  288. * ID of the revision that was loaded, or FALSE if the most current revision
  289. * was loaded.
  290. */
  291. protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
  292. // Attach fields.
  293. if ($this->entityInfo['fieldable']) {
  294. if ($revision_id) {
  295. field_attach_load_revision($this->entityType, $queried_entities);
  296. }
  297. else {
  298. field_attach_load($this->entityType, $queried_entities);
  299. }
  300. }
  301. // Call hook_entity_load().
  302. foreach (module_implements('entity_load') as $module) {
  303. $function = $module . '_entity_load';
  304. $function($queried_entities, $this->entityType);
  305. }
  306. // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
  307. // always the queried entities, followed by additional arguments set in
  308. // $this->hookLoadArguments.
  309. $args = array_merge(array($queried_entities), $this->hookLoadArguments);
  310. foreach (module_implements($this->entityInfo['load hook']) as $module) {
  311. call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
  312. }
  313. }
  314. /**
  315. * Gets entities from the static cache.
  316. *
  317. * @param $ids
  318. * If not empty, return entities that match these IDs.
  319. * @param $conditions
  320. * If set, return entities that match all of these conditions.
  321. *
  322. * @return
  323. * Array of entities from the entity cache.
  324. */
  325. protected function cacheGet($ids, $conditions = array()) {
  326. $entities = array();
  327. // Load any available entities from the internal cache.
  328. if (!empty($this->entityCache)) {
  329. if ($ids) {
  330. $entities += array_intersect_key($this->entityCache, array_flip($ids));
  331. }
  332. // If loading entities only by conditions, fetch all available entities
  333. // from the cache. Entities which don't match are removed later.
  334. elseif ($conditions) {
  335. $entities = $this->entityCache;
  336. }
  337. }
  338. // Exclude any entities loaded from cache if they don't match $conditions.
  339. // This ensures the same behavior whether loading from memory or database.
  340. if ($conditions) {
  341. foreach ($entities as $entity) {
  342. $entity_values = (array) $entity;
  343. if (array_diff_assoc($conditions, $entity_values)) {
  344. unset($entities[$entity->{$this->idKey}]);
  345. }
  346. }
  347. }
  348. return $entities;
  349. }
  350. /**
  351. * Stores entities in the static entity cache.
  352. *
  353. * @param $entities
  354. * Entities to store in the cache.
  355. */
  356. protected function cacheSet($entities) {
  357. $this->entityCache += $entities;
  358. }
  359. }
  360. /**
  361. * Exception thrown by EntityFieldQuery() on unsupported query syntax.
  362. *
  363. * Some storage modules might not support the full range of the syntax for
  364. * conditions, and will raise an EntityFieldQueryException when an unsupported
  365. * condition was specified.
  366. */
  367. class EntityFieldQueryException extends Exception {}
  368. /**
  369. * Retrieves entities matching a given set of conditions.
  370. *
  371. * This class allows finding entities based on entity properties (for example,
  372. * node->changed), field values, and generic entity meta data (bundle,
  373. * entity type, entity id, and revision ID). It is not possible to query across
  374. * multiple entity types. For example, there is no facility to find published
  375. * nodes written by users created in the last hour, as this would require
  376. * querying both node->status and user->created.
  377. *
  378. * Normally we would not want to have public properties on the object, as that
  379. * allows the object's state to become inconsistent too easily. However, this
  380. * class's standard use case involves primarily code that does need to have
  381. * direct access to the collected properties in order to handle alternate
  382. * execution routines. We therefore use public properties for simplicity. Note
  383. * that code that is simply creating and running a field query should still use
  384. * the appropriate methods to add conditions on the query.
  385. *
  386. * Storage engines are not required to support every type of query. By default,
  387. * an EntityFieldQueryException will be raised if an unsupported condition is
  388. * specified or if the query has field conditions or sorts that are stored in
  389. * different field storage engines. However, this logic can be overridden in
  390. * hook_entity_query_alter().
  391. *
  392. * Also note that this query does not automatically respect entity access
  393. * restrictions. Node access control is performed by the SQL storage engine but
  394. * other storage engines might not do this.
  395. */
  396. class EntityFieldQuery {
  397. /**
  398. * Indicates that both deleted and non-deleted fields should be returned.
  399. *
  400. * @see EntityFieldQuery::deleted()
  401. */
  402. const RETURN_ALL = NULL;
  403. /**
  404. * TRUE if the query has already been altered, FALSE if it hasn't.
  405. *
  406. * Used in alter hooks to check for cloned queries that have already been
  407. * altered prior to the clone (for example, the pager count query).
  408. *
  409. * @var boolean
  410. */
  411. public $altered = FALSE;
  412. /**
  413. * Associative array of entity-generic metadata conditions.
  414. *
  415. * @var array
  416. *
  417. * @see EntityFieldQuery::entityCondition()
  418. */
  419. public $entityConditions = array();
  420. /**
  421. * List of field conditions.
  422. *
  423. * @var array
  424. *
  425. * @see EntityFieldQuery::fieldCondition()
  426. */
  427. public $fieldConditions = array();
  428. /**
  429. * List of field meta conditions (language and delta).
  430. *
  431. * Field conditions operate on columns specified by hook_field_schema(),
  432. * the meta conditions operate on columns added by the system: delta
  433. * and language. These can not be mixed with the field conditions because
  434. * field columns can have any name including delta and language.
  435. *
  436. * @var array
  437. *
  438. * @see EntityFieldQuery::fieldLanguageCondition()
  439. * @see EntityFieldQuery::fieldDeltaCondition()
  440. */
  441. public $fieldMetaConditions = array();
  442. /**
  443. * List of property conditions.
  444. *
  445. * @var array
  446. *
  447. * @see EntityFieldQuery::propertyCondition()
  448. */
  449. public $propertyConditions = array();
  450. /**
  451. * List of order clauses.
  452. *
  453. * @var array
  454. */
  455. public $order = array();
  456. /**
  457. * The query range.
  458. *
  459. * @var array
  460. *
  461. * @see EntityFieldQuery::range()
  462. */
  463. public $range = array();
  464. /**
  465. * The query pager data.
  466. *
  467. * @var array
  468. *
  469. * @see EntityFieldQuery::pager()
  470. */
  471. public $pager = array();
  472. /**
  473. * Query behavior for deleted data.
  474. *
  475. * TRUE to return only deleted data, FALSE to return only non-deleted data,
  476. * EntityFieldQuery::RETURN_ALL to return everything.
  477. *
  478. * @see EntityFieldQuery::deleted()
  479. */
  480. public $deleted = FALSE;
  481. /**
  482. * A list of field arrays used.
  483. *
  484. * Field names passed to EntityFieldQuery::fieldCondition() and
  485. * EntityFieldQuery::fieldOrderBy() are run through field_info_field() before
  486. * stored in this array. This way, the elements of this array are field
  487. * arrays.
  488. *
  489. * @var array
  490. */
  491. public $fields = array();
  492. /**
  493. * TRUE if this is a count query, FALSE if it isn't.
  494. *
  495. * @var boolean
  496. */
  497. public $count = FALSE;
  498. /**
  499. * Flag indicating whether this is querying current or all revisions.
  500. *
  501. * @var int
  502. *
  503. * @see EntityFieldQuery::age()
  504. */
  505. public $age = FIELD_LOAD_CURRENT;
  506. /**
  507. * A list of the tags added to this query.
  508. *
  509. * @var array
  510. *
  511. * @see EntityFieldQuery::addTag()
  512. */
  513. public $tags = array();
  514. /**
  515. * A list of metadata added to this query.
  516. *
  517. * @var array
  518. *
  519. * @see EntityFieldQuery::addMetaData()
  520. */
  521. public $metaData = array();
  522. /**
  523. * The ordered results.
  524. *
  525. * @var array
  526. *
  527. * @see EntityFieldQuery::execute().
  528. */
  529. public $orderedResults = array();
  530. /**
  531. * The method executing the query, if it is overriding the default.
  532. *
  533. * @var string
  534. *
  535. * @see EntityFieldQuery::execute().
  536. */
  537. public $executeCallback = '';
  538. /**
  539. * Adds a condition on entity-generic metadata.
  540. *
  541. * If the overall query contains only entity conditions or ordering, or if
  542. * there are property conditions, then specifying the entity type is
  543. * mandatory. If there are field conditions or ordering but no property
  544. * conditions or ordering, then specifying an entity type is optional. While
  545. * the field storage engine might support field conditions on more than one
  546. * entity type, there is no way to query across multiple entity base tables by
  547. * default. To specify the entity type, pass in 'entity_type' for $name,
  548. * the type as a string for $value, and no $operator (it's disregarded).
  549. *
  550. * 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
  551. *
  552. * Note: The "comment" entity type does not support bundle conditions.
  553. *
  554. * @param $name
  555. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  556. * @param $value
  557. * The value for $name. In most cases, this is a scalar. For more complex
  558. * options, it is an array. The meaning of each element in the array is
  559. * dependent on $operator.
  560. * @param $operator
  561. * Possible values:
  562. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  563. * operators expect $value to be a literal of the same type as the
  564. * column.
  565. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  566. * literals of the same type as the column.
  567. * - 'BETWEEN': This operator expects $value to be an array of two literals
  568. * of the same type as the column.
  569. * The operator can be omitted, and will default to 'IN' if the value is an
  570. * array, or to '=' otherwise.
  571. *
  572. * @return EntityFieldQuery
  573. * The called object.
  574. */
  575. public function entityCondition($name, $value, $operator = NULL) {
  576. // The '!=' operator is deprecated in favour of the '<>' operator since the
  577. // latter is ANSI SQL compatible.
  578. if ($operator == '!=') {
  579. $operator = '<>';
  580. }
  581. $this->entityConditions[$name] = array(
  582. 'value' => $value,
  583. 'operator' => $operator,
  584. );
  585. return $this;
  586. }
  587. /**
  588. * Adds a condition on field values.
  589. *
  590. * Note that entities with empty field values will be excluded from the
  591. * EntityFieldQuery results when using this method.
  592. *
  593. * @param $field
  594. * Either a field name or a field array.
  595. * @param $column
  596. * The column that should hold the value to be matched.
  597. * @param $value
  598. * The value to test the column value against.
  599. * @param $operator
  600. * The operator to be used to test the given value.
  601. * @param $delta_group
  602. * An arbitrary identifier: conditions in the same group must have the same
  603. * $delta_group.
  604. * @param $language_group
  605. * An arbitrary identifier: conditions in the same group must have the same
  606. * $language_group.
  607. *
  608. * @return EntityFieldQuery
  609. * The called object.
  610. *
  611. * @see EntityFieldQuery::addFieldCondition
  612. * @see EntityFieldQuery::deleted
  613. */
  614. public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  615. return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
  616. }
  617. /**
  618. * Adds a condition on the field language column.
  619. *
  620. * @param $field
  621. * Either a field name or a field array.
  622. * @param $value
  623. * The value to test the column value against.
  624. * @param $operator
  625. * The operator to be used to test the given value.
  626. * @param $delta_group
  627. * An arbitrary identifier: conditions in the same group must have the same
  628. * $delta_group.
  629. * @param $language_group
  630. * An arbitrary identifier: conditions in the same group must have the same
  631. * $language_group.
  632. *
  633. * @return EntityFieldQuery
  634. * The called object.
  635. *
  636. * @see EntityFieldQuery::addFieldCondition
  637. * @see EntityFieldQuery::deleted
  638. */
  639. public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  640. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
  641. }
  642. /**
  643. * Adds a condition on the field delta column.
  644. *
  645. * @param $field
  646. * Either a field name or a field array.
  647. * @param $value
  648. * The value to test the column value against.
  649. * @param $operator
  650. * The operator to be used to test the given value.
  651. * @param $delta_group
  652. * An arbitrary identifier: conditions in the same group must have the same
  653. * $delta_group.
  654. * @param $language_group
  655. * An arbitrary identifier: conditions in the same group must have the same
  656. * $language_group.
  657. *
  658. * @return EntityFieldQuery
  659. * The called object.
  660. *
  661. * @see EntityFieldQuery::addFieldCondition
  662. * @see EntityFieldQuery::deleted
  663. */
  664. public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  665. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
  666. }
  667. /**
  668. * Adds the given condition to the proper condition array.
  669. *
  670. * @param $conditions
  671. * A reference to an array of conditions.
  672. * @param $field
  673. * Either a field name or a field array.
  674. * @param $column
  675. * A column defined in the hook_field_schema() of this field. If this is
  676. * omitted then the query will find only entities that have data in this
  677. * field, using the entity and property conditions if there are any.
  678. * @param $value
  679. * The value to test the column value against. In most cases, this is a
  680. * scalar. For more complex options, it is an array. The meaning of each
  681. * element in the array is dependent on $operator.
  682. * @param $operator
  683. * Possible values:
  684. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  685. * operators expect $value to be a literal of the same type as the
  686. * column.
  687. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  688. * literals of the same type as the column.
  689. * - 'BETWEEN': This operator expects $value to be an array of two literals
  690. * of the same type as the column.
  691. * The operator can be omitted, and will default to 'IN' if the value is an
  692. * array, or to '=' otherwise.
  693. * @param $delta_group
  694. * An arbitrary identifier: conditions in the same group must have the same
  695. * $delta_group. For example, let's presume a multivalue field which has
  696. * two columns, 'color' and 'shape', and for entity id 1, there are two
  697. * values: red/square and blue/circle. Entity ID 1 does not have values
  698. * corresponding to 'red circle', however if you pass 'red' and 'circle' as
  699. * conditions, it will appear in the results - by default queries will run
  700. * against any combination of deltas. By passing the conditions with the
  701. * same $delta_group it will ensure that only values attached to the same
  702. * delta are matched, and entity 1 would then be excluded from the results.
  703. * @param $language_group
  704. * An arbitrary identifier: conditions in the same group must have the same
  705. * $language_group.
  706. *
  707. * @return EntityFieldQuery
  708. * The called object.
  709. */
  710. protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  711. // The '!=' operator is deprecated in favour of the '<>' operator since the
  712. // latter is ANSI SQL compatible.
  713. if ($operator == '!=') {
  714. $operator = '<>';
  715. }
  716. if (is_scalar($field)) {
  717. $field_definition = field_info_field($field);
  718. if (empty($field_definition)) {
  719. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  720. }
  721. $field = $field_definition;
  722. }
  723. // Ensure the same index is used for field conditions as for fields.
  724. $index = count($this->fields);
  725. $this->fields[$index] = $field;
  726. if (isset($column)) {
  727. $conditions[$index] = array(
  728. 'field' => $field,
  729. 'column' => $column,
  730. 'value' => $value,
  731. 'operator' => $operator,
  732. 'delta_group' => $delta_group,
  733. 'language_group' => $language_group,
  734. );
  735. }
  736. return $this;
  737. }
  738. /**
  739. * Adds a condition on an entity-specific property.
  740. *
  741. * An $entity_type must be specified by calling
  742. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  743. * executing the query. Also, by default only entities stored in SQL are
  744. * supported; however, EntityFieldQuery::executeCallback can be set to handle
  745. * different entity storage.
  746. *
  747. * @param $column
  748. * A column defined in the hook_schema() of the base table of the entity.
  749. * @param $value
  750. * The value to test the field against. In most cases, this is a scalar. For
  751. * more complex options, it is an array. The meaning of each element in the
  752. * array is dependent on $operator.
  753. * @param $operator
  754. * Possible values:
  755. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  756. * operators expect $value to be a literal of the same type as the
  757. * column.
  758. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  759. * literals of the same type as the column.
  760. * - 'BETWEEN': This operator expects $value to be an array of two literals
  761. * of the same type as the column.
  762. * The operator can be omitted, and will default to 'IN' if the value is an
  763. * array, or to '=' otherwise.
  764. *
  765. * @return EntityFieldQuery
  766. * The called object.
  767. */
  768. public function propertyCondition($column, $value, $operator = NULL) {
  769. // The '!=' operator is deprecated in favour of the '<>' operator since the
  770. // latter is ANSI SQL compatible.
  771. if ($operator == '!=') {
  772. $operator = '<>';
  773. }
  774. $this->propertyConditions[] = array(
  775. 'column' => $column,
  776. 'value' => $value,
  777. 'operator' => $operator,
  778. );
  779. return $this;
  780. }
  781. /**
  782. * Orders the result set by entity-generic metadata.
  783. *
  784. * If called multiple times, the query will order by each specified column in
  785. * the order this method is called.
  786. *
  787. * Note: The "comment" and "taxonomy_term" entity types don't support ordering
  788. * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
  789. *
  790. * @param $name
  791. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  792. * @param $direction
  793. * The direction to sort. Legal values are "ASC" and "DESC".
  794. *
  795. * @return EntityFieldQuery
  796. * The called object.
  797. */
  798. public function entityOrderBy($name, $direction = 'ASC') {
  799. $this->order[] = array(
  800. 'type' => 'entity',
  801. 'specifier' => $name,
  802. 'direction' => $direction,
  803. );
  804. return $this;
  805. }
  806. /**
  807. * Orders the result set by a given field column.
  808. *
  809. * If called multiple times, the query will order by each specified column in
  810. * the order this method is called. Note that entities with empty field
  811. * values will be excluded from the EntityFieldQuery results when using this
  812. * method.
  813. *
  814. * @param $field
  815. * Either a field name or a field array.
  816. * @param $column
  817. * A column defined in the hook_field_schema() of this field. entity_id and
  818. * bundle can also be used.
  819. * @param $direction
  820. * The direction to sort. Legal values are "ASC" and "DESC".
  821. *
  822. * @return EntityFieldQuery
  823. * The called object.
  824. */
  825. public function fieldOrderBy($field, $column, $direction = 'ASC') {
  826. if (is_scalar($field)) {
  827. $field_definition = field_info_field($field);
  828. if (empty($field_definition)) {
  829. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  830. }
  831. $field = $field_definition;
  832. }
  833. // Save the index used for the new field, for later use in field storage.
  834. $index = count($this->fields);
  835. $this->fields[$index] = $field;
  836. $this->order[] = array(
  837. 'type' => 'field',
  838. 'specifier' => array(
  839. 'field' => $field,
  840. 'index' => $index,
  841. 'column' => $column,
  842. ),
  843. 'direction' => $direction,
  844. );
  845. return $this;
  846. }
  847. /**
  848. * Orders the result set by an entity-specific property.
  849. *
  850. * An $entity_type must be specified by calling
  851. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  852. * executing the query.
  853. *
  854. * If called multiple times, the query will order by each specified column in
  855. * the order this method is called.
  856. *
  857. * @param $column
  858. * The column on which to order.
  859. * @param $direction
  860. * The direction to sort. Legal values are "ASC" and "DESC".
  861. *
  862. * @return EntityFieldQuery
  863. * The called object.
  864. */
  865. public function propertyOrderBy($column, $direction = 'ASC') {
  866. $this->order[] = array(
  867. 'type' => 'property',
  868. 'specifier' => $column,
  869. 'direction' => $direction,
  870. );
  871. return $this;
  872. }
  873. /**
  874. * Sets the query to be a count query only.
  875. *
  876. * @return EntityFieldQuery
  877. * The called object.
  878. */
  879. public function count() {
  880. $this->count = TRUE;
  881. return $this;
  882. }
  883. /**
  884. * Restricts a query to a given range in the result set.
  885. *
  886. * @param $start
  887. * The first entity from the result set to return. If NULL, removes any
  888. * range directives that are set.
  889. * @param $length
  890. * The number of entities to return from the result set.
  891. *
  892. * @return EntityFieldQuery
  893. * The called object.
  894. */
  895. public function range($start = NULL, $length = NULL) {
  896. $this->range = array(
  897. 'start' => $start,
  898. 'length' => $length,
  899. );
  900. return $this;
  901. }
  902. /**
  903. * Enables a pager for the query.
  904. *
  905. * @param $limit
  906. * An integer specifying the number of elements per page. If passed a false
  907. * value (FALSE, 0, NULL), the pager is disabled.
  908. * @param $element
  909. * An optional integer to distinguish between multiple pagers on one page.
  910. * If not provided, one is automatically calculated.
  911. *
  912. * @return EntityFieldQuery
  913. * The called object.
  914. */
  915. public function pager($limit = 10, $element = NULL) {
  916. if (!isset($element)) {
  917. $element = PagerDefault::$maxElement++;
  918. }
  919. elseif ($element >= PagerDefault::$maxElement) {
  920. PagerDefault::$maxElement = $element + 1;
  921. }
  922. $this->pager = array(
  923. 'limit' => $limit,
  924. 'element' => $element,
  925. );
  926. return $this;
  927. }
  928. /**
  929. * Enables sortable tables for this query.
  930. *
  931. * @param $headers
  932. * An EFQ Header array based on which the order clause is added to the
  933. * 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. * Gets the total number of results and initializes 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. * Defines an exception thrown when a malformed entity is passed.
  1282. */
  1283. class EntityMalformedException extends Exception { }