Projet

Général

Profil

Paste
Télécharger (45,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / entity.inc @ 4444412d

1
<?php
2

    
3
/**
4
 * Interface for entity controller classes.
5
 *
6
 * All entity controller classes specified via the 'controller class' key
7
 * returned by hook_entity_info() or hook_entity_info_alter() have to implement
8
 * this interface.
9
 *
10
 * Most simple, SQL-based entity controllers will do better by extending
11
 * DrupalDefaultEntityController instead of implementing this interface
12
 * directly.
13
 */
14
interface DrupalEntityControllerInterface {
15

    
16
  /**
17
   * Resets the internal, static entity cache.
18
   *
19
   * @param $ids
20
   *   (optional) If specified, the cache is reset for the entities with the
21
   *   given ids only.
22
   */
23
  public function resetCache(array $ids = NULL);
24

    
25
  /**
26
   * Loads one or more entities.
27
   *
28
   * @param $ids
29
   *   An array of entity IDs, or FALSE to load all entities.
30
   * @param $conditions
31
   *   An array of conditions in the form 'field' => $value.
32
   *
33
   * @return
34
   *   An array of entity objects indexed by their ids. When no results are
35
   *   found, an empty array is returned.
36
   */
37
  public function load($ids = array(), $conditions = array());
38
}
39

    
40
/**
41
 * Default implementation of DrupalEntityControllerInterface.
42
 *
43
 * This class can be used as-is by most simple entity types. Entity types
44
 * requiring special handling can extend the class.
45
 */
46
class DrupalDefaultEntityController implements DrupalEntityControllerInterface {
47

    
48
  /**
49
   * Static cache of entities.
50
   *
51
   * @var array
52
   */
53
  protected $entityCache;
54

    
55
  /**
56
   * Entity type for this controller instance.
57
   *
58
   * @var string
59
   */
60
  protected $entityType;
61

    
62
  /**
63
   * Array of information about the entity.
64
   *
65
   * @var array
66
   *
67
   * @see entity_get_info()
68
   */
69
  protected $entityInfo;
70

    
71
  /**
72
   * Additional arguments to pass to hook_TYPE_load().
73
   *
74
   * Set before calling DrupalDefaultEntityController::attachLoad().
75
   *
76
   * @var array
77
   */
78
  protected $hookLoadArguments;
79

    
80
  /**
81
   * Name of the entity's ID field in the entity database table.
82
   *
83
   * @var string
84
   */
85
  protected $idKey;
86

    
87
  /**
88
   * Name of entity's revision database table field, if it supports revisions.
89
   *
90
   * Has the value FALSE if this entity does not use revisions.
91
   *
92
   * @var string
93
   */
94
  protected $revisionKey;
95

    
96
  /**
97
   * The table that stores revisions, if the entity supports revisions.
98
   *
99
   * @var string
100
   */
101
  protected $revisionTable;
102

    
103
  /**
104
   * Whether this entity type should use the static cache.
105
   *
106
   * Set by entity info.
107
   *
108
   * @var boolean
109
   */
110
  protected $cache;
111

    
112
  /**
113
   * Constructor: sets basic variables.
114
   *
115
   * @param $entityType
116
   *   The entity type for which the instance is created.
117
   */
118
  public function __construct($entityType) {
119
    $this->entityType = $entityType;
120
    $this->entityInfo = entity_get_info($entityType);
121
    $this->entityCache = array();
122
    $this->hookLoadArguments = array();
123
    $this->idKey = $this->entityInfo['entity keys']['id'];
124

    
125
    // Check if the entity type supports revisions.
126
    if (!empty($this->entityInfo['entity keys']['revision'])) {
127
      $this->revisionKey = $this->entityInfo['entity keys']['revision'];
128
      $this->revisionTable = $this->entityInfo['revision table'];
129
    }
130
    else {
131
      $this->revisionKey = FALSE;
132
    }
133

    
134
    // Check if the entity type supports static caching of loaded entities.
135
    $this->cache = !empty($this->entityInfo['static cache']);
136
  }
137

    
138
  /**
139
   * Implements DrupalEntityControllerInterface::resetCache().
140
   */
141
  public function resetCache(array $ids = NULL) {
142
    if (isset($ids)) {
143
      foreach ($ids as $id) {
144
        unset($this->entityCache[$id]);
145
      }
146
    }
147
    else {
148
      $this->entityCache = array();
149
    }
150
  }
151

    
152
  /**
153
   * Implements DrupalEntityControllerInterface::load().
154
   */
155
  public function load($ids = array(), $conditions = array()) {
156
    $entities = array();
157

    
158
    // Revisions are not statically cached, and require a different query to
159
    // other conditions, so separate the revision id into its own variable.
160
    if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
161
      $revision_id = $conditions[$this->revisionKey];
162
      unset($conditions[$this->revisionKey]);
163
    }
164
    else {
165
      $revision_id = FALSE;
166
    }
167

    
168
    // Create a new variable which is either a prepared version of the $ids
169
    // array for later comparison with the entity cache, or FALSE if no $ids
170
    // were passed. The $ids array is reduced as items are loaded from cache,
171
    // and we need to know if it's empty for this reason to avoid querying the
172
    // database when all requested entities are loaded from cache.
173
    $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
174
    // Try to load entities from the static cache, if the entity type supports
175
    // static caching.
176
    if ($this->cache && !$revision_id) {
177
      $entities += $this->cacheGet($ids, $conditions);
178
      // If any entities were loaded, remove them from the ids still to load.
179
      if ($passed_ids) {
180
        $ids = array_keys(array_diff_key($passed_ids, $entities));
181
      }
182
    }
183

    
184
    // Load any remaining entities from the database. This is the case if $ids
185
    // is set to FALSE (so we load all entities), if there are any ids left to
186
    // load, if loading a revision, or if $conditions was passed without $ids.
187
    if ($ids === FALSE || $ids || $revision_id || ($conditions && !$passed_ids)) {
188
      // Build the query.
189
      $query = $this->buildQuery($ids, $conditions, $revision_id);
190
      $queried_entities = $query
191
        ->execute()
192
        ->fetchAllAssoc($this->idKey);
193
    }
194

    
195
    // Pass all entities loaded from the database through $this->attachLoad(),
196
    // which attaches fields (if supported by the entity type) and calls the
197
    // entity type specific load callback, for example hook_node_load().
198
    if (!empty($queried_entities)) {
199
      $this->attachLoad($queried_entities, $revision_id);
200
      $entities += $queried_entities;
201
    }
202

    
203
    if ($this->cache) {
204
      // Add entities to the cache if we are not loading a revision.
205
      if (!empty($queried_entities) && !$revision_id) {
206
        $this->cacheSet($queried_entities);
207
      }
208
    }
209

    
210
    // Ensure that the returned array is ordered the same as the original
211
    // $ids array if this was passed in and remove any invalid ids.
212
    if ($passed_ids) {
213
      // Remove any invalid ids from the array.
214
      $passed_ids = array_intersect_key($passed_ids, $entities);
215
      foreach ($entities as $entity) {
216
        $passed_ids[$entity->{$this->idKey}] = $entity;
217
      }
218
      $entities = $passed_ids;
219
    }
220

    
221
    return $entities;
222
  }
223

    
224
  /**
225
   * Builds the query to load the entity.
226
   *
227
   * This has full revision support. For entities requiring special queries,
228
   * the class can be extended, and the default query can be constructed by
229
   * calling parent::buildQuery(). This is usually necessary when the object
230
   * being loaded needs to be augmented with additional data from another
231
   * table, such as loading node type into comments or vocabulary machine name
232
   * into terms, however it can also support $conditions on different tables.
233
   * See CommentController::buildQuery() or TaxonomyTermController::buildQuery()
234
   * for examples.
235
   *
236
   * @param $ids
237
   *   An array of entity IDs, or FALSE to load all entities.
238
   * @param $conditions
239
   *   An array of conditions in the form 'field' => $value.
240
   * @param $revision_id
241
   *   The ID of the revision to load, or FALSE if this query is asking for the
242
   *   most current revision(s).
243
   *
244
   * @return SelectQuery
245
   *   A SelectQuery object for loading the entity.
246
   */
247
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
248
    $query = db_select($this->entityInfo['base table'], 'base');
249

    
250
    $query->addTag($this->entityType . '_load_multiple');
251

    
252
    if ($revision_id) {
253
      $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} = :revisionId", array(':revisionId' => $revision_id));
254
    }
