Skip navigation
Help

entity.inc

  1. drupal
    1. 7 drupal/includes/entity.inc

Classes

NameDescription
DrupalDefaultEntityControllerDefault implementation of DrupalEntityControllerInterface.
EntityFieldQueryRetrieves entities matching a given set of conditions.
EntityFieldQueryExceptionException thrown by EntityFieldQuery() on unsupported query syntax.
EntityMalformedExceptionException thrown when a malformed entity is passed.

Interfaces

NameDescription
DrupalEntityControllerInterfaceInterface for entity controller classes.

File

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