Project

General

Profile

Paste
Download (39.6 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / entity / includes / entity.wrapper.inc @ 082b75eb

1
<?php
2

    
3
/**
4
 * @file
5
 * Provides wrappers allowing easy usage of the entity metadata.
6
 */
7

    
8
/**
9
 * A common base class for all wrappers.
10
 */
11
abstract class EntityMetadataWrapper {
12

    
13
  protected $type;
14
  protected $data;
15
  protected $info;
16
  protected $cache = array();
17

    
18
  /**
19
   * Construct a new wrapper object.
20
   *
21
   * @param $type
22
   *   The type of the passed data.
23
   * @param $data
24
   *   Optional. The data to wrap.
25
   * @param $info
26
   *   Optional. Used internally to pass info about properties down the tree.
27
   */
28
  public function __construct($type, $data = NULL, $info = array()) {
29
    $this->type = $type;
30
    $this->info = $info + array(
31
      'langcode' => NULL,
32
    );
33
    $this->info['type'] = $type;
34
    if (isset($data)) {
35
      $this->set($data);
36
    }
37
  }
38

    
39
  /**
40
   * Gets info about the wrapped data.
41
   *
42
   * @return Array
43
   *   Keys set are all keys as specified for a property in hook_entity_info()
44
   *   as well as possible the following keys:
45
   *    - name: If this wraps a property, the name of the property.
46
   *    - parent: The parent wrapper, if any.
47
   *    - langcode: The language code, if this data is language specific.
48
   */
49
  public function info() {
50
    return $this->info;
51
  }
52

    
53
  /**
54
   * Gets the (entity)type of the wrapped data.
55
   */
56
  public function type() {
57
    return $this->type;
58
  }
59

    
60
  /**
61
   * Returns the wrapped data. If no options are given the data is returned as
62
   * described in the info.
63
   *
64
   * @param $options
65
   *   (optional) A keyed array of options:
66
   *   - sanitize: A boolean flag indicating that textual properties should be
67
   *     sanitized for display to a web browser. Defaults to FALSE.
68
   *   - decode: If set to TRUE and some textual data is already sanitized, it
69
   *     strips HTML tags and decodes HTML entities. Defaults to FALSE.
70
   *
71
   *  @return
72
   *    The value of the wrapped data. If the data property is not set, NULL
73
   *    is returned.
74
   *
75
   *  @throws EntityMetadataWrapperException
76
   *    In case there are no data values available to the wrapper, an exception
77
   *    is thrown. E.g. if the value for an entity property is to be retrieved
78
   *    and there is no entity available, the exception is thrown. However, if
79
   *    an entity is available but the property is not set, NULL is returned.
80
   */
81
  public function value(array $options = array()) {
82
    if (!$this->dataAvailable() && isset($this->info['parent'])) {
83
      throw new EntityMetadataWrapperException('Missing data values.');
84
    }
85
    if (!isset($this->data) && isset($this->info['name'])) {
86
      $this->data = $this->info['parent']->getPropertyValue($this->info['name'], $this->info);
87
    }
88
    return $this->data;
89
  }
90

    
91
  /**
92
   * Returns the raw, unprocessed data. Most times this is the same as returned
93
   * by value(), however for already processed and sanitized textual data, this
94
   * will return the unprocessed data in contrast to value().
95
   */
96
  public function raw() {
97
    if (!$this->dataAvailable()) {
98
      throw new EntityMetadataWrapperException('Missing data values.');
99
    }
100
    if (isset($this->info['name']) && isset($this->info['parent'])) {
101
      return $this->info['parent']->getPropertyRaw($this->info['name'], $this->info);
102
    }
103
    // Else return the usual value, which should be raw in this case.
104
    return $this->value();
105
  }
106

    
107
  /**
108
   * Returns whether data is available to work with.
109
   *
110
   * @return
111
   *   If we operate without any data FALSE, else TRUE.
112
   */
113
  protected function dataAvailable() {
114
    return isset($this->data) || (isset($this->info['parent']) && $this->info['parent']->dataAvailable());
115
  }
116

    
117
  /**
118
   * Set a new data value.
119
   */
120
  public function set($value) {
121
    if (!$this->validate($value)) {
122
      throw new EntityMetadataWrapperException(t('Invalid data value given. Be sure it matches the required data type and format. Value at !location: !value.', array(
123
        // An exception's message is output through check_plain().
124
        '!value' => is_array($value) || is_object($value) ? var_export($value, TRUE) : $value,
125
        '!location' => $this->debugIdentifierLocation(),
126
      )));
127
    }
128
    $this->clear();
129
    $this->data = $value;
130
    $this->updateParent($value);
131
    return $this;
132
  }
133

    
134
  /**
135
   * Updates the parent data structure of a data property with the latest data value.
136
   */
137
  protected function updateParent($value) {
138
    if (isset($this->info['parent'])) {
139
      $this->info['parent']->setProperty($this->info['name'], $value);
140
    }
141
  }
142

    
143
  /**
144
   * Returns whether $value is a valid value to set.
145
   */
146
  public function validate($value) {
147
    if (isset($value) && !entity_property_verify_data_type($value, $this->type)) {
148
      return FALSE;
149
    }
150
    // Only proceed with further checks if this is not a list item. If this is
151
    // a list item, the checks are performed on the list property level.
152
    if (isset($this->info['parent']) && $this->info['parent'] instanceof EntityListWrapper) {
153
      return TRUE;
154
    }
155
    if (!isset($value) && !empty($this->info['required'])) {
156
      // Do not allow NULL values if the property is required.
157
      return FALSE;
158
    }
159
    return !isset($this->info['validation callback']) || call_user_func($this->info['validation callback'], $value, $this->info);
160
  }
161

    
162
  public function __toString() {
163
    return isset($this->info) ? 'Property ' . $this->info['name'] : $this->type;
164
  }
165

    
166
  /**
167
   * Clears the data value and the wrapper cache.
168
   */
169
  protected function clear() {
170
    $this->data = NULL;
171
    foreach ($this->cache as $wrapper) {
172
      $wrapper->clear();
173
    }
174
  }
175

    
176
  /**
177
   * Returns the options list specifying possible values for the property, if
178
   * defined.
179
   *
180
   * @param $op
181
   *   (optional) One of 'edit' or 'view'. In case the list of possible values
182
   *   a user could set for a property differs from the list of values a
183
   *   property could have, $op determines which options should be returned.
184
   *   Defaults to 'edit'.
185
   *   E.g. all possible roles a user could have include the anonymous and the
186
   *   authenticated user roles, while those roles cannot be added to a user
187
   *   account. So their options would be included for 'view', but for 'edit'
188
   *   not.
189
   *
190
   * @return
191
   *   An array as used by hook_options_list() or FALSE.
192
   */
193
  public function optionsList($op = 'edit') {
194
    if (isset($this->info['options list']) && is_callable($this->info['options list'])) {
195
      $name = isset($this->info['name']) ? $this->info['name'] : NULL;
196
      return call_user_func($this->info['options list'], $name, $this->info, $op);
197
    }
198
    return FALSE;
199
  }
200

    
201
  /**
202
   * Returns the label for the currently set property value if there is one
203
   * available, i.e. if an options list has been specified.
204
   */
205
  public function label() {
206
    if ($options = $this->optionsList('view')) {
207
      $options = entity_property_options_flatten($options);
208
      $value = $this->value();
209
      if (is_scalar($value) && isset($options[$value])) {
210
        return $options[$value];
211
      }
212
    }
213
  }
214

    
215
  /**
216
   * Determines whether the given user has access to view or edit this property.
217
   * Apart from relying on access metadata of properties, this takes into
218
   * account information about entity level access, if available:
219
   *  - Referenced entities can only be viewed, when the user also has
220
   *    permission to view the entity.
221
   *  - A property may be only edited, if the user has permission to update the
222
   *    entity containing the property.
223
   *
224
   * @param $op
225
   *   The operation being performed. One of 'view' or 'edit.
226
   * @param $account
227
   *   The user to check for. Leave it to NULL to check for the global user.
228
   * @return boolean
229
   *   Whether access to entity property is allowed for the given operation.
230
   *   However if we wrap no data, it returns whether access is allowed to the
231
   *   property of all entities of this type.
232
   *   If there is no access information for this property, TRUE is returned.
233
   */
234
  public function access($op, $account = NULL) {
235
    return !empty($this->info['parent']) ? $this->info['parent']->propertyAccess($this->info['name'], $op, $account) : TRUE;
236
  }
237

    
238
  /**
239
   * Returns a string to use to identify this wrapper in error messages.
240
   *
241
   * @return
242
   *  A string that identifies this wrapper and its chain of ancestors, of the
243
   *  form 'grandparentidentifier->parentidentifier->identifier'.
244
   */
245
  public function debugIdentifierLocation() {
246
    $debug = $this->info['name'];
247
    if (isset($this->info['parent'])) {
248
      $debug = $this->info['parent']->debugIdentifierLocation() . '->' . $debug;
249
    }
250
    return $debug;
251
  }
252

    
253
  /**
254
   * Prepare for serializiation.
255
   */
256
  public function __sleep() {
257
    $vars = get_object_vars($this);
258
    unset($vars['cache']);
259
    return drupal_map_assoc(array_keys($vars));
260
  }
261
}
262

    
263
/**
264
 * Wraps a single value.
265
 */
266
class EntityValueWrapper extends EntityMetadataWrapper {
267

    
268
  /**
269
   * Overrides EntityMetadataWrapper#value().
270
   * Sanitizes or decode textual data if necessary.
271
   */
272
  public function value(array $options = array()) {
273
    $data = parent::value();
274
    if ($this->type == 'text' && isset($data)) {
275
      $info = $this->info + array('sanitized' => FALSE, 'sanitize' => 'check_plain');
276
      $options += array('sanitize' => FALSE, 'decode' => FALSE);
277
      if ($options['sanitize'] && !$info['sanitized']) {
278
        return call_user_func($info['sanitize'], $data);
279
      }
280
      elseif ($options['decode'] && $info['sanitized']) {
281
        return decode_entities(strip_tags($data));
282
      }
283
    }
284
    return $data;
285
  }
286
}
287

    
288
/**
289
 * Provides a general wrapper for any data structure. For this to work the
290
 * metadata has to be passed during construction.
291
 */
292
class EntityStructureWrapper extends EntityMetadataWrapper implements IteratorAggregate {
293

    
294
  protected $propertyInfo = array(), $propertyInfoAltered = FALSE;
295
  protected $langcode = LANGUAGE_NONE;
296

    
297
  protected $propertyInfoDefaults = array(
298
    'type' => 'text',
299
    'getter callback' => 'entity_property_verbatim_get',
300
    'clear' => array(),
301
  );
302

    
303
  /**
304
   * Construct a new EntityStructureWrapper object.
305
   *
306
   * @param $type
307
   *   The type of the passed data.
308
   * @param $data
309
   *   Optional. The data to wrap.
310
   * @param $info
311
   *   Used to for specifying metadata about the data and internally to pass
312
   *   info about properties down the tree. For specifying metadata known keys
313
   *   are:
314
   *   - property info: An array of info about the properties of the wrapped
315
   *     data structure. It has to contain an array of property info in the same
316
   *     structure as used by hook_entity_property_info().
317
   */
318
  public function __construct($type, $data = NULL, $info = array()) {
319
    parent::__construct($type, $data, $info);
320
    $this->info += array('property defaults' => array());
321
    $info += array('property info' => array());
322
    $this->propertyInfo['properties'] = $info['property info'];
323
  }
324

    
325
  /**
326
   * May be used to lazy-load additional info about the data, depending on the
327
   * concrete passed data.
328
   */
329
  protected function spotInfo() {
330
    // Apply the callback if set, such that the caller may alter the info.
331
    if (!empty($this->info['property info alter']) && !$this->propertyInfoAltered) {
332
      $this->propertyInfo = call_user_func($this->info['property info alter'], $this, $this->propertyInfo);
333
      $this->propertyInfoAltered = TRUE;
334
    }
335
  }
336

    
337
  /**
338
   * Gets the info about the given property.
339
   *
340
   * @param $name
341
   *   The name of the property. If not given, info about all properties will
342
   *   be returned.
343
   * @throws EntityMetadataWrapperException
344
   *   If there is no such property.
345
   * @return
346
   *   An array of info about the property.
347
   */
348
  public function getPropertyInfo($name = NULL) {
349
    $this->spotInfo();
350
    if (!isset($name)) {
351
      return $this->propertyInfo['properties'];
352
    }
353
    if (!isset($this->propertyInfo['properties'][$name])) {
354
      throw new EntityMetadataWrapperException('Unknown data property ' . check_plain($name) . '.');
355
    }
356
    return $this->propertyInfo['properties'][$name] + $this->info['property defaults'] + $this->propertyInfoDefaults;
357
  }
358

    
359
  /**
360
   * Returns a reference on the property info.
361
   *
362
   * If possible, use the property info alter callback for spotting metadata.
363
   * The reference may be used to alter the property info for any remaining
364
   * cases, e.g. if additional metadata has been asserted.
365
   */
366
  public function &refPropertyInfo() {
367
    return $this->propertyInfo;
368
  }
369

    
370
  /**
371
   * Sets a new language to use for retrieving properties.
372
   *
373
   * @param $langcode
374
   *   The language code of the language to set.
375
   * @return EntityWrapper
376
   */
377
  public function language($langcode = LANGUAGE_NONE) {
378
    if ($langcode != $this->langcode) {
379
      $this->langcode = $langcode;
380
      $this->cache = array();
381
    }
382
    return $this;
383
  }
384

    
385
  /**
386
   * Gets the language used for retrieving properties.
387
   *
388
   * @return String
389
   *   The language object of the language or NULL for the default language.
390
   *
391
   * @see EntityStructureWrapper::language()
392
   */
393
  public function getPropertyLanguage() {
394
    if ($this->langcode != LANGUAGE_NONE && $list = language_list()) {
395
      if (isset($list[$this->langcode])) {
396
        return $list[$this->langcode];
397
      }
398
    }
399
    return NULL;
400
  }
401

    
402
  /**
403
   * Get the wrapper for a property.
404
   *
405
   * @return
406
   *   An instance of EntityMetadataWrapper.
407
   */
408
  public function get($name) {
409
    // Look it up in the cache if possible.
410
    if (!array_key_exists($name, $this->cache)) {
411
      if ($info = $this->getPropertyInfo($name)) {
412
        $info += array('parent' => $this, 'name' => $name, 'langcode' => $this->langcode, 'property defaults' => array());
413
        $info['property defaults'] += $this->info['property defaults'];
414
        $this->cache[$name] = entity_metadata_wrapper($info['type'], NULL, $info);
415
      }
416
      else {
417
        throw new EntityMetadataWrapperException('There is no property ' . check_plain($name) . " for this entity.");
418
      }
419
    }
420
    return $this->cache[$name];
421
  }
422

    
423
  /**
424
   * Magic method: Get a wrapper for a property.
425
   */
426
  public function __get($name) {
427
    if (strpos($name, 'krumo') === 0) {
428
      // #914934 Ugly workaround to allow krumo to write its recursion property.
429
      // This is necessary to make dpm() work without throwing exceptions.
430
      return NULL;
431
    }
432
    $get = $this->get($name);
433
    return $get;
434
  }
435

    
436
  /**
437
   * Magic method: Set a property.
438
   */
439
  public function __set($name, $value) {
440
    if (strpos($name, 'krumo') === 0) {
441
      // #914934 Ugly workaround to allow krumo to write its recursion property.
442
      // This is necessary to make dpm() work without throwing exceptions.
443
      $this->$name = $value;
444
    }
445
    else {
446
      $this->get($name)->set($value);
447
    }
448
  }
449

    
450
  /**
451
   * Gets the value of a property.
452
   */
453
  protected function getPropertyValue($name, &$info) {
454
    $options = array('language' => $this->getPropertyLanguage(), 'absolute' => TRUE);
455
    $data = $this->value();
456
    if (!isset($data)) {
457
      throw new EntityMetadataWrapperException('Unable to get the data property ' . check_plain($name) . ' as the parent data structure is not set.');
458
    }
459
    return $info['getter callback']($data, $options, $name, $this->type, $info);
460
  }
461

    
462
  /**
463
   * Gets the raw value of a property.
464
   */
465
  protected function getPropertyRaw($name, &$info) {
466
    if (!empty($info['raw getter callback'])) {
467
      $options = array('language' => $this->getPropertyLanguage(), 'absolute' => TRUE);
468
      $data = $this->value();
469
      if (!isset($data)) {
470
        throw new EntityMetadataWrapperException('Unable to get the data property ' . check_plain($name) . ' as the parent data structure is not set.');
471
      }
472
      return $info['raw getter callback']($data, $options, $name, $this->type, $info);
473
    }
474
    return $this->getPropertyValue($name, $info);
475
  }
476

    
477
  /**
478
   * Sets a property.
479
   */
480
  protected function setProperty($name, $value) {
481
    $info = $this->getPropertyInfo($name);
482
    if (!empty($info['setter callback'])) {
483
      $data = $this->value();
484

    
485
      // In case the data structure is not set, support simple auto-creation
486
      // for arrays. Else an exception is thrown.
487
      if (!isset($data)) {
488
        if (!empty($this->info['auto creation']) && !($this instanceof EntityDrupalWrapper)) {
489
          $data = $this->info['auto creation']($name, $this->info);
490
        }
491
        else {
492
          throw new EntityMetadataWrapperException('Unable to set the data property ' . check_plain($name) . ' as the parent data structure is not set.');
493
        }
494
      }
495

    
496
      // Invoke the setter callback for updating our data.
497
      $info['setter callback']($data, $name, $value, $this->langcode, $this->type, $info);
498

    
499
      // If the setter has not thrown any exceptions, proceed and apply the
500
      // update to the current and any parent wrappers as necessary.
501
      $data = $this->info['type'] == 'entity' ? $this : $data;
502
      $this->set($data);
503

    
504
      // Clear the cache of properties dependent on this value.
505
      foreach ($info['clear'] as $name) {
506
        if (isset($this->cache[$name])) {
507
          $this->cache[$name]->clear();
508
        }
509
      }
510
    }
511
    else {
512
      throw new EntityMetadataWrapperException('Entity property ' . check_plain($name) . " doesn't support writing.");
513
    }
514
  }
515

    
516
  protected function propertyAccess($name, $op, $account = NULL) {
517
    $info = $this->getPropertyInfo($name);
518

    
519
    // If a property should be edited and this is part of an entity, make sure
520
    // the user has update access for this entity.
521
    if ($op == 'edit') {
522
      $entity = $this;
523
      while (!($entity instanceof EntityDrupalWrapper) && isset($entity->info['parent'])) {
524
        $entity = $entity->info['parent'];
525
      }
526
      if ($entity instanceof EntityDrupalWrapper && $entity->entityAccess('update', $account) === FALSE) {
527
        return FALSE;
528
      }
529
    }
530
    if (!empty($info['access callback'])) {
531
      $data = $this->dataAvailable() ? $this->value() : NULL;
532
      return call_user_func($info['access callback'], $op, $name, $data, $account, $this->type);
533
    }
534
    elseif ($op == 'edit' && isset($info['setter permission'])) {
535
      return user_access($info['setter permission'], $account);
536
    }
537
    // If access is unknown, we return TRUE.
538
    return TRUE;
539
  }
540

    
541
  /**
542
   * Magic method: Can be used to check if a property is known.
543
   */
544
  public function __isset($name) {
545
    $this->spotInfo();
546
    return isset($this->propertyInfo['properties'][$name]);
547
  }
548

    
549
  public function getIterator() {
550
    $this->spotInfo();
551
    return new EntityMetadataWrapperIterator($this, array_keys($this->propertyInfo['properties']));
552
  }
553

    
554
  /**
555
   * Returns the identifier of the data structure. If there is none, NULL is
556
   * returned.
557
   */
558
  public function getIdentifier() {
559
    return isset($this->id) && $this->dataAvailable() ? $this->id->value() : NULL;
560
  }
561

    
562
  /**
563
   * Prepare for serializiation.
564
   */
565
  public function __sleep() {
566
    $vars = parent::__sleep();
567
    unset($vars['propertyInfoDefaults']);
568
    return $vars;
569
  }
570

    
571
  public function clear() {
572
    $this->propertyInfoAltered = FALSE;
573
    parent::clear();
574
  }
575
}
576

    
577
/**
578
 * Provides a wrapper for entities registrered in hook_entity_info().
579
 *
580
 * The wrapper eases applying getter and setter callbacks of entity properties
581
 * specified in hook_entity_property_info().
582
 */
583
class EntityDrupalWrapper extends EntityStructureWrapper {
584

    
585
  /**
586
   * Contains the entity id.
587
   */
588
  protected $id = FALSE;
589
  protected $bundle;
590
  protected $entityInfo;
591

    
592
  /**
593
   * Construct a new EntityDrupalWrapper object.
594
   *
595
   * @param $type
596
   *   The type of the passed data.
597
   * @param $data
598
   *   Optional. The entity to wrap or its identifier.
599
   * @param $info
600
   *   Optional. Used internally to pass info about properties down the tree.
601
   */
602
  public function __construct($type, $data = NULL, $info = array()) {
603
    parent::__construct($type, $data, $info);
604
    $this->setUp();
605
  }
606

    
607
  protected function setUp() {
608
    $this->propertyInfo = entity_get_property_info($this->type) + array('properties' => array());
609
    $info = $this->info + array('property info' => array(), 'bundle' => NULL);
610
    $this->propertyInfo['properties'] += $info['property info'];
611
    $this->bundle = $info['bundle'];
612
    $this->entityInfo = entity_get_info($this->type);
613
    if (isset($this->bundle)) {
614
      $this->spotBundleInfo(FALSE);
615
    }
616
  }
617

    
618
  /**
619
   * Sets the entity internally accepting both the entity id and object.
620
   */
621
  protected function setEntity($data) {
622
    // For entities we allow getter callbacks to return FALSE, which we
623
    // interpret like NULL values as unset properties.
624
    if (isset($data) && $data !== FALSE && !is_object($data)) {
625
      $this->id = $data;
626
      $this->data = FALSE;
627
    }
628
    elseif (is_object($data) && $data instanceof EntityDrupalWrapper) {
629
      // We got a wrapped entity passed, so take over its values.
630
      $this->id = $data->id;
631
      $this->data = $data->data;
632
      // For generic entity references, also update the entity type accordingly.
633
      if ($this->info['type'] == 'entity') {
634
        $this->type = $data->type;
635
      }
636
    }
637
    elseif (is_object($data)) {
638
      // We got the entity object passed.
639
      $this->data = $data;
640
      $id = entity_id($this->type, $data);
641
      $this->id = isset($id) ? $id : FALSE;
642
    }
643
    else {
644
      $this->id = FALSE;
645
      $this->data = NULL;
646
    }
647
  }
648

    
649
  /**
650
   * Used to lazy-load bundle info. So the wrapper can be loaded e.g. just
651
   * for setting without the data being loaded.
652
   */
653
  protected function spotInfo() {
654
    if (!$this->propertyInfoAltered) {
655
      if ($this->info['type'] == 'entity' && $this->dataAvailable() && $this->value()) {
656
        // Add in entity-type specific details.
657
        $this->setUp();
658
      }
659
      $this->spotBundleInfo(TRUE);
660
      parent::spotInfo();
661
      $this->propertyInfoAltered = TRUE;
662
    }
663
  }
664

    
665
  /**
666
   * Tries to determine the bundle and adds in the according property info.
667
   *
668
   * @param $load
669
   *   Whether the entity should be loaded to spot the info if necessary.
670
   */
671
  protected function spotBundleInfo($load = TRUE) {
672
    // Like entity_extract_ids() assume the entity type if no key is given.
673
    if (empty($this->entityInfo['entity keys']['bundle']) && $this->type != 'entity') {
674
      $this->bundle = $this->type;
675
    }
676
    // Detect the bundle if not set yet and add in properties from the bundle.
677
    elseif (!$this->bundle && $load && $this->dataAvailable()) {
678
      try {
679
        if ($entity = $this->value()) {
680
          list($id, $vid, $bundle) = entity_extract_ids($this->type, $entity);
681
          $this->bundle = $bundle;
682
        }
683
      }
684
      catch (EntityMetadataWrapperException $e) {
685
        // Loading data failed, so we cannot derive the used bundle.
686
      }
687
    }
688

    
689
    if ($this->bundle && isset($this->propertyInfo['bundles'][$this->bundle])) {
690
      $bundle_info = (array) $this->propertyInfo['bundles'][$this->bundle] + array('properties' => array());
691
      // Allow bundles to re-define existing properties, such that the bundle
692
      // can add in more bundle-specific details like the bundle of a referenced
693
      // entity.
694
      $this->propertyInfo['properties'] = $bundle_info['properties'] + $this->propertyInfo['properties'];
695
    }
696
  }
697

    
698
  /**
699
   * Returns the identifier of the wrapped entity.
700
   *
701
   * @see entity_id()
702
   */
703
  public function getIdentifier() {
704
    return $this->dataAvailable() ? $this->value(array('identifier' => TRUE)) : NULL;
705
  }
706

    
707
  /**
708
   * Returns the bundle of an entity, or FALSE if it has no bundles.
709
   */
710
  public function getBundle() {
711
    if ($this->dataAvailable()) {
712
      $this->spotInfo();
713
      return $this->bundle;
714
    }
715
  }
716

    
717
  /**
718
   * Overridden.
719
   *
720
   * @param $options
721
   *   An array of options. Known keys:
722
   *   - identifier: If set to TRUE, the entity identifier is returned.
723
   */
724
  public function value(array $options = array()) {
725
    // Try loading the data via the getter callback if there is none yet.
726
    if (!isset($this->data)) {
727
      $this->setEntity(parent::value());
728
    }
729
    if (!empty($options['identifier'])) {
730
      return $this->id;
731
    }
732
    elseif (!$this->data && !empty($this->id)) {
733
      // Lazy load the entity if necessary.
734
      $return = entity_load($this->type, array($this->id));
735
      // In case the entity cannot be loaded, we return NULL just as for empty
736
      // properties.
737
      $this->data = $return ? reset($return) : NULL;
738
    }
739
    return $this->data;
740
  }
741

    
742
  /**
743
   * Returns the entity prepared for rendering.
744
   *
745
   * @see entity_view()
746
   */
747
  public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
748
    return entity_view($this->type(), array($this->value()), $view_mode, $langcode, $page);
749
  }
750

    
751
  /**
752
   * Overridden to support setting the entity by either the object or the id.
753
   */
754
  public function set($value) {
755
    if (!$this->validate($value)) {
756
      throw new EntityMetadataWrapperException(t('Invalid data value given. Be sure it matches the required data type and format. Value at !location: !value.', array(
757
        // An exception's message is output through check_plain().
758
        '!value' => is_array($value) || is_object($value) ? var_export($value, TRUE) : $value,
759
        '!location' => $this->debugIdentifierLocation(),
760
      )));
761
    }
762
    if ($this->info['type'] == 'entity' && $value === $this) {
763
      // Nothing to do.
764
      return $this;
765
    }
766
    $previous_id = $this->id;
767
    $previous_type = $this->type;
768
    // Set value, so we get the identifier and pass it to the normal setter.
769
    $this->clear();
770
    $this->setEntity($value);
771
    // Generally, we have to update the parent only if the entity reference
772
    // has changed. In case of a generic entity reference, we pass the entity
773
    // wrapped. Else we just pass the id of the entity to the setter callback.
774
    if ($this->info['type'] == 'entity' && ($previous_id != $this->id || $previous_type != $this->type)) {
775
      // We need to clone the wrapper we pass through as value, so it does not
776
      // get cleared when the current wrapper instance gets cleared.
777
      $this->updateParent(clone $this);
778
    }
779
    // In case the entity has been unset, we cannot properly detect changes as
780
    // the previous id defaults to FALSE for unloaded entities too. So in that
781
    // case we just always update the parent.
782
    elseif ($this->id === FALSE && !$this->data) {
783
      $this->updateParent(NULL);
784
    }
785
    elseif ($previous_id !== $this->id) {
786
      $this->updateParent($this->id);
787
    }
788
    return $this;
789
  }
790

    
791
  /**
792
   * Overridden.
793
   */
794
  public function clear() {
795
    $this->id = NULL;
796
    $this->bundle = isset($this->info['bundle']) ? $this->info['bundle'] : NULL;
797
    if ($this->type != $this->info['type']) {
798
      // Reset entity info / property info based upon the info provided during
799
      // the creation of the wrapper.
800
      $this->type = $this->info['type'];
801
      $this->setUp();
802
    }
803
    parent::clear();
804
  }
805

    
806
  /**
807
   * Overridden.
808
   */
809
  public function type() {
810
    // In case of a generic entity wrapper, load the data first to determine
811
    // the type of the concrete entity.
812
    if ($this->dataAvailable() && $this->info['type'] == 'entity') {
813
      try {
814
        $this->value(array('identifier' => TRUE));
815
      }
816
      catch (EntityMetadataWrapperException $e) {
817
        // If loading data fails, we cannot determine the concrete entity type.
818
      }
819
    }
820
    return $this->type;
821
  }
822

    
823
  /**
824
   * {@inheritdoc}
825
   *
826
   * Note that this method checks property access, but can be used for checking
827
   * entity access *only* if the wrapper is not a property (i.e. has no parent
828
   * wrapper).
829
   * To be safe, better use EntityDrupalWrapper::entityAccess() for checking
830
   * entity access.
831
   */
832
  public function access($op, $account = NULL) {
833
    if (!empty($this->info['parent'])) {
834
      // If this is a property, make sure the user is able to view the
835
      // currently referenced entity also.
836
      if ($this->entityAccess('view', $account) === FALSE) {
837
        return FALSE;
838
      }
839
      if (parent::access($op, $account) === FALSE) {
840
        return FALSE;
841
      }
842
      // If access is unknown, we return TRUE.
843
      return TRUE;
844
    }
845
    else {
846
      // This is not a property, so fallback on entity access.
847
      if ($op == 'edit') {
848
        // If the operation is "edit" determine if its actually a "create" for
849
        // new un-saved entities, or an "update" for existing ones.
850
        return $this->entityAccess($this->getIdentifier() ? 'update' : 'create', $account);
851
      }
852
      return $this->entityAccess('view', $account);
853
    }
854
  }
855

    
856
  /**
857
   * Checks whether the operation $op is allowed on the entity.
858
   *
859
   * @see entity_access()
860
   */
861
  public function entityAccess($op, $account = NULL) {
862
    $entity = $this->dataAvailable() ? $this->value() : NULL;
863
    // The value() method could return FALSE on entities such as user 0, so we
864
    // need to use NULL instead to conform to the expectations of
865
    // entity_access().
866
    if ($entity === FALSE) {
867
      $entity = NULL;
868
    }
869
    return entity_access($op, $this->type, $entity, $account);
870
  }
871

    
872
  /**
873
   * Permanently save the wrapped entity.
874
   *
875
   * @throws EntityMetadataWrapperException
876
   *   If the entity type does not support saving.
877
   *
878
   * @return EntityDrupalWrapper
879
   */
880
  public function save() {
881
    if ($this->data) {
882
      if (!entity_type_supports($this->type, 'save')) {
883
        throw new EntityMetadataWrapperException("There is no information about how to save entities of type " . check_plain($this->type) . '.');
884
      }
885
      entity_save($this->type, $this->data);
886
      // On insert, update the identifier afterwards.
887
      if (!$this->id) {
888
        list($this->id, , ) = entity_extract_ids($this->type, $this->data);
889
      }
890
    }
891
    // If the entity hasn't been loaded yet, don't bother saving it.
892
    return $this;
893
  }
894

    
895
  /**
896
   * Permanently delete the wrapped entity.
897
   *
898
   * @return EntityDrupalWrapper
899
   */
900
  public function delete() {
901
    if ($this->dataAvailable() && $this->value()) {
902
      $return = entity_delete($this->type, $this->id);
903
      if ($return === FALSE) {
904
        throw new EntityMetadataWrapperException("There is no information about how to delete entities of type " . check_plain($this->type) . '.');
905
      }
906
    }
907
    return $this;
908
  }
909

    
910
  /**
911
   * Gets the info about the wrapped entity.
912
   */
913
  public function entityInfo() {
914
    return $this->entityInfo;
915
  }
916

    
917
  /**
918
   * Returns the name of the key used by the entity for given entity key.
919
   *
920
   * @param $name
921
   *   One of 'id', 'name', 'bundle' or 'revision'.
922
   * @return
923
   *   The name of the key used by the entity.
924
   */
925
  public function entityKey($name) {
926
    return isset($this->entityInfo['entity keys'][$name]) ? $this->entityInfo['entity keys'][$name] : FALSE;
927
  }
928

    
929
  /**
930
   * Returns the entity label.
931
   *
932
   * @see entity_label()
933
   */
934
  public function label() {
935
    if ($entity = $this->value()) {
936
      return entity_label($this->type, $entity);
937
    }
938
  }
939

    
940
  /**
941
   * Returns a string to use to identify this wrapper in error messages.
942
   */
943
  public function debugIdentifierLocation() {
944
    // An entity wrapper can be at the top of the chain or a part of it.
945
    if (isset($this->info['name'])) {
946
      // This wrapper is part of a chain, eg in the position node->author.
947
      // Return the name.
948
      $debug = $this->info['name'];
949
    }
950
    else {
951
      // This is a wrapper for an actual entity: return its type and id.
952
      $debug = $this->info['type'] . '(' . $this->getIdentifier() . ')';
953
    }
954

    
955
    if (isset($this->info['parent'])) {
956
      $debug = $this->info['parent']->debugIdentifierLocation() . '->' . $debug;
957
    }
958
    return $debug;
959
  }
960

    
961
  /**
962
   * Prepare for serializiation.
963
   */
964
  public function __sleep() {
965
    $vars = parent::__sleep();
966
    // Don't serialize the loaded entity and its property info.
967
    unset($vars['data'], $vars['propertyInfo'], $vars['propertyInfoAltered'], $vars['entityInfo']);
968
    // In case the entity is not saved yet, serialize the unsaved data.
969
    if ($this->dataAvailable() && $this->id === FALSE) {
970
      $vars['data'] = 'data';
971
    }
972
    return $vars;
973
  }
974

    
975
  public function __wakeup() {
976
    $this->setUp();
977
    if ($this->id !== FALSE) {
978
      // Make sure data is set, so the entity will be loaded when needed.
979
      $this->data = FALSE;
980
    }
981
  }
982
}
983

    
984
/**
985
 * Wraps a list of values.
986
 *
987
 * If the wrapped data is a list of data, its numerical indexes may be used to
988
 * retrieve wrappers for the list items. For that this wrapper implements
989
 * ArrayAccess so it may be used like a usual numerically indexed array.
990
 */