255
    elseif ($this->revisionKey) {
256
      $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
257
    }
258

    
259
    // Add fields from the {entity} table.
260
    $entity_fields = $this->entityInfo['schema_fields_sql']['base table'];
261

    
262
    if ($this->revisionKey) {
263
      // Add all fields from the {entity_revision} table.
264
      $entity_revision_fields = drupal_map_assoc($this->entityInfo['schema_fields_sql']['revision table']);
265
      // The id field is provided by entity, so remove it.
266
      unset($entity_revision_fields[$this->idKey]);
267

    
268
      // Remove all fields from the base table that are also fields by the same
269
      // name in the revision table.
270
      $entity_field_keys = array_flip($entity_fields);
271
      foreach ($entity_revision_fields as $key => $name) {
272
        if (isset($entity_field_keys[$name])) {
273
          unset($entity_fields[$entity_field_keys[$name]]);
274
        }
275
      }
276
      $query->fields('revision', $entity_revision_fields);
277
    }
278

    
279
    $query->fields('base', $entity_fields);
280

    
281
    if ($ids) {
282
      $query->condition("base.{$this->idKey}", $ids, 'IN');
283
    }
284
    if ($conditions) {
285
      foreach ($conditions as $field => $value) {
286
        $query->condition('base.' . $field, $value);
287
      }
288
    }
289
    return $query;
290
  }
291

    
292
  /**
293
   * Attaches data to entities upon loading.
294
   *
295
   * This will attach fields, if the entity is fieldable. It calls
296
   * hook_entity_load() for modules which need to add data to all entities.
297
   * It also calls hook_TYPE_load() on the loaded entities. For example
298
   * hook_node_load() or hook_user_load(). If your hook_TYPE_load()
299
   * expects special parameters apart from the queried entities, you can set
300
   * $this->hookLoadArguments prior to calling the method.
301
   * See NodeController::attachLoad() for an example.
302
   *
303
   * @param $queried_entities
304
   *   Associative array of query results, keyed on the entity ID.
305
   * @param $revision_id
306
   *   ID of the revision that was loaded, or FALSE if the most current revision
307
   *   was loaded.
308
   */
309
  protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
310
    // Attach fields.
311
    if ($this->entityInfo['fieldable']) {
312
      if ($revision_id) {
313
        field_attach_load_revision($this->entityType, $queried_entities);
314
      }
315
      else {
316
        field_attach_load($this->entityType, $queried_entities);
317
      }
318
    }
319

    
320
    // Call hook_entity_load().
321
    foreach (module_implements('entity_load') as $module) {
322
      $function = $module . '_entity_load';
323
      $function($queried_entities, $this->entityType);
324
    }
325
    // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
326
    // always the queried entities, followed by additional arguments set in
327
    // $this->hookLoadArguments.
328
    $args = array_merge(array($queried_entities), $this->hookLoadArguments);
329
    foreach (module_implements($this->entityInfo['load hook']) as $module) {
330
      call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
331
    }
332
  }
333

    
334
  /**
335
   * Gets entities from the static cache.
336
   *
337
   * @param $ids
338
   *   If not empty, return entities that match these IDs.
339
   * @param $conditions
340
   *   If set, return entities that match all of these conditions.
341
   *
342
   * @return
343
   *   Array of entities from the entity cache.
344
   */
