entity.inc 46 KB

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