991
class EntityListWrapper extends EntityMetadataWrapper implements IteratorAggregate, ArrayAccess, Countable {
992

    
993
  /**
994
   * The type of contained items.
995
   */
996
  protected $itemType;
997

    
998
  /**
999
   * Whether this is a list of entities with a known entity type, i.e. for
1000
   * generic list of entities (list<entity>) this is FALSE.
1001
   */
1002
  protected $isEntityList;
1003

    
1004

    
1005
  public function __construct($type, $data = NULL, $info = array()) {
1006
    parent::__construct($type, NULL, $info);
1007

    
1008
    $this->itemType = entity_property_list_extract_type($this->type);
1009
    if (!$this->itemType) {
1010
      $this->itemType = 'unknown';
1011
    }
1012
    $this->isEntityList = (bool) entity_get_info($this->itemType);
1013

    
1014
    if (isset($data)) {
1015
      $this->set($data);
1016
    }
1017
  }
1018

    
1019
  /**
1020
   * Get the wrapper for a single item.
1021
   *
1022
   * @return
1023
   *   An instance of EntityMetadataWrapper.
1024
   */
1025
  public function get($delta) {
1026
    // Look it up in the cache if possible.
1027
    if (!array_key_exists($delta, $this->cache)) {
1028
      if (!isset($delta)) {
1029
        // The [] operator has been used so point at a new entry.
1030
        $values = parent::value();
1031
        $delta = $values ? max(array_keys($values)) + 1 : 0;
1032
      }
1033
      if (is_numeric($delta)) {
1034
        $info = array('parent' => $this, 'name' => $delta) + $this->info;
1035
        $this->cache[$delta] = entity_metadata_wrapper($this->itemType, NULL, $info);
1036
      }
1037
      else {
1038
        throw new EntityMetadataWrapperException('There can be only numerical keyed items in a list.');
1039
      }
1040
    }
1041
    return $this->cache[$delta];
1042
  }
1043

    
1044
  protected function getPropertyValue($delta) {
1045
    // Make use parent::value() to easily by-pass any entity-loading.
1046
    $data = parent::value();
1047
    if (isset($data[$delta])) {
1048
      return $data[$delta];
1049
    }
1050
  }
1051

    
1052
  protected function getPropertyRaw($delta) {
1053
    return $this->getPropertyValue($delta);
1054
  }
1055

    
1056
  protected function setProperty($delta, $value) {
1057
    $data = parent::value();
1058
    if (is_numeric($delta)) {
1059
      $data[$delta] = $value;
1060
      $this->set($data);
1061
    }
1062
  }
1063

    
1064
  protected function propertyAccess($delta, $op, $account = NULL) {
1065
    return $this->access($op, $account);
1066
  }
1067

    
1068
  /**
1069
   * Returns the list as numerically indexed array.
1070
   *
1071
   * Note that a list of entities might contain stale entity references. In
1072
   * that case the wrapper and the identifier of a stale reference would be
1073
   * still accessible, however the entity object value would be NULL. That way,
1074
   * there may be NULL values in lists of entity objects due to stale entity
1075
   * references.
1076
   *
1077
   * @param $options
1078
   *   An array of options. Known keys:
1079
   *   - identifier: If set to TRUE for a list of entities, it won't be returned
1080
   *     as list of fully loaded entity objects, but as a list of entity ids.
1081
   *     Note that this list may contain ids of stale entity references.
1082
   */
1083
  public function value(array $options = array()) {
1084
    // For lists of entities fetch full entity objects before returning.
1085
    // Generic entity-wrappers need to be handled separately though.
1086
    if ($this->isEntityList && empty($options['identifier']) && $this->dataAvailable()) {
1087
      $list = parent::value();
1088
      $entities = $list ? entity_load($this->get(0)->type, $list) : array();
1089
      // Make sure to keep the array keys as present in the list.
1090
      foreach ($list as $key => $id) {
1091
        // In case the entity cannot be loaded, we return NULL just as for empty
1092
        // properties.
1093
        $list[$key] = isset($entities[$id]) ? $entities[$id] : NULL;
1094
      }
1095
      return $list;
1096
    }
1097
    return parent::value();
1098
  }
1099

    
1100
  public function set($values) {
1101
    // Support setting lists of fully loaded entities.
1102
    if ($this->isEntityList && $values && is_object(reset($values))) {
1103
      foreach ($values as $key => $value) {
1104
        // Ignore outdated NULL value references in lists of entities.
1105
        if (isset($value)) {
1106
          list($id, $vid, $bundle) = entity_extract_ids($this->itemType, $value);
1107
          $values[$key] = $id;
1108
        }
1109
      }
1110
    }
1111
    return parent::set($values);
1112
  }
1113

    
1114
  /**
1115
   * If we wrap a list, we return an iterator over the data list.
1116
   */
1117
  public function getIterator() {
1118
    // In case there is no data available, just iterate over the first item.
1119
    return new EntityMetadataWrapperIterator($this, ($this->dataAvailable() && is_array(parent::value())) ? array_keys(parent::value()) : array(0));
1120
  }
1121

    
1122
  /**
1123
   * Implements the ArrayAccess interface.
1124
   */
1125
  public function offsetGet($delta) {
1126
    return $this->get($delta);
1127
  }
1128

    
1129
  public function offsetExists($delta) {
1130
    return $this->dataAvailable() && ($data = $this->value()) && array_key_exists($delta, $data);
1131
  }
1132

    
1133
  public function offsetSet($delta, $value) {
1134
    $this->get($delta)->set($value);
1135
  }
1136

    
1137
  public function offsetUnset($delta) {
1138
    if ($this->offsetExists($delta)) {
1139
      unset($this->data[$delta]);
1140
      $this->set($this->data);
1141
    }
1142
  }
1143

    
1144
  public function count() {
1145
    return $this->dataAvailable() ? count($this->value()) : 0;
1146
  }
1147

    
1148
  /**
1149
   * Overridden.
1150
   */
1151
  public function validate($value) {
1152
    // Required lists may not be empty or unset.
1153
    if (!empty($this->info['required']) && empty($value)) {
1154
      return FALSE;
1155
    }
1156
    return parent::validate($value);
1157
  }
1158

    
1159
  /**
1160
   * Returns the label for the list of set values if available.
1161
   */
1162
  public function label() {
1163
    if ($options = $this->optionsList('view')) {
1164
      $options = entity_property_options_flatten($options);
1165
      $labels = array_intersect_key($options, array_flip((array) parent::value()));
1166
    }
1167
    else {
1168
      // Get each label on its own, e.g. to support getting labels of a list
1169
      // of entities.
1170
      $labels = array();
1171
      foreach ($this as $key => $property) {
1172
        $label = $property->label();
1173
        if (!$label) {
1174
          return NULL;
1175
        }
1176
        $labels[] = $label;
1177
      }
1178
    }
1179
    return isset($labels) ? implode(', ', $labels) : NULL;
1180
  }
1181
}
1182

    
1183
/**
1184
 * Provide a separate Exception so it can be caught separately.
1185
 */
