entity.inc 46 KB

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