345
  protected function cacheGet($ids, $conditions = array()) {
346
    $entities = array();
347
    // Load any available entities from the internal cache.
348
    if (!empty($this->entityCache)) {
349
      if ($ids) {
350
        $entities += array_intersect_key($this->entityCache, array_flip($ids));
351
      }
352
      // If loading entities only by conditions, fetch all available entities
353
      // from the cache. Entities which don't match are removed later.
354
      elseif ($conditions) {
355
        $entities = $this->entityCache;
356
      }
357
    }
358

    
359
    // Exclude any entities loaded from cache if they don't match $conditions.
360
    // This ensures the same behavior whether loading from memory or database.
361
    if ($conditions) {
362
      foreach ($entities as $entity) {
363
        // Iterate over all conditions and compare them to the entity
364
        // properties. We cannot use array_diff_assoc() here since the
365
        // conditions can be nested arrays, too.
366
        foreach ($conditions as $property_name => $condition) {
367
          if (is_array($condition)) {
368
            // Multiple condition values for one property are treated as OR
369
            // operation: only if the value is not at all in the condition array
370
            // we remove the entity.
371
            if (!in_array($entity->{$property_name}, $condition)) {
372
              unset($entities[$entity->{$this->idKey}]);
373
              continue 2;
374
            }
375
          }
376
          elseif ($condition != $entity->{$property_name}) {
377
            unset($entities[$entity->{$this->idKey}]);
378
            continue 2;
379
          }
380
        }
381
      }
382
    }
383
    return $entities;
384
  }
385

    
386
  /**
387
   * Stores entities in the static entity cache.
388
   *
389
   * @param $entities
390
   *   Entities to store in the cache.
391
   */
392
  protected function cacheSet($entities) {
393
    $this->entityCache += $entities;
394
  }
395
}
396

    
397
/**
398
 * Exception thrown by EntityFieldQuery() on unsupported query syntax.
399
 *
400
 * Some storage modules might not support the full range of the syntax for
401
 * conditions, and will raise an EntityFieldQueryException when an unsupported
402
 * condition was specified.
403
 */
404
class EntityFieldQueryException extends Exception {}
405

    
406
/**
407
 * Retrieves entities matching a given set of conditions.
408
 *
409
 * This class allows finding entities based on entity properties (for example,
410
 * node->changed), field values, and generic entity meta data (bundle,
411
 * entity type, entity id, and revision ID). It is not possible to query across
412
 * multiple entity types. For example, there is no facility to find published
413
 * nodes written by users created in the last hour, as this would require
414
 * querying both node->status and user->created.
415
 *
416
 * Normally we would not want to have public properties on the object, as that
417
 * allows the object's state to become inconsistent too easily. However, this
418
 * class's standard use case involves primarily code that does need to have
419
 * direct access to the collected properties in order to handle alternate
420
 * execution routines. We therefore use public properties for simplicity. Note
421
 * that code that is simply creating and running a field query should still use
422
 * the appropriate methods to add conditions on the query.
423
 *
424
 * Storage engines are not required to support every type of query. By default,
425
 * an EntityFieldQueryException will be raised if an unsupported condition is
426
 * specified or if the query has field conditions or sorts that are stored in
427
 * different field storage engines. However, this logic can be overridden in
428
 * hook_entity_query_alter().
429
 *
430
 * Also note that this query does not automatically respect entity access
431
 * restrictions. Node access control is performed by the SQL storage engine but
432
 * other storage engines might not do this.
433
 */