1186
class EntityMetadataWrapperException extends Exception { }
1187

    
1188

    
1189
/**
1190
 * Allows to easily iterate over existing child wrappers.
1191
 */
1192
class EntityMetadataWrapperIterator implements RecursiveIterator {
1193

    
1194
  protected $position = 0;
1195
  protected $wrapper, $keys;
1196

    
1197
  public function __construct(EntityMetadataWrapper $wrapper, array $keys) {
1198
    $this->wrapper = $wrapper;
1199
    $this->keys = $keys;
1200
  }
1201

    
1202
  function rewind() {
1203
    $this->position = 0;
1204
  }
1205

    
1206
  function current() {
1207
    return $this->wrapper->get($this->keys[$this->position]);
1208
  }
1209

    
1210
  function key() {
1211
    return $this->keys[$this->position];
1212
  }
1213

    
1214
  function next() {
1215
    $this->position++;
1216
  }
1217

    
1218
  function valid() {
1219
    return isset($this->keys[$this->position]);
1220
  }
1221

    
1222
  public function hasChildren() {
1223
    return $this->current() instanceof IteratorAggregate;
1224
  }
1225

    
1226
  public function getChildren() {
1227
    return $this->current()->getIterator();
1228
  }
1229
}
1230

    
1231
/**
1232
 * An array object implementation keeping the reference on the given array so
1233
 * changes to the object are reflected in the passed array.
1234
 */
1235
class EntityMetadataArrayObject implements ArrayAccess, Countable, IteratorAggregate {
1236

    
1237
  protected $data;
1238

    
1239
  public function __construct(&$array) {
1240
    $this->data =& $array;
1241
  }
1242

    
1243
  public function &getArray() {
1244
    return $this->data;
1245
  }
1246

    
1247
  /**
1248
   * Implements the ArrayAccess interface.
1249
   */
1250
  public function offsetGet($delta) {
1251
    return $this->data[$delta];
1252
  }
1253

    
1254
  public function offsetExists($delta) {
1255
    return array_key_exists($delta, $this->data);
1256
  }
1257

    
1258
  public function offsetSet($delta, $value) {
1259
    $this->data[$delta] = $value;
1260
  }
1261

    
1262
  public function offsetUnset($delta) {
1263
    unset($this->data[$delta]);
1264
  }
1265

    
1266
  public function count() {
1267
    return count($this->data);
1268
  }
1269

    
1270
  public function getIterator() {
1271
    return new ArrayIterator($this->data);
1272
  }
1273
}