entity.inc 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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. *
  266. * This will attach fields, if the entity is fieldable. It calls
  267. * hook_entity_load() for modules which need to add data to all entities.
  268. * It also calls hook_TYPE_load() on the loaded entities. For example
  269. * hook_node_load() or hook_user_load(). If your hook_TYPE_load()
  270. * expects special parameters apart from the queried entities, you can set
  271. * $this->hookLoadArguments prior to calling the method.
  272. * See NodeController::attachLoad() for an example.
  273. *
  274. * @param $queried_entities
  275. * Associative array of query results, keyed on the entity ID.
  276. * @param $revision_id
  277. * ID of the revision that was loaded, or FALSE if the most current revision
  278. * was loaded.
  279. */
  280. protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
  281. // Attach fields.
  282. if ($this->entityInfo['fieldable']) {
  283. if ($revision_id) {
  284. field_attach_load_revision($this->entityType, $queried_entities);
  285. }
  286. else {
  287. field_attach_load($this->entityType, $queried_entities);
  288. }
  289. }
  290. // Call hook_entity_load().
  291. foreach (module_implements('entity_load') as $module) {
  292. $function = $module . '_entity_load';
  293. $function($queried_entities, $this->entityType);
  294. }
  295. // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
  296. // always the queried entities, followed by additional arguments set in
  297. // $this->hookLoadArguments.
  298. $args = array_merge(array($queried_entities), $this->hookLoadArguments);
  299. foreach (module_implements($this->entityInfo['load hook']) as $module) {
  300. call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
  301. }
  302. }
  303. /**
  304. * Gets entities from the static cache.
  305. *
  306. * @param $ids
  307. * If not empty, return entities that match these IDs.
  308. * @param $conditions
  309. * If set, return entities that match all of these conditions.
  310. *
  311. * @return
  312. * Array of entities from the entity cache.
  313. */
  314. protected function cacheGet($ids, $conditions = array()) {
  315. $entities = array();
  316. // Load any available entities from the internal cache.
  317. if (!empty($this->entityCache)) {
  318. if ($ids) {
  319. $entities += array_intersect_key($this->entityCache, array_flip($ids));
  320. }
  321. // If loading entities only by conditions, fetch all available entities
  322. // from the cache. Entities which don't match are removed later.
  323. elseif ($conditions) {
  324. $entities = $this->entityCache;
  325. }
  326. }
  327. // Exclude any entities loaded from cache if they don't match $conditions.
  328. // This ensures the same behavior whether loading from memory or database.
  329. if ($conditions) {
  330. foreach ($entities as $entity) {
  331. $entity_values = (array) $entity;
  332. if (array_diff_assoc($conditions, $entity_values)) {
  333. unset($entities[$entity->{$this->idKey}]);
  334. }
  335. }
  336. }
  337. return $entities;
  338. }
  339. /**
  340. * Stores entities in the static entity cache.
  341. *
  342. * @param $entities
  343. * Entities to store in the cache.
  344. */
  345. protected function cacheSet($entities) {
  346. $this->entityCache += $entities;
  347. }
  348. }
  349. /**
  350. * Exception thrown by EntityFieldQuery() on unsupported query syntax.
  351. *
  352. * Some storage modules might not support the full range of the syntax for
  353. * conditions, and will raise an EntityFieldQueryException when an unsupported
  354. * condition was specified.
  355. */
  356. class EntityFieldQueryException extends Exception {}
  357. /**
  358. * Retrieves entities matching a given set of conditions.
  359. *
  360. * This class allows finding entities based on entity properties (for example,
  361. * node->changed), field values, and generic entity meta data (bundle,
  362. * entity type, entity id, and revision ID). It is not possible to query across
  363. * multiple entity types. For example, there is no facility to find published
  364. * nodes written by users created in the last hour, as this would require
  365. * querying both node->status and user->created.
  366. *
  367. * Normally we would not want to have public properties on the object, as that
  368. * allows the object's state to become inconsistent too easily. However, this
  369. * class's standard use case involves primarily code that does need to have
  370. * direct access to the collected properties in order to handle alternate
  371. * execution routines. We therefore use public properties for simplicity. Note
  372. * that code that is simply creating and running a field query should still use
  373. * the appropriate methods to add conditions on the query.
  374. *
  375. * Storage engines are not required to support every type of query. By default,
  376. * an EntityFieldQueryException will be raised if an unsupported condition is
  377. * specified or if the query has field conditions or sorts that are stored in
  378. * different field storage engines. However, this logic can be overridden in
  379. * hook_entity_query_alter().
  380. *
  381. * Also note that this query does not automatically respect entity access
  382. * restrictions. Node access control is performed by the SQL storage engine but
  383. * other storage engines might not do this.
  384. */
  385. class EntityFieldQuery {
  386. /**
  387. * Indicates that both deleted and non-deleted fields should be returned.
  388. *
  389. * @see EntityFieldQuery::deleted()
  390. */
  391. const RETURN_ALL = NULL;
  392. /**
  393. * TRUE if the query has already been altered, FALSE if it hasn't.
  394. *
  395. * Used in alter hooks to check for cloned queries that have already been
  396. * altered prior to the clone (for example, the pager count query).
  397. *
  398. * @var boolean
  399. */
  400. public $altered = FALSE;
  401. /**
  402. * Associative array of entity-generic metadata conditions.
  403. *
  404. * @var array
  405. *
  406. * @see EntityFieldQuery::entityCondition()
  407. */
  408. public $entityConditions = array();
  409. /**
  410. * List of field conditions.
  411. *
  412. * @var array
  413. *
  414. * @see EntityFieldQuery::fieldCondition()
  415. */
  416. public $fieldConditions = array();
  417. /**
  418. * List of field meta conditions (language and delta).
  419. *
  420. * Field conditions operate on columns specified by hook_field_schema(),
  421. * the meta conditions operate on columns added by the system: delta
  422. * and language. These can not be mixed with the field conditions because
  423. * field columns can have any name including delta and language.
  424. *
  425. * @var array
  426. *
  427. * @see EntityFieldQuery::fieldLanguageCondition()
  428. * @see EntityFieldQuery::fieldDeltaCondition()
  429. */
  430. public $fieldMetaConditions = array();
  431. /**
  432. * List of property conditions.
  433. *
  434. * @var array
  435. *
  436. * @see EntityFieldQuery::propertyCondition()
  437. */
  438. public $propertyConditions = array();
  439. /**
  440. * List of order clauses.
  441. *
  442. * @var array
  443. */
  444. public $order = array();
  445. /**
  446. * The query range.
  447. *
  448. * @var array
  449. *
  450. * @see EntityFieldQuery::range()
  451. */
  452. public $range = array();
  453. /**
  454. * The query pager data.
  455. *
  456. * @var array
  457. *
  458. * @see EntityFieldQuery::pager()
  459. */
  460. public $pager = array();
  461. /**
  462. * Query behavior for deleted data.
  463. *
  464. * TRUE to return only deleted data, FALSE to return only non-deleted data,
  465. * EntityFieldQuery::RETURN_ALL to return everything.
  466. *
  467. * @see EntityFieldQuery::deleted()
  468. */
  469. public $deleted = FALSE;
  470. /**
  471. * A list of field arrays used.
  472. *
  473. * Field names passed to EntityFieldQuery::fieldCondition() and
  474. * EntityFieldQuery::fieldOrderBy() are run through field_info_field() before
  475. * stored in this array. This way, the elements of this array are field
  476. * arrays.
  477. *
  478. * @var array
  479. */
  480. public $fields = array();
  481. /**
  482. * TRUE if this is a count query, FALSE if it isn't.
  483. *
  484. * @var boolean
  485. */
  486. public $count = FALSE;
  487. /**
  488. * Flag indicating whether this is querying current or all revisions.
  489. *
  490. * @var int
  491. *
  492. * @see EntityFieldQuery::age()
  493. */
  494. public $age = FIELD_LOAD_CURRENT;
  495. /**
  496. * A list of the tags added to this query.
  497. *
  498. * @var array
  499. *
  500. * @see EntityFieldQuery::addTag()
  501. */
  502. public $tags = array();
  503. /**
  504. * A list of metadata added to this query.
  505. *
  506. * @var array
  507. *
  508. * @see EntityFieldQuery::addMetaData()
  509. */
  510. public $metaData = array();
  511. /**
  512. * The ordered results.
  513. *
  514. * @var array
  515. *
  516. * @see EntityFieldQuery::execute().
  517. */
  518. public $orderedResults = array();
  519. /**
  520. * The method executing the query, if it is overriding the default.
  521. *
  522. * @var string
  523. *
  524. * @see EntityFieldQuery::execute().
  525. */
  526. public $executeCallback = '';
  527. /**
  528. * Adds a condition on entity-generic metadata.
  529. *
  530. * If the overall query contains only entity conditions or ordering, or if
  531. * there are property conditions, then specifying the entity type is
  532. * mandatory. If there are field conditions or ordering but no property
  533. * conditions or ordering, then specifying an entity type is optional. While
  534. * the field storage engine might support field conditions on more than one
  535. * entity type, there is no way to query across multiple entity base tables by
  536. * default. To specify the entity type, pass in 'entity_type' for $name,
  537. * the type as a string for $value, and no $operator (it's disregarded).
  538. *
  539. * 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
  540. *
  541. * Note: The "comment" entity type does not support bundle conditions.
  542. *
  543. * @param $name
  544. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  545. * @param $value
  546. * The value for $name. In most cases, this is a scalar. For more complex
  547. * options, it is an array. The meaning of each element in the array is
  548. * dependent on $operator.
  549. * @param $operator
  550. * Possible values:
  551. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  552. * operators expect $value to be a literal of the same type as the
  553. * column.
  554. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  555. * literals of the same type as the column.
  556. * - 'BETWEEN': This operator expects $value to be an array of two literals
  557. * of the same type as the column.
  558. * The operator can be omitted, and will default to 'IN' if the value is an
  559. * array, or to '=' otherwise.
  560. *
  561. * @return EntityFieldQuery
  562. * The called object.
  563. */
  564. public function entityCondition($name, $value, $operator = NULL) {
  565. // The '!=' operator is deprecated in favour of the '<>' operator since the
  566. // latter is ANSI SQL compatible.
  567. if ($operator == '!=') {
  568. $operator = '<>';
  569. }
  570. $this->entityConditions[$name] = array(
  571. 'value' => $value,
  572. 'operator' => $operator,
  573. );
  574. return $this;
  575. }
  576. /**
  577. * Adds a condition on field values.
  578. *
  579. * Note that entities with empty field values will be excluded from the
  580. * EntityFieldQuery results when using this method.
  581. *
  582. * @param $field
  583. * Either a field name or a field array.
  584. * @param $column
  585. * The column that should hold the value to be matched.
  586. * @param $value
  587. * The value to test the column value against.
  588. * @param $operator
  589. * The operator to be used to test the given value.
  590. * @param $delta_group
  591. * An arbitrary identifier: conditions in the same group must have the same
  592. * $delta_group.
  593. * @param $language_group
  594. * An arbitrary identifier: conditions in the same group must have the same
  595. * $language_group.
  596. *
  597. * @return EntityFieldQuery
  598. * The called object.
  599. *
  600. * @see EntityFieldQuery::addFieldCondition
  601. * @see EntityFieldQuery::deleted
  602. */
  603. public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  604. return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
  605. }
  606. /**
  607. * Adds a condition on the field language column.
  608. *
  609. * @param $field
  610. * Either a field name or a field array.
  611. * @param $value
  612. * The value to test the column value against.
  613. * @param $operator
  614. * The operator to be used to test the given value.
  615. * @param $delta_group
  616. * An arbitrary identifier: conditions in the same group must have the same
  617. * $delta_group.
  618. * @param $language_group
  619. * An arbitrary identifier: conditions in the same group must have the same
  620. * $language_group.
  621. *
  622. * @return EntityFieldQuery
  623. * The called object.
  624. *
  625. * @see EntityFieldQuery::addFieldCondition
  626. * @see EntityFieldQuery::deleted
  627. */
  628. public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  629. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
  630. }
  631. /**
  632. * Adds a condition on the field delta column.
  633. *
  634. * @param $field
  635. * Either a field name or a field array.
  636. * @param $value
  637. * The value to test the column value against.
  638. * @param $operator
  639. * The operator to be used to test the given value.
  640. * @param $delta_group
  641. * An arbitrary identifier: conditions in the same group must have the same
  642. * $delta_group.
  643. * @param $language_group
  644. * An arbitrary identifier: conditions in the same group must have the same
  645. * $language_group.
  646. *
  647. * @return EntityFieldQuery
  648. * The called object.
  649. *
  650. * @see EntityFieldQuery::addFieldCondition
  651. * @see EntityFieldQuery::deleted
  652. */
  653. public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  654. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
  655. }
  656. /**
  657. * Adds the given condition to the proper condition array.
  658. *
  659. * @param $conditions
  660. * A reference to an array of conditions.
  661. * @param $field
  662. * Either a field name or a field array.
  663. * @param $column
  664. * A column defined in the hook_field_schema() of this field. If this is
  665. * omitted then the query will find only entities that have data in this
  666. * field, using the entity and property conditions if there are any.
  667. * @param $value
  668. * The value to test the column value against. In most cases, this is a
  669. * scalar. For more complex options, it is an array. The meaning of each
  670. * element in the array is dependent on $operator.
  671. * @param $operator
  672. * Possible values:
  673. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  674. * operators expect $value to be a literal of the same type as the
  675. * column.
  676. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  677. * literals of the same type as the column.
  678. * - 'BETWEEN': This operator expects $value to be an array of two literals
  679. * of the same type as the column.
  680. * The operator can be omitted, and will default to 'IN' if the value is an
  681. * array, or to '=' otherwise.
  682. * @param $delta_group
  683. * An arbitrary identifier: conditions in the same group must have the same
  684. * $delta_group. For example, let's presume a multivalue field which has
  685. * two columns, 'color' and 'shape', and for entity id 1, there are two
  686. * values: red/square and blue/circle. Entity ID 1 does not have values
  687. * corresponding to 'red circle', however if you pass 'red' and 'circle' as
  688. * conditions, it will appear in the results - by default queries will run
  689. * against any combination of deltas. By passing the conditions with the
  690. * same $delta_group it will ensure that only values attached to the same
  691. * delta are matched, and entity 1 would then be excluded from the results.
  692. * @param $language_group
  693. * An arbitrary identifier: conditions in the same group must have the same
  694. * $language_group.
  695. *
  696. * @return EntityFieldQuery
  697. * The called object.
  698. */
  699. protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  700. // The '!=' operator is deprecated in favour of the '<>' operator since the
  701. // latter is ANSI SQL compatible.
  702. if ($operator == '!=') {
  703. $operator = '<>';
  704. }
  705. if (is_scalar($field)) {
  706. $field_definition = field_info_field($field);
  707. if (empty($field_definition)) {
  708. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  709. }
  710. $field = $field_definition;
  711. }
  712. // Ensure the same index is used for field conditions as for fields.
  713. $index = count($this->fields);
  714. $this->fields[$index] = $field;
  715. if (isset($column)) {
  716. $conditions[$index] = array(
  717. 'field' => $field,
  718. 'column' => $column,
  719. 'value' => $value,
  720. 'operator' => $operator,
  721. 'delta_group' => $delta_group,
  722. 'language_group' => $language_group,
  723. );
  724. }
  725. return $this;
  726. }
  727. /**
  728. * Adds a condition on an entity-specific property.
  729. *
  730. * An $entity_type must be specified by calling
  731. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  732. * executing the query. Also, by default only entities stored in SQL are
  733. * supported; however, EntityFieldQuery::executeCallback can be set to handle
  734. * different entity storage.
  735. *
  736. * @param $column
  737. * A column defined in the hook_schema() of the base table of the entity.
  738. * @param $value
  739. * The value to test the field against. In most cases, this is a scalar. For
  740. * more complex options, it is an array. The meaning of each element in the
  741. * array is dependent on $operator.
  742. * @param $operator
  743. * Possible values:
  744. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  745. * operators expect $value to be a literal of the same type as the
  746. * column.
  747. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  748. * literals of the same type as the column.
  749. * - 'BETWEEN': This operator expects $value to be an array of two literals
  750. * of the same type as the column.
  751. * The operator can be omitted, and will default to 'IN' if the value is an
  752. * array, or to '=' otherwise.
  753. *
  754. * @return EntityFieldQuery
  755. * The called object.
  756. */
  757. public function propertyCondition($column, $value, $operator = NULL) {
  758. // The '!=' operator is deprecated in favour of the '<>' operator since the
  759. // latter is ANSI SQL compatible.
  760. if ($operator == '!=') {
  761. $operator = '<>';
  762. }
  763. $this->propertyConditions[] = array(
  764. 'column' => $column,
  765. 'value' => $value,
  766. 'operator' => $operator,
  767. );
  768. return $this;
  769. }
  770. /**
  771. * Orders the result set by entity-generic metadata.
  772. *
  773. * If called multiple times, the query will order by each specified column in
  774. * the order this method is called.
  775. *
  776. * Note: The "comment" and "taxonomy_term" entity types don't support ordering
  777. * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
  778. *
  779. * @param $name
  780. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  781. * @param $direction
  782. * The direction to sort. Legal values are "ASC" and "DESC".
  783. *
  784. * @return EntityFieldQuery
  785. * The called object.
  786. */
  787. public function entityOrderBy($name, $direction = 'ASC') {
  788. $this->order[] = array(
  789. 'type' => 'entity',
  790. 'specifier' => $name,
  791. 'direction' => $direction,
  792. );
  793. return $this;
  794. }
  795. /**
  796. * Orders the result set by a given field column.
  797. *
  798. * If called multiple times, the query will order by each specified column in
  799. * the order this method is called. Note that entities with empty field
  800. * values will be excluded from the EntityFieldQuery results when using this
  801. * method.
  802. *
  803. * @param $field
  804. * Either a field name or a field array.
  805. * @param $column
  806. * A column defined in the hook_field_schema() of this field. entity_id and
  807. * bundle can also be used.
  808. * @param $direction
  809. * The direction to sort. Legal values are "ASC" and "DESC".
  810. *
  811. * @return EntityFieldQuery
  812. * The called object.
  813. */
  814. public function fieldOrderBy($field, $column, $direction = 'ASC') {
  815. if (is_scalar($field)) {
  816. $field_definition = field_info_field($field);
  817. if (empty($field_definition)) {
  818. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  819. }
  820. $field = $field_definition;
  821. }
  822. // Save the index used for the new field, for later use in field storage.
  823. $index = count($this->fields);
  824. $this->fields[$index] = $field;
  825. $this->order[] = array(
  826. 'type' => 'field',
  827. 'specifier' => array(
  828. 'field' => $field,
  829. 'index' => $index,
  830. 'column' => $column,
  831. ),
  832. 'direction' => $direction,
  833. );
  834. return $this;
  835. }
  836. /**
  837. * Orders the result set by an entity-specific property.
  838. *
  839. * An $entity_type must be specified by calling
  840. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  841. * executing the query.
  842. *
  843. * If called multiple times, the query will order by each specified column in
  844. * the order this method is called.
  845. *
  846. * @param $column
  847. * The column on which to order.
  848. * @param $direction
  849. * The direction to sort. Legal values are "ASC" and "DESC".
  850. *
  851. * @return EntityFieldQuery
  852. * The called object.
  853. */
  854. public function propertyOrderBy($column, $direction = 'ASC') {
  855. $this->order[] = array(
  856. 'type' => 'property',
  857. 'specifier' => $column,
  858. 'direction' => $direction,
  859. );
  860. return $this;
  861. }
  862. /**
  863. * Sets the query to be a count query only.
  864. *
  865. * @return EntityFieldQuery
  866. * The called object.
  867. */
  868. public function count() {
  869. $this->count = TRUE;
  870. return $this;
  871. }
  872. /**
  873. * Restricts a query to a given range in the result set.
  874. *
  875. * @param $start
  876. * The first entity from the result set to return. If NULL, removes any
  877. * range directives that are set.
  878. * @param $length
  879. * The number of entities to return from the result set.
  880. *
  881. * @return EntityFieldQuery
  882. * The called object.
  883. */
  884. public function range($start = NULL, $length = NULL) {
  885. $this->range = array(
  886. 'start' => $start,
  887. 'length' => $length,
  888. );
  889. return $this;
  890. }
  891. /**
  892. * Enables a pager for the query.
  893. *
  894. * @param $limit
  895. * An integer specifying the number of elements per page. If passed a false
  896. * value (FALSE, 0, NULL), the pager is disabled.
  897. * @param $element
  898. * An optional integer to distinguish between multiple pagers on one page.
  899. * If not provided, one is automatically calculated.
  900. *
  901. * @return EntityFieldQuery
  902. * The called object.
  903. */
  904. public function pager($limit = 10, $element = NULL) {
  905. if (!isset($element)) {
  906. $element = PagerDefault::$maxElement++;
  907. }
  908. elseif ($element >= PagerDefault::$maxElement) {
  909. PagerDefault::$maxElement = $element + 1;
  910. }
  911. $this->pager = array(
  912. 'limit' => $limit,
  913. 'element' => $element,
  914. );
  915. return $this;
  916. }
  917. /**
  918. * Enables sortable tables for this query.
  919. *
  920. * @param $headers
  921. * An EFQ Header array based on which the order clause is added to the
  922. * 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. * Gets the total number of results and initializes 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. * Defines an exception thrown when a malformed entity is passed.
  1271. */
  1272. class EntityMalformedException extends Exception { }