434
class EntityFieldQuery {
435

    
436
  /**
437
   * Indicates that both deleted and non-deleted fields should be returned.
438
   *
439
   * @see EntityFieldQuery::deleted()
440
   */
441
  const RETURN_ALL = NULL;
442

    
443
  /**
444
   * TRUE if the query has already been altered, FALSE if it hasn't.
445
   *
446
   * Used in alter hooks to check for cloned queries that have already been
447
   * altered prior to the clone (for example, the pager count query).
448
   *
449
   * @var boolean
450
   */
451
  public $altered = FALSE;
452

    
453
  /**
454
   * Associative array of entity-generic metadata conditions.
455
   *
456
   * @var array
457
   *
458
   * @see EntityFieldQuery::entityCondition()
459
   */
460
  public $entityConditions = array();
461

    
462
  /**
463
   * List of field conditions.
464
   *
465
   * @var array
466
   *
467
   * @see EntityFieldQuery::fieldCondition()
468
   */
469
  public $fieldConditions = array();
470

    
471
  /**
472
   * List of field meta conditions (language and delta).
473
   *
474
   * Field conditions operate on columns specified by hook_field_schema(),
475
   * the meta conditions operate on columns added by the system: delta
476
   * and language. These can not be mixed with the field conditions because
477
   * field columns can have any name including delta and language.
478
   *
479
   * @var array
480
   *
481
   * @see EntityFieldQuery::fieldLanguageCondition()
482
   * @see EntityFieldQuery::fieldDeltaCondition()
483
   */
484
  public $fieldMetaConditions = array();
485

    
486
  /**
487
   * List of property conditions.
488
   *
489
   * @var array
490
   *
491
   * @see EntityFieldQuery::propertyCondition()
492
   */
493
  public $propertyConditions = array();
494

    
495
  /**
496
   * List of order clauses.
497
   *
498
   * @var array
499
   */
500
  public $order = array();
501

    
502
  /**
503
   * The query range.
504
   *
505
   * @var array
506
   *
507
   * @see EntityFieldQuery::range()
508
   */
509
  public $range = array();
510

    
511
  /**
512
   * The query pager data.
513
   *
514
   * @var array
515
   *
516
   * @see EntityFieldQuery::pager()
517
   */
518
  public $pager = array();
519

    
520
  /**
521
   * Query behavior for deleted data.
522
   *
523
   * TRUE to return only deleted data, FALSE to return only non-deleted data,
524
   * EntityFieldQuery::RETURN_ALL to return everything.
525
   *
526
   * @see EntityFieldQuery::deleted()
527
   */
528
  public $deleted = FALSE;
529

    
530
  /**
531
   * A list of field arrays used.
532
   *
533
   * Field names passed to EntityFieldQuery::fieldCondition() and
534
   * EntityFieldQuery::fieldOrderBy() are run through field_info_field() before
535
   * stored in this array. This way, the elements of this array are field
536
   * arrays.
537
   *
538
   * @var array
539
   */
540
  public $fields = array();
541

    
542
  /**
543
   * TRUE if this is a count query, FALSE if it isn't.
544
   *
545
   * @var boolean
546
   */
547
  public $count = FALSE;
548

    
549
  /**
550
   * Flag indicating whether this is querying current or all revisions.
551
   *
552
   * @var int
553
   *
554
   * @see EntityFieldQuery::age()
555
   */
556
  public $age = FIELD_LOAD_CURRENT;
557

    
558
  /**
559
   * A list of the tags added to this query.
560
   *
561
   * @var array
562
   *
563
   * @see EntityFieldQuery::addTag()
564
   */
565
  public $tags = array();
566

    
567
  /**
568
   * A list of metadata added to this query.
569
   *
570
   * @var array
571
   *
572
   * @see EntityFieldQuery::addMetaData()
573
   */
574
  public $metaData = array();
575

    
576
  /**
577
   * The ordered results.
578
   *
579
   * @var array
580
   *
581
   * @see EntityFieldQuery::execute().
582
   */
583
  public $orderedResults = array();
584

    
585
  /**
586
   * The method executing the query, if it is overriding the default.
587
   *
588
   * @var string
589
   *
590
   * @see EntityFieldQuery::execute().
591
   */
592
  public $executeCallback = '';
593

    
594
  /**
595
   * Adds a condition on entity-generic metadata.
596
   *
597
   * If the overall query contains only entity conditions or ordering, or if
598
   * there are property conditions, then specifying the entity type is
599
   * mandatory. If there are field conditions or ordering but no property
600
   * conditions or ordering, then specifying an entity type is optional. While
601
   * the field storage engine might support field conditions on more than one
602
   * entity type, there is no way to query across multiple entity base tables by
603
   * default. To specify the entity type, pass in 'entity_type' for $name,
604
   * the type as a string for $value, and no $operator (it's disregarded).
605
   *
606
   * 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
607
   *
608
   * Note: The "comment" entity type does not support bundle conditions.
609
   *
610
   * @param $name
611
   *   'entity_type', 'bundle', 'revision_id' or 'entity_id'.
612
   * @param $value
613
   *   The value for $name. In most cases, this is a scalar. For more complex
614
   *   options, it is an array. The meaning of each element in the array is
615
   *   dependent on $operator.
616
   * @param $operator
617
   *   Possible values:
618
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
619
   *     operators expect $value to be a literal of the same type as the
620
   *     column.
621
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
622
   *     literals of the same type as the column.
623
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
624
   *     of the same type as the column.
625
   *   The operator can be omitted, and will default to 'IN' if the value is an
626
   *   array, or to '=' otherwise.
627
   *
628
   * @return EntityFieldQuery
629
   *   The called object.
630
   */
631
  public function entityCondition($name, $value, $operator = NULL) {
632
    // The '!=' operator is deprecated in favour of the '<>' operator since the
633
    // latter is ANSI SQL compatible.
634
    if ($operator == '!=') {
635
      $operator = '<>';
636
    }
637
    $this->entityConditions[$name] = array(
638
      'value' => $value,
639
      'operator' => $operator,
640
    );
641
    return $this;
642
  }
643

    
644
  /**
645
   * Adds a condition on field values.
646
   *
647
   * Note that entities with empty field values will be excluded from the
648
   * EntityFieldQuery results when using this method.
649
   *
650
   * @param $field
651
   *   Either a field name or a field array.
652
   * @param $column
653
   *   The column that should hold the value to be matched.
654
   * @param $value
655
   *   The value to test the column value against.
656
   * @param $operator
657
   *   The operator to be used to test the given value.
658
   * @param $delta_group
659
   *   An arbitrary identifier: conditions in the same group must have the same
660
   *   $delta_group.
661
   * @param $language_group
662
   *   An arbitrary identifier: conditions in the same group must have the same
663
   *   $language_group.
664
   *
665
   * @return EntityFieldQuery
666
   *   The called object.
667
   *
668
   * @see EntityFieldQuery::addFieldCondition
669
   * @see EntityFieldQuery::deleted
670
   */
671
  public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
672
    return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
673
  }
674

    
675
  /**
676
   * Adds a condition on the field language column.
677
   *
678
   * @param $field
679
   *   Either a field name or a field array.
680
   * @param $value
681
   *   The value to test the column value against.
682
   * @param $operator
683
   *   The operator to be used to test the given value.
684
   * @param $delta_group
685
   *   An arbitrary identifier: conditions in the same group must have the same
686
   *   $delta_group.
687
   * @param $language_group
688
   *   An arbitrary identifier: conditions in the same group must have the same
689
   *   $language_group.
690
   *
691
   * @return EntityFieldQuery
692
   *   The called object.
693
   *
694
   * @see EntityFieldQuery::addFieldCondition
695
   * @see EntityFieldQuery::deleted
696
   */
697
  public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
698
    return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
699
  }
700

    
701
  /**
702
   * Adds a condition on the field delta column.
703
   *
704
   * @param $field
705
   *   Either a field name or a field array.
706
   * @param $value
707
   *   The value to test the column value against.
708
   * @param $operator
709
   *   The operator to be used to test the given value.
710
   * @param $delta_group
711
   *   An arbitrary identifier: conditions in the same group must have the same
712
   *   $delta_group.
713
   * @param $language_group
714
   *   An arbitrary identifier: conditions in the same group must have the same
715
   *   $language_group.
716
   *
717
   * @return EntityFieldQuery
718
   *   The called object.
719
   *
720
   * @see EntityFieldQuery::addFieldCondition
721
   * @see EntityFieldQuery::deleted
722
   */
