entity.inc 45 KB

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