entity.inc 45 KB

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