entity.inc 46 KB

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