723
  public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
724
    return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
725
  }
726

    
727
  /**
728
   * Adds the given condition to the proper condition array.
729
   *
730
   * @param $conditions
731
   *   A reference to an array of conditions.
732
   * @param $field
733
   *   Either a field name or a field array.
734
   * @param $column
735
   *   A column defined in the hook_field_schema() of this field. If this is
736
   *   omitted then the query will find only entities that have data in this
737
   *   field, using the entity and property conditions if there are any.
738
   * @param $value
739
   *   The value to test the column value against. In most cases, this is a
740
   *   scalar. For more complex options, it is an array. The meaning of each
741
   *   element in the 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
   * @param $delta_group
754
   *   An arbitrary identifier: conditions in the same group must have the same
755
   *   $delta_group. For example, let's presume a multivalue field which has
756
   *   two columns, 'color' and 'shape', and for entity id 1, there are two
757
   *   values: red/square and blue/circle. Entity ID 1 does not have values
758
   *   corresponding to 'red circle', however if you pass 'red' and 'circle' as
759
   *   conditions, it will appear in the  results - by default queries will run
760
   *   against any combination of deltas. By passing the conditions with the
761
   *   same $delta_group it will ensure that only values attached to the same
762
   *   delta are matched, and entity 1 would then be excluded from the results.
763
   * @param $language_group
764
   *   An arbitrary identifier: conditions in the same group must have the same
765
   *   $language_group.
766
   *
767
   * @return EntityFieldQuery
768
   *   The called object.
769
   */
770
  protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
771
    // The '!=' operator is deprecated in favour of the '<>' operator since the
772
    // latter is ANSI SQL compatible.
773
    if ($operator == '!=') {
774
      $operator = '<>';
775
    }
776
    if (is_scalar($field)) {
777
      $field_definition = field_info_field($field);
778
      if (empty($field_definition)) {
779
        throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
780
      }
781
      $field = $field_definition;
782
    }
783
    // Ensure the same index is used for field conditions as for fields.
784
    $index = count($this->fields);
785
    $this->fields[$index] = $field;
786
    if (isset($column)) {
787
      $conditions[$index] = array(
788
        'field' => $field,
789
        'column' => $column,
790
        'value' => $value,
791
        'operator' => $operator,
792
        'delta_group' => $delta_group,
793
        'language_group' => $language_group,
794
      );
795
    }
796
    return $this;
797
  }
798

    
799
  /**
800
   * Adds a condition on an entity-specific property.
801
   *
802
   * An $entity_type must be specified by calling
803
   * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
804
   * executing the query. Also, by default only entities stored in SQL are
805
   * supported; however, EntityFieldQuery::executeCallback can be set to handle
806
   * different entity storage.
807
   *
808
   * @param $column
809
   *   A column defined in the hook_schema() of the base table of the entity.
810
   * @param $value
811
   *   The value to test the field against. In most cases, this is a scalar. For
812
   *   more complex options, it is an array. The meaning of each element in the
813
   *   array is dependent on $operator.
814
   * @param $operator
815
   *   Possible values:
816
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
817
   *     operators expect $value to be a literal of the same type as the
818
   *     column.
819
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
820
   *     literals of the same type as the column.
821
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
822
   *     of the same type as the column.
823
   *   The operator can be omitted, and will default to 'IN' if the value is an
824
   *   array, or to '=' otherwise.
825
   *
826
   * @return EntityFieldQuery
827
   *   The called object.
828
   */
829
  public function propertyCondition($column, $value, $operator = NULL) {
830
    // The '!=' operator is deprecated in favour of the '<>' operator since the
831
    // latter is ANSI SQL compatible.
832
    if ($operator == '!=') {
833
      $operator = '<>';
834
    }
835
    $this->propertyConditions[] = array(
836
      'column' => $column,
837
      'value' => $value,
838
      'operator' => $operator,
839
    );
840
    return $this;
841
  }
842

    
843
  /**
844
   * Orders the result set by entity-generic metadata.
845
   *
846
   * If called multiple times, the query will order by each specified column in
847
   * the order this method is called.
848
   *
849
   * Note: The "comment" and "taxonomy_term" entity types don't support ordering
850
   * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
851
   *
852
   * @param $name
853
   *   'entity_type', 'bundle', 'revision_id' or 'entity_id'.
854
   * @param $direction
855
   *   The direction to sort. Legal values are "ASC" and "DESC".
856
   *
857
   * @return EntityFieldQuery
858
   *   The called object.
859
   */
860
  public function entityOrderBy($name, $direction = 'ASC') {
861
    $this->order[] = array(
862
      'type' => 'entity',
863
      'specifier' => $name,
864
      'direction' => $direction,
865
    );
866
    return $this;
867
  }
868

    
869
  /**
870
   * Orders the result set by a given field column.
871
   *
872
   * If called multiple times, the query will order by each specified column in
873
   * the order this method is called. Note that entities with empty field
874
   * values will be excluded from the EntityFieldQuery results when using this
875
   * method.
876
   *
877
   * @param $field
878
   *   Either a field name or a field array.
879
   * @param $column
880
   *   A column defined in the hook_field_schema() of this field. entity_id and
881
   *   bundle can also be used.
882
   * @param $direction
883
   *   The direction to sort. Legal values are "ASC" and "DESC".
884
   *
885
   * @return EntityFieldQuery
886
   *   The called object.
887
   */
888
  public function fieldOrderBy($field, $column, $direction = 'ASC') {
889
    if (is_scalar($field)) {
890
      $field_definition = field_info_field($field);
891
      if (empty($field_definition)) {
892
        throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
893
      }
894
      $field = $field_definition;
895
    }
896
    // Save the index used for the new field, for later use in field storage.
897
    $index = count($this->fields);
898
    $this->fields[$index] = $field;
899
    $this->order[] = array(
900
      'type' => 'field',
901
      'specifier' => array(
902
        'field' => $field,
903
        'index' => $index,
904
        'column' => $column,
905
      ),
906
      'direction' => $direction,
907
    );
908
    return $this;
909
  }
910

    
911
  /**
912
   * Orders the result set by an entity-specific property.
913
   *
914
   * An $entity_type must be specified by calling
915
   * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
916
   * executing the query.
917
   *
918
   * If called multiple times, the query will order by each specified column in
919
   * the order this method is called.
920
   *
921
   * @param $column
922
   *   The column on which to order.
923
   * @param $direction
924
   *   The direction to sort. Legal values are "ASC" and "DESC".
925
   *
926
   * @return EntityFieldQuery
927
   *   The called object.
928
   */
929
  public function propertyOrderBy($column, $direction = 'ASC') {
930
    $this->order[] = array(
931
      'type' => 'property',
932
      'specifier' => $column,
933
      'direction' => $direction,
934
    );
935
    return $this;
936
  }
937

    
938
  /**
939
   * Sets the query to be a count query only.
940
   *
941
   * @return EntityFieldQuery
942
   *   The called object.
943
   */
944
  public function count() {
945
    $this->count = TRUE;
946
    return $this;
947
  }
948

    
949
  /**
950
   * Restricts a query to a given range in the result set.
951
   *
952
   * @param $start
953
   *   The first entity from the result set to return. If NULL, removes any
954
   *   range directives that are set.
955
   * @param $length
956
   *   The number of entities to return from the result set.
957
   *
958
   * @return EntityFieldQuery
959
   *   The called object.
960
   */
961
  public function range($start = NULL, $length = NULL) {
962
    $this->range = array(
963
      'start' => $start,
964
      'length' => $length,
965
    );
966
    return $this;
967
  }
968

    
969
  /**
970
   * Enables a pager for the query.
971
   *
972
   * @param $limit
973
   *   An integer specifying the number of elements per page.  If passed a false
974
   *   value (FALSE, 0, NULL), the pager is disabled.
975
   * @param $element
976
   *   An optional integer to distinguish between multiple pagers on one page.
977
   *   If not provided, one is automatically calculated.
978
   *
979
   * @return EntityFieldQuery
980
   *   The called object.
981
   */
982
  public function pager($limit = 10, $element = NULL) {
983
    if (!isset($element)) {
984
      $element = PagerDefault::$maxElement++;
985
    }
986
    elseif ($element >= PagerDefault::$maxElement) {
987
      PagerDefault::$maxElement = $element + 1;
988
    }
989

    
990
    $this->pager = array(
991
      'limit' => $limit,
992
      'element' => $element,
993
    );
994
    return $this;
995
  }
996

    
997
  /**
998
   * Enables sortable tables for this query.
999
   *
1000
   * @param $headers
1001
   *   An EFQ Header array based on which the order clause is added to the
1002
   *   query.
1003
   *
1004
   * @return EntityFieldQuery
1005
   *   The called object.
1006
   */
1007
  public function tableSort(&$headers) {
1008
    // If 'field' is not initialized, the header columns aren't clickable
1009
    foreach ($headers as $key =>$header) {
1010
      if (is_array($header) && isset($header['specifier'])) {
1011
        $headers[$key]['field'] = '';
1012
      }
1013
    }
1014

    
1015
    $order = tablesort_get_order($headers);
1016
    $direction = tablesort_get_sort($headers);
1017
    foreach ($headers as $header) {
1018
      if (is_array($header) && ($header['data'] == $order['name'])) {
1019
        if ($header['type'] == 'field') {
1020
          $this->fieldOrderBy($header['specifier']['field'], $header['specifier']['column'], $direction);
1021
        }
1022
        else {
1023
          $header['direction'] = $direction;
1024
          $this->order[] = $header;
1025
        }
1026
      }
1027
    }
1028

    
1029
    return $this;
1030
  }
1031

    
1032
  /**
1033
   * Filters on the data being deleted.
1034
   *
1035
   * @param $deleted
1036
   *   TRUE to only return deleted data, FALSE to return non-deleted data,
1037
   *   EntityFieldQuery::RETURN_ALL to return everything. Defaults to FALSE.
1038
   *
1039
   * @return EntityFieldQuery
1040
   *   The called object.
1041
   */
1042
  public function deleted($deleted = TRUE) {
1043
    $this->deleted = $deleted;
1044
    return $this;
1045
  }
1046

    
1047
  /**
1048
   * Queries the current or every revision.
1049
   *
1050
   * Note that this only affects field conditions. Property conditions always
1051
   * apply to the current revision.
1052
   * @TODO: Once revision tables have been cleaned up, revisit this.
1053
   *
1054
   * @param $age
1055
   *   - FIELD_LOAD_CURRENT (default): Query the most recent revisions for all
1056
   *     entities. The results will be keyed by entity type and entity ID.
1057
   *   - FIELD_LOAD_REVISION: Query all revisions. The results will be keyed by
1058
   *     entity type and entity revision ID.
1059
   *
1060
   * @return EntityFieldQuery
1061
   *   The called object.
1062
   */
1063
  public function age($age) {
1064
    $this->age = $age;
1065
    return $this;
1066
  }
1067

    
1068
  /**
1069
   * Adds a tag to the query.
1070
   *
1071
   * Tags are strings that mark a query so that hook_query_alter() and
1072
   * hook_query_TAG_alter() implementations may decide if they wish to alter
1073
   * the query. A query may have any number of tags, and they must be valid PHP
1074
   * identifiers (composed of letters, numbers, and underscores). For example,
1075
   * queries involving nodes that will be displayed for a user need to add the
1076
   * tag 'node_access', so that the node module can add access restrictions to
1077
   * the query.
1078
   *
1079
   * If an entity field query has tags, it must also have an entity type
1080
   * specified, because the alter hook will need the entity base table.
1081
   *
1082
   * @param string $tag
1083
   *   The tag to add.
1084
   *
1085
   * @return EntityFieldQuery
1086
   *   The called object.
1087
   */
1088
  public function addTag($tag) {
1089
    $this->tags[$tag] = $tag;
1090
    return $this;
1091
  }
1092

    
1093
  /**
1094
   * Adds additional metadata to the query.
1095
   *
1096
   * Sometimes a query may need to provide additional contextual data for the
1097
   * alter hook. The alter hook implementations may then use that information
1098
   * to decide if and how to take action.
1099
   *
1100
   * @param $key
1101
   *   The unique identifier for this piece of metadata. Must be a string that
1102
   *   follows the same rules as any other PHP identifier.
1103
   * @param $object
1104
   *   The additional data to add to the query. May be any valid PHP variable.
1105
   *
1106
   * @return EntityFieldQuery
1107
   *   The called object.
1108
   */
1109
  public function addMetaData($key, $object) {
1110
    $this->metaData[$key] = $object;
1111
    return $this;
1112
  }
1113

    
1114
  /**
1115
   * Executes the query.
1116
   *
1117
   * After executing the query, $this->orderedResults will contain a list of
1118
   * the same stub entities in the order returned by the query. This is only
1119
   * relevant if there are multiple entity types in the returned value and
1120
   * a field ordering was requested. In every other case, the returned value
1121
   * contains everything necessary for processing.
1122
   *
1123
   * @return
1124
   *   Either a number if count() was called or an array of associative arrays
1125
   *   of stub entities. The outer array keys are entity types, and the inner
1126
   *   array keys are the relevant ID. (In most cases this will be the entity
1127
   *   ID. The only exception is when age=FIELD_LOAD_REVISION is used and field
1128
   *   conditions or sorts are present -- in this case, the key will be the
1129
   *   revision ID.) The entity type will only exist in the outer array if
1130
   *   results were found. The inner array values are always stub entities, as
1131
   *   returned by entity_create_stub_entity(). To traverse the returned array:
1132
   *   @code
1133
   *     foreach ($query->execute() as $entity_type => $entities) {
1134
   *       foreach ($entities as $entity_id => $entity) {
1135
   *   @endcode
1136
   *   Note if the entity type is known, then the following snippet will load
1137
   *   the entities found:
1138
   *   @code
1139
   *     $result = $query->execute();
1140
   *     if (!empty($result[$my_type])) {
1141
   *       $entities = entity_load($my_type, array_keys($result[$my_type]));
1142
   *     }
1143
   *   @endcode
1144
   */
1145
  public function execute() {
1146
    // Give a chance to other modules to alter the query.
1147
    drupal_alter('entity_query', $this);
1148
    $this->altered = TRUE;
1149

    
1150
    // Initialize the pager.
1151
    $this->initializePager();
1152

    
1153
    // Execute the query using the correct callback.
1154
    $result = call_user_func($this->queryCallback(), $this);
1155

    
1156
    return $result;
1157
  }
1158

    
1159
  /**
1160
   * Determines the query callback to use for this entity query.
1161
   *
1162
   * @return
1163
   *   A callback that can be used with call_user_func().
1164
   */
1165
  public function queryCallback() {
1166
    // Use the override from $this->executeCallback. It can be set either
1167
    // while building the query, or using hook_entity_query_alter().
1168
    if (function_exists($this->executeCallback)) {
1169
      return $this->executeCallback;
1170
    }
1171
    // If there are no field conditions and sorts, and no execute callback
1172
    // then we default to querying entity tables in SQL.
1173
    if (empty($this->fields)) {
1174
      return array($this, 'propertyQuery');
1175
    }
1176
    // If no override, find the storage engine to be used.
1177
    foreach ($this->fields as $field) {
1178
      if (!isset($storage)) {
1179
        $storage = $field['storage']['module'];
1180
      }
1181
      elseif ($storage != $field['storage']['module']) {
1182
        throw new EntityFieldQueryException(t("Can't handle more than one field storage engine"));
1183
      }
1184
    }
1185
    if ($storage) {
1186
      // Use hook_field_storage_query() from the field storage.
1187
      return $storage . '_field_storage_query';
1188
    }
1189
    else {
1190
      throw new EntityFieldQueryException(t("Field storage engine not found."));
1191
    }
1192
  }
1193

    
1194
  /**
1195
   * Queries entity tables in SQL for property conditions and sorts.
1196
   *
1197
   * This method is only used if there are no field conditions and sorts.
1198
   *
1199
   * @return
1200
   *   See EntityFieldQuery::execute().
1201
   */
1202
  protected function propertyQuery() {
1203
    if (empty($this->entityConditions['entity_type'])) {
1204
      throw new EntityFieldQueryException(t('For this query an entity type must be specified.'));
1205
    }
1206
    $entity_type = $this->entityConditions['entity_type']['value'];
1207
    $entity_info = entity_get_info($entity_type);
1208
    if (empty($entity_info['base table'])) {
1209
      throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
1210
    }
1211
    $base_table = $entity_info['base table'];
1212
    $base_table_schema = drupal_get_schema($base_table);
1213
    $select_query = db_select($base_table);
1214
    $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
1215
    // Process the property conditions.
1216
    foreach ($this->propertyConditions as $property_condition) {
1217
      $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
1218
    }
1219
    // Process the four possible entity condition.
1220
    // The id field is always present in entity keys.
1221
    $sql_field = $entity_info['entity keys']['id'];
1222
    $id_map['entity_id'] = $sql_field;
1223
    $select_query->addField($base_table, $sql_field, 'entity_id');
1224
    if (isset($this->entityConditions['entity_id'])) {
1225
      $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['entity_id']);
1226
    }
1227

    
1228
    // If there is a revision key defined, use it.
1229
    if (!empty($entity_info['entity keys']['revision'])) {
1230
      $sql_field = $entity_info['entity keys']['revision'];
1231
      $select_query->addField($base_table, $sql_field, 'revision_id');
1232
      if (isset($this->entityConditions['revision_id'])) {
1233
        $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['revision_id']);
1234
      }
1235
    }
1236
    else {
1237
      $sql_field = 'revision_id';
1238
      $select_query->addExpression('NULL', 'revision_id');
1239
    }
1240
    $id_map['revision_id'] = $sql_field;
1241

    
1242
    // Handle bundles.
1243
    if (!empty($entity_info['entity keys']['bundle'])) {
1244
      $sql_field = $entity_info['entity keys']['bundle'];
1245
      $having = FALSE;
1246

    
1247
      if (!empty($base_table_schema['fields'][$sql_field])) {
1248
        $select_query->addField($base_table, $sql_field, 'bundle');
1249
      }
1250
    }
1251
    else {
1252
      $sql_field = 'bundle';
1253
      $select_query->addExpression(':bundle', 'bundle', array(':bundle' => $entity_type));
1254
      $having = TRUE;
1255
    }
1256
    $id_map['bundle'] = $sql_field;
1257
    if (isset($this->entityConditions['bundle'])) {
1258
      if (!empty($entity_info['entity keys']['bundle'])) {
1259
        $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['bundle'], $having);
1260
      }
1261
      else {
1262
        // This entity has no bundle, so invalidate the query.
1263
        $select_query->where('1 = 0');
1264
      }
1265
    }
1266

    
1267
    // Order the query.
1268
    foreach ($this->order as $order) {
1269
      if ($order['type'] == 'entity') {
1270
        $key = $order['specifier'];
1271
        if (!isset($id_map[$key])) {
1272
          throw new EntityFieldQueryException(t('Do not know how to order on @key for @entity_type', array('@key' => $key, '@entity_type' => $entity_type)));
1273
        }
1274
        $select_query->orderBy($id_map[$key], $order['direction']);
1275
      }
1276
      elseif ($order['type'] == 'property') {
1277
        $select_query->orderBy($base_table . '.' . $order['specifier'], $order['direction']);
1278
      }
1279
    }
1280

    
1281
    return $this->finishQuery($select_query);
1282
  }
1283

    
1284
  /**
1285
   * Gets the total number of results and initializes a pager for the query.
1286
   *
1287
   * The pager can be disabled by either setting the pager limit to 0, or by
1288
   * setting this query to be a count query.
1289
   */
1290
  function initializePager() {
1291
    if ($this->pager && !empty($this->pager['limit']) && !$this->count) {
1292
      $page = pager_find_page($this->pager['element']);
1293
      $count_query = clone $this;
1294
      $this->pager['total'] = $count_query->count()->execute();
1295
      $this->pager['start'] = $page * $this->pager['limit'];
1296
      pager_default_initialize($this->pager['total'], $this->pager['limit'], $this->pager['element']);
1297
      $this->range($this->pager['start'], $this->pager['limit']);
1298
    }
1299
  }
1300

    
1301
  /**
1302
   * Finishes the query.
1303
   *
1304
   * Adds tags, metaData, range and returns the requested list or count.
1305
   *
1306
   * @param SelectQuery $select_query
1307
   *   A SelectQuery which has entity_type, entity_id, revision_id and bundle
1308
   *   fields added.
1309
   * @param $id_key
1310
   *   Which field's values to use as the returned array keys.
1311
   *
1312
   * @return
1313
   *   See EntityFieldQuery::execute().
1314
   */
1315
  function finishQuery($select_query, $id_key = 'entity_id') {
1316
    foreach ($this->tags as $tag) {
1317
      $select_query->addTag($tag);
1318
    }
1319
    foreach ($this->metaData as $key => $object) {
1320
      $select_query->addMetaData($key, $object);
1321
    }
1322
    $select_query->addMetaData('entity_field_query', $this);
1323
    if ($this->range) {
1324
      $select_query->range($this->range['start'], $this->range['length']);
1325
    }
1326
    if ($this->count) {
1327
      return $select_query->countQuery()->execute()->fetchField();
1328
    }
1329
    $return = array();
1330
    foreach ($select_query->execute() as $partial_entity) {
1331
      $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
1332
      $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
1333
      $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
1334
      $this->ordered_results[] = $partial_entity;
1335
    }
1336
    return $return;
1337
  }
1338

    
1339
  /**
1340
   * Adds a condition to an already built SelectQuery (internal function).
1341
   *
1342
   * This is a helper for hook_entity_query() and hook_field_storage_query().
1343
   *
1344
   * @param SelectQuery $select_query
1345
   *   A SelectQuery object.
1346
   * @param $sql_field
1347
   *   The name of the field.
1348
   * @param $condition
1349
   *   A condition as described in EntityFieldQuery::fieldCondition() and
1350
   *   EntityFieldQuery::entityCondition().
1351
   * @param $having
1352
   *   HAVING or WHERE. This is necessary because SQL can't handle WHERE
1353
   *   conditions on aliased columns.
1354
   */
1355
  public function addCondition(SelectQuery $select_query, $sql_field, $condition, $having = FALSE) {
1356
    $method = $having ? 'havingCondition' : 'condition';
1357
    $like_prefix = '';
1358
    switch ($condition['operator']) {
1359
      case 'CONTAINS':
1360
        $like_prefix = '%';
1361
      case 'STARTS_WITH':
1362
        $select_query->$method($sql_field, $like_prefix . db_like($condition['value']) . '%', 'LIKE');
1363
        break;
1364
      default:
1365
        $select_query->$method($sql_field, $condition['value'], $condition['operator']);
1366
    }
1367
  }
1368

    
1369
}
1370

    
1371
/**
1372
 * Defines an exception thrown when a malformed entity is passed.
1373
 */
1374
class EntityMalformedException extends Exception { }