entity.inc 47 KB

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