entity.inc

  1. drupal
    1. 7 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

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 the 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::fieldDeltaCondition()
  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. * The operator can be omitted, and will default to 'IN' if the value is an
  560. * array, or to '=' otherwise.
  561. *
  562. * @return EntityFieldQuery
  563. * The called object.
  564. */
  565. public function entityCondition($name, $value, $operator = NULL) {
  566. // The '!=' operator is deprecated in favour of the '<>' operator since the
  567. // latter is ANSI SQL compatible.
  568. if ($operator == '!=') {
  569. $operator = '<>';
  570. }
  571. $this->entityConditions[$name] = array(
  572. 'value' => $value,
  573. 'operator' => $operator,
  574. );
  575. return $this;
  576. }
  577. /**
  578. * Adds a condition on field values.
  579. *
  580. * @param $field
  581. * Either a field name or a field array.
  582. * @param $column
  583. * The column that should hold the value to be matched.
  584. * @param $value
  585. * The value to test the column value against.
  586. * @param $operator
  587. * The operator to be used to test the given value.
  588. * @param $delta_group
  589. * An arbitrary identifier: conditions in the same group must have the same
  590. * $delta_group.
  591. * @param $language_group
  592. * An arbitrary identifier: conditions in the same group must have the same
  593. * $language_group.
  594. *
  595. * @return EntityFieldQuery
  596. * The called object.
  597. *
  598. * @see EntityFieldQuery::addFieldCondition
  599. * @see EntityFieldQuery::deleted
  600. */
  601. public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  602. return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
  603. }
  604. /**
  605. * Adds a condition on the field language column.
  606. *
  607. * @param $field
  608. * Either a field name or a field array.
  609. * @param $value
  610. * The value to test the column value against.
  611. * @param $operator
  612. * The operator to be used to test the given value.
  613. * @param $delta_group
  614. * An arbitrary identifier: conditions in the same group must have the same
  615. * $delta_group.
  616. * @param $language_group
  617. * An arbitrary identifier: conditions in the same group must have the same
  618. * $language_group.
  619. *
  620. * @return EntityFieldQuery
  621. * The called object.
  622. *
  623. * @see EntityFieldQuery::addFieldCondition
  624. * @see EntityFieldQuery::deleted
  625. */
  626. public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  627. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
  628. }
  629. /**
  630. * Adds a condition on the field delta column.
  631. *
  632. * @param $field
  633. * Either a field name or a field array.
  634. * @param $value
  635. * The value to test the column value against.
  636. * @param $operator
  637. * The operator to be used to test the given value.
  638. * @param $delta_group
  639. * An arbitrary identifier: conditions in the same group must have the same
  640. * $delta_group.
  641. * @param $language_group
  642. * An arbitrary identifier: conditions in the same group must have the same
  643. * $language_group.
  644. *
  645. * @return EntityFieldQuery
  646. * The called object.
  647. *
  648. * @see EntityFieldQuery::addFieldCondition
  649. * @see EntityFieldQuery::deleted
  650. */
  651. public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  652. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
  653. }
  654. /**
  655. * Adds the given condition to the proper condition array.
  656. *
  657. * @param $conditions
  658. * A reference to an array of conditions.
  659. * @param $field
  660. * Either a field name or a field array.
  661. * @param $column
  662. * A column defined in the hook_field_schema() of this field. If this is
  663. * omitted then the query will find only entities that have data in this
  664. * field, using the entity and property conditions if there are any.
  665. * @param $value
  666. * The value to test the column value against. In most cases, this is a
  667. * scalar. For more complex options, it is an array. The meaning of each
  668. * element in the array is dependent on $operator.
  669. * @param $operator
  670. * Possible values:
  671. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  672. * operators expect $value to be a literal of the same type as the
  673. * column.
  674. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  675. * literals of the same type as the column.
  676. * - 'BETWEEN': This operator expects $value to be an array of two literals
  677. * of the same type as the column.
  678. * The operator can be omitted, and will default to 'IN' if the value is an
  679. * array, or to '=' otherwise.
  680. * @param $delta_group
  681. * An arbitrary identifier: conditions in the same group must have the same
  682. * $delta_group. For example, let's presume a multivalue field which has
  683. * two columns, 'color' and 'shape', and for entity id 1, there are two
  684. * values: red/square and blue/circle. Entity ID 1 does not have values
  685. * corresponding to 'red circle', however if you pass 'red' and 'circle' as
  686. * conditions, it will appear in the results - by default queries will run
  687. * against any combination of deltas. By passing the conditions with the
  688. * same $delta_group it will ensure that only values attached to the same
  689. * delta are matched, and entity 1 would then be excluded from the results.
  690. * @param $language_group
  691. * An arbitrary identifier: conditions in the same group must have the same
  692. * $language_group.
  693. *
  694. * @return EntityFieldQuery
  695. * The called object.
  696. */
  697. protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  698. // The '!=' operator is deprecated in favour of the '<>' operator since the
  699. // latter is ANSI SQL compatible.
  700. if ($operator == '!=') {
  701. $operator = '<>';
  702. }
  703. if (is_scalar($field)) {
  704. $field_definition = field_info_field($field);
  705. if (empty($field_definition)) {
  706. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  707. }
  708. $field = $field_definition;
  709. }
  710. // Ensure the same index is used for field conditions as for fields.
  711. $index = count($this->fields);
  712. $this->fields[$index] = $field;
  713. if (isset($column)) {
  714. $conditions[$index] = array(
  715. 'field' => $field,
  716. 'column' => $column,
  717. 'value' => $value,
  718. 'operator' => $operator,
  719. 'delta_group' => $delta_group,
  720. 'language_group' => $language_group,
  721. );
  722. }
  723. return $this;
  724. }
  725. /**
  726. * Adds a condition on an entity-specific property.
  727. *
  728. * An $entity_type must be specified by calling
  729. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  730. * executing the query. Also, by default only entities stored in SQL are
  731. * supported; however, EntityFieldQuery::executeCallback can be set to handle
  732. * different entity storage.
  733. *
  734. * @param $column
  735. * A column defined in the hook_schema() of the base table of the entity.
  736. * @param $value
  737. * The value to test the field against. In most cases, this is a scalar. For
  738. * more complex options, it is an array. The meaning of each element in the
  739. * array is dependent on $operator.
  740. * @param $operator
  741. * Possible values:
  742. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  743. * operators expect $value to be a literal of the same type as the
  744. * column.
  745. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  746. * literals of the same type as the column.
  747. * - 'BETWEEN': This operator expects $value to be an array of two literals
  748. * of the same type as the column.
  749. * The operator can be omitted, and will default to 'IN' if the value is an
  750. * array, or to '=' otherwise.
  751. *
  752. * @return EntityFieldQuery
  753. * The called object.
  754. */
  755. public function propertyCondition($column, $value, $operator = NULL) {
  756. // The '!=' operator is deprecated in favour of the '<>' operator since the
  757. // latter is ANSI SQL compatible.
  758. if ($operator == '!=') {
  759. $operator = '<>';
  760. }
  761. $this->propertyConditions[] = array(
  762. 'column' => $column,
  763. 'value' => $value,
  764. 'operator' => $operator,
  765. );
  766. return $this;
  767. }
  768. /**
  769. * Orders the result set by entity-generic metadata.
  770. *
  771. * If called multiple times, the query will order by each specified column in
  772. * the order this method is called.
  773. *
  774. * Note: The "comment" and "taxonomy_term" entity types don't support ordering
  775. * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
  776. *
  777. * @param $name
  778. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  779. * @param $direction
  780. * The direction to sort. Legal values are "ASC" and "DESC".
  781. *
  782. * @return EntityFieldQuery
  783. * The called object.
  784. */
  785. public function entityOrderBy($name, $direction = 'ASC') {
  786. $this->order[] = array(
  787. 'type' => 'entity',
  788. 'specifier' => $name,
  789. 'direction' => $direction,
  790. );
  791. return $this;
  792. }
  793. /**
  794. * Orders the result set by a given field column.
  795. *
  796. * If called multiple times, the query will order by each specified column in
  797. * the order this method is called.
  798. *
  799. * @param $field
  800. * Either a field name or a field array.
  801. * @param $column
  802. * A column defined in the hook_field_schema() of this field. entity_id and
  803. * bundle can also be used.
  804. * @param $direction
  805. * The direction to sort. Legal values are "ASC" and "DESC".
  806. *
  807. * @return EntityFieldQuery
  808. * The called object.
  809. */
  810. public function fieldOrderBy($field, $column, $direction = 'ASC') {
  811. if (is_scalar($field)) {
  812. $field_definition = field_info_field($field);
  813. if (empty($field_definition)) {
  814. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  815. }
  816. $field = $field_definition;
  817. }
  818. // Save the index used for the new field, for later use in field storage.
  819. $index = count($this->fields);
  820. $this->fields[$index] = $field;
  821. $this->order[] = array(
  822. 'type' => 'field',
  823. 'specifier' => array(
  824. 'field' => $field,
  825. 'index' => $index,
  826. 'column' => $column,
  827. ),
  828. 'direction' => $direction,
  829. );
  830. return $this;
  831. }
  832. /**
  833. * Orders the result set by an entity-specific property.
  834. *
  835. * An $entity_type must be specified by calling
  836. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  837. * executing the query.
  838. *
  839. * If called multiple times, the query will order by each specified column in
  840. * the order this method is called.
  841. *
  842. * @param $column
  843. * The column on which to order.
  844. * @param $direction
  845. * The direction to sort. Legal values are "ASC" and "DESC".
  846. *
  847. * @return EntityFieldQuery
  848. * The called object.
  849. */
  850. public function propertyOrderBy($column, $direction = 'ASC') {
  851. $this->order[] = array(
  852. 'type' => 'property',
  853. 'specifier' => $column,
  854. 'direction' => $direction,
  855. );
  856. return $this;
  857. }
  858. /**
  859. * Sets the query to be a count query only.
  860. *
  861. * @return EntityFieldQuery
  862. * The called object.
  863. */
  864. public function count() {
  865. $this->count = TRUE;
  866. return $this;
  867. }
  868. /**
  869. * Restricts a query to a given range in the result set.
  870. *
  871. * @param $start
  872. * The first entity from the result set to return. If NULL, removes any
  873. * range directives that are set.
  874. * @param $length
  875. * The number of entities to return from the result set.
  876. *
  877. * @return EntityFieldQuery
  878. * The called object.
  879. */
  880. public function range($start = NULL, $length = NULL) {
  881. $this->range = array(
  882. 'start' => $start,
  883. 'length' => $length,
  884. );
  885. return $this;
  886. }
  887. /**
  888. * Enable a pager for the query.
  889. *
  890. * @param $limit
  891. * An integer specifying the number of elements per page. If passed a false
  892. * value (FALSE, 0, NULL), the pager is disabled.
  893. * @param $element
  894. * An optional integer to distinguish between multiple pagers on one page.
  895. * If not provided, one is automatically calculated.
  896. *
  897. * @return EntityFieldQuery
  898. * The called object.
  899. */
  900. public function pager($limit = 10, $element = NULL) {
  901. if (!isset($element)) {
  902. $element = PagerDefault::$maxElement++;
  903. }
  904. elseif ($element >= PagerDefault::$maxElement) {
  905. PagerDefault::$maxElement = $element + 1;
  906. }
  907. $this->pager = array(
  908. 'limit' => $limit,
  909. 'element' => $element,
  910. );
  911. return $this;
  912. }
  913. /**
  914. * Enable sortable tables for this query.
  915. *
  916. * @param $headers
  917. * An EFQ Header array based on which the order clause is added to the query.
  918. *
  919. * @return EntityFieldQuery
  920. * The called object.
  921. */
  922. public function tableSort(&$headers) {
  923. // If 'field' is not initialized, the header columns aren't clickable
  924. foreach ($headers as $key =>$header) {
  925. if (is_array($header) && isset($header['specifier'])) {
  926. $headers[$key]['field'] = '';
  927. }
  928. }
  929. $order = tablesort_get_order($headers);
  930. $direction = tablesort_get_sort($headers);
  931. foreach ($headers as $header) {
  932. if (is_array($header) && ($header['data'] == $order['name'])) {
  933. if ($header['type'] == 'field') {
  934. $this->fieldOrderBy($header['specifier']['field'], $header['specifier']['column'], $direction);
  935. }
  936. else {
  937. $header['direction'] = $direction;
  938. $this->order[] = $header;
  939. }
  940. }
  941. }
  942. return $this;
  943. }
  944. /**
  945. * Filters on the data being deleted.
  946. *
  947. * @param $deleted
  948. * TRUE to only return deleted data, FALSE to return non-deleted data,
  949. * EntityFieldQuery::RETURN_ALL to return everything. Defaults to FALSE.
  950. *
  951. * @return EntityFieldQuery
  952. * The called object.
  953. */
  954. public function deleted($deleted = TRUE) {
  955. $this->deleted = $deleted;
  956. return $this;
  957. }
  958. /**
  959. * Queries the current or every revision.
  960. *
  961. * Note that this only affects field conditions. Property conditions always
  962. * apply to the current revision.
  963. * @TODO: Once revision tables have been cleaned up, revisit this.
  964. *
  965. * @param $age
  966. * - FIELD_LOAD_CURRENT (default): Query the most recent revisions for all
  967. * entities. The results will be keyed by entity type and entity ID.
  968. * - FIELD_LOAD_REVISION: Query all revisions. The results will be keyed by
  969. * entity type and entity revision ID.
  970. *
  971. * @return EntityFieldQuery
  972. * The called object.
  973. */
  974. public function age($age) {
  975. $this->age = $age;
  976. return $this;
  977. }
  978. /**
  979. * Adds a tag to the query.
  980. *
  981. * Tags are strings that mark a query so that hook_query_alter() and
  982. * hook_query_TAG_alter() implementations may decide if they wish to alter
  983. * the query. A query may have any number of tags, and they must be valid PHP
  984. * identifiers (composed of letters, numbers, and underscores). For example,
  985. * queries involving nodes that will be displayed for a user need to add the
  986. * tag 'node_access', so that the node module can add access restrictions to
  987. * the query.
  988. *
  989. * If an entity field query has tags, it must also have an entity type
  990. * specified, because the alter hook will need the entity base table.
  991. *
  992. * @param string $tag
  993. * The tag to add.
  994. *
  995. * @return EntityFieldQuery
  996. * The called object.
  997. */
  998. public function addTag($tag) {
  999. $this->tags[$tag] = $tag;
  1000. return $this;
  1001. }
  1002. /**
  1003. * Adds additional metadata to the query.
  1004. *
  1005. * Sometimes a query may need to provide additional contextual data for the
  1006. * alter hook. The alter hook implementations may then use that information
  1007. * to decide if and how to take action.
  1008. *
  1009. * @param $key
  1010. * The unique identifier for this piece of metadata. Must be a string that
  1011. * follows the same rules as any other PHP identifier.
  1012. * @param $object
  1013. * The additional data to add to the query. May be any valid PHP variable.
  1014. *
  1015. * @return EntityFieldQuery
  1016. * The called object.
  1017. */
  1018. public function addMetaData($key, $object) {
  1019. $this->metaData[$key] = $object;
  1020. return $this;
  1021. }
  1022. /**
  1023. * Executes the query.
  1024. *
  1025. * After executing the query, $this->orderedResults will contain a list of
  1026. * the same stub entities in the order returned by the query. This is only
  1027. * relevant if there are multiple entity types in the returned value and
  1028. * a field ordering was requested. In every other case, the returned value
  1029. * contains everything necessary for processing.
  1030. *
  1031. * @return
  1032. * Either a number if count() was called or an array of associative arrays
  1033. * of stub entities. The outer array keys are entity types, and the inner
  1034. * array keys are the relevant ID. (In most cases this will be the entity
  1035. * ID. The only exception is when age=FIELD_LOAD_REVISION is used and field
  1036. * conditions or sorts are present -- in this case, the key will be the
  1037. * revision ID.) The entity type will only exist in the outer array if
  1038. * results were found. The inner array values are always stub entities, as
  1039. * returned by entity_create_stub_entity(). To traverse the returned array:
  1040. * @code
  1041. * foreach ($query->execute() as $entity_type => $entities) {
  1042. * foreach ($entities as $entity_id => $entity) {
  1043. * @endcode
  1044. * Note if the entity type is known, then the following snippet will load
  1045. * the entities found:
  1046. * @code
  1047. * $result = $query->execute();
  1048. * if (!empty($result[$my_type])) {
  1049. * $entities = entity_load($my_type, array_keys($result[$my_type]));
  1050. * }
  1051. * @endcode
  1052. */
  1053. public function execute() {
  1054. // Give a chance to other modules to alter the query.
  1055. drupal_alter('entity_query', $this);
  1056. $this->altered = TRUE;
  1057. // Initialize the pager.
  1058. $this->initializePager();
  1059. // Execute the query using the correct callback.
  1060. $result = call_user_func($this->queryCallback(), $this);
  1061. return $result;
  1062. }
  1063. /**
  1064. * Determines the query callback to use for this entity query.
  1065. *
  1066. * @return
  1067. * A callback that can be used with call_user_func().
  1068. */
  1069. public function queryCallback() {
  1070. // Use the override from $this->executeCallback. It can be set either
  1071. // while building the query, or using hook_entity_query_alter().
  1072. if (function_exists($this->executeCallback)) {
  1073. return $this->executeCallback;
  1074. }
  1075. // If there are no field conditions and sorts, and no execute callback
  1076. // then we default to querying entity tables in SQL.
  1077. if (empty($this->fields)) {
  1078. return array($this, 'propertyQuery');
  1079. }
  1080. // If no override, find the storage engine to be used.
  1081. foreach ($this->fields as $field) {
  1082. if (!isset($storage)) {
  1083. $storage = $field['storage']['module'];
  1084. }
  1085. elseif ($storage != $field['storage']['module']) {
  1086. throw new EntityFieldQueryException(t("Can't handle more than one field storage engine"));
  1087. }
  1088. }
  1089. if ($storage) {
  1090. // Use hook_field_storage_query() from the field storage.
  1091. return $storage . '_field_storage_query';
  1092. }
  1093. else {
  1094. throw new EntityFieldQueryException(t("Field storage engine not found."));
  1095. }
  1096. }
  1097. /**
  1098. * Queries entity tables in SQL for property conditions and sorts.
  1099. *
  1100. * This method is only used if there are no field conditions and sorts.
  1101. *
  1102. * @return
  1103. * See EntityFieldQuery::execute().
  1104. */
  1105. protected function propertyQuery() {
  1106. if (empty($this->entityConditions['entity_type'])) {
  1107. throw new EntityFieldQueryException(t('For this query an entity type must be specified.'));
  1108. }
  1109. $entity_type = $this->entityConditions['entity_type']['value'];
  1110. $entity_info = entity_get_info($entity_type);
  1111. if (empty($entity_info['base table'])) {
  1112. throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
  1113. }
  1114. $base_table = $entity_info['base table'];
  1115. $base_table_schema = drupal_get_schema($base_table);
  1116. $select_query = db_select($base_table);
  1117. $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
  1118. // Process the property conditions.
  1119. foreach ($this->propertyConditions as $property_condition) {
  1120. $this->addCondition($select_query, "$base_table." . $property_condition['column'], $property_condition);
  1121. }
  1122. // Process the four possible entity condition.
  1123. // The id field is always present in entity keys.
  1124. $sql_field = $entity_info['entity keys']['id'];
  1125. $id_map['entity_id'] = $sql_field;
  1126. $select_query->addField($base_table, $sql_field, 'entity_id');
  1127. if (isset($this->entityConditions['entity_id'])) {
  1128. $this->addCondition($select_query, $sql_field, $this->entityConditions['entity_id']);
  1129. }
  1130. // If there is a revision key defined, use it.
  1131. if (!empty($entity_info['entity keys']['revision'])) {
  1132. $sql_field = $entity_info['entity keys']['revision'];
  1133. $select_query->addField($base_table, $sql_field, 'revision_id');
  1134. if (isset($this->entityConditions['revision_id'])) {
  1135. $this->addCondition($select_query, $sql_field, $this->entityConditions['revision_id']);
  1136. }
  1137. }
  1138. else {
  1139. $sql_field = 'revision_id';
  1140. $select_query->addExpression('NULL', 'revision_id');
  1141. }
  1142. $id_map['revision_id'] = $sql_field;
  1143. // Handle bundles.
  1144. if (!empty($entity_info['entity keys']['bundle'])) {
  1145. $sql_field = $entity_info['entity keys']['bundle'];
  1146. $having = FALSE;
  1147. if (!empty($base_table_schema['fields'][$sql_field])) {
  1148. $select_query->addField($base_table, $sql_field, 'bundle');
  1149. }
  1150. }
  1151. else {
  1152. $sql_field = 'bundle';
  1153. $select_query->addExpression(':bundle', 'bundle', array(':bundle' => $entity_type));
  1154. $having = TRUE;
  1155. }
  1156. $id_map['bundle'] = $sql_field;
  1157. if (isset($this->entityConditions['bundle'])) {
  1158. $this->addCondition($select_query, $sql_field, $this->entityConditions['bundle'], $having);
  1159. }
  1160. // Order the query.
  1161. foreach ($this->order as $order) {
  1162. if ($order['type'] == 'entity') {
  1163. $key = $order['specifier'];
  1164. if (!isset($id_map[$key])) {
  1165. throw new EntityFieldQueryException(t('Do not know how to order on @key for @entity_type', array('@key' => $key, '@entity_type' => $entity_type)));
  1166. }
  1167. $select_query->orderBy($id_map[$key], $order['direction']);
  1168. }
  1169. elseif ($order['type'] == 'property') {
  1170. $select_query->orderBy("$base_table." . $order['specifier'], $order['direction']);
  1171. }
  1172. }
  1173. return $this->finishQuery($select_query);
  1174. }
  1175. /**
  1176. * Get the total number of results and initialize a pager for the query.
  1177. *
  1178. * The pager can be disabled by either setting the pager limit to 0, or by
  1179. * setting this query to be a count query.
  1180. */
  1181. function initializePager() {
  1182. if ($this->pager && !empty($this->pager['limit']) && !$this->count) {
  1183. $page = pager_find_page($this->pager['element']);
  1184. $count_query = clone $this;
  1185. $this->pager['total'] = $count_query->count()->execute();
  1186. $this->pager['start'] = $page * $this->pager['limit'];
  1187. pager_default_initialize($this->pager['total'], $this->pager['limit'], $this->pager['element']);
  1188. $this->range($this->pager['start'], $this->pager['limit']);
  1189. }
  1190. }
  1191. /**
  1192. * Finishes the query.
  1193. *
  1194. * Adds tags, metaData, range and returns the requested list or count.
  1195. *
  1196. * @param SelectQuery $select_query
  1197. * A SelectQuery which has entity_type, entity_id, revision_id and bundle
  1198. * fields added.
  1199. * @param $id_key
  1200. * Which field's values to use as the returned array keys.
  1201. *
  1202. * @return
  1203. * See EntityFieldQuery::execute().
  1204. */
  1205. function finishQuery($select_query, $id_key = 'entity_id') {
  1206. foreach ($this->tags as $tag) {
  1207. $select_query->addTag($tag);
  1208. }
  1209. foreach ($this->metaData as $key => $object) {
  1210. $select_query->addMetaData($key, $object);
  1211. }
  1212. $select_query->addMetaData('entity_field_query', $this);
  1213. if ($this->range) {
  1214. $select_query->range($this->range['start'], $this->range['length']);
  1215. }
  1216. if ($this->count) {
  1217. return $select_query->countQuery()->execute()->fetchField();
  1218. }
  1219. $return = array();
  1220. foreach ($select_query->execute() as $partial_entity) {
  1221. $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
  1222. $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
  1223. $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
  1224. $this->ordered_results[] = $partial_entity;
  1225. }
  1226. return $return;
  1227. }
  1228. /**
  1229. * Adds a condition to an already built SelectQuery (internal function).
  1230. *
  1231. * This is a helper for hook_entity_query() and hook_field_storage_query().
  1232. *
  1233. * @param SelectQuery $select_query
  1234. * A SelectQuery object.
  1235. * @param $sql_field
  1236. * The name of the field.
  1237. * @param $condition
  1238. * A condition as described in EntityFieldQuery::fieldCondition() and
  1239. * EntityFieldQuery::entityCondition().
  1240. * @param $having
  1241. * HAVING or WHERE. This is necessary because SQL can't handle WHERE
  1242. * conditions on aliased columns.
  1243. */
  1244. public function addCondition(SelectQuery $select_query, $sql_field, $condition, $having = FALSE) {
  1245. $method = $having ? 'havingCondition' : 'condition';
  1246. $like_prefix = '';
  1247. switch ($condition['operator']) {
  1248. case 'CONTAINS':
  1249. $like_prefix = '%';
  1250. case 'STARTS_WITH':
  1251. $select_query->$method($sql_field, $like_prefix . db_like($condition['value']) . '%', 'LIKE');
  1252. break;
  1253. default:
  1254. $select_query->$method($sql_field, $condition['value'], $condition['operator']);
  1255. }
  1256. }
  1257. }
  1258. /**
  1259. * Exception thrown when a malformed entity is passed.
  1260. */
  1261. class EntityMalformedException extends Exception { }
Login or register to post comments