Projet

Général

Profil

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

root / drupal7 / sites / all / modules / entity / includes / entity.wrapper.inc @ 7d7b5830

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('Invalid data value given. Be sure it matches the required data type and format.');
123
    }
124
    $this->clear();
125
    $this->data = $value;
126
    $this->updateParent($value);
127
    return $this;
128
  }
129

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

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

    
158
  public function __toString() {
159
    return isset($this->info) ? 'Property ' . $this->info['name'] : $this->type;
160
  }
161

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

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

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

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

    
234
  /**
235
   * Prepare for serializiation.
236
   */
237
  public function __sleep() {
238
    $vars = get_object_vars($this);
239
    unset($vars['cache']);
240
    return drupal_map_assoc(array_keys($vars));
241
  }
242
}
243

    
244
/**
245
 * Wraps a single value.
246
 */
247
class EntityValueWrapper extends EntityMetadataWrapper {
248

    
249
  /**
250
   * Overrides EntityMetadataWrapper#value().
251
   * Sanitizes or decode textual data if necessary.
252
   */
253
  public function value(array $options = array()) {
254
    $data = parent::value();
255
    if ($this->type == 'text' && isset($data)) {
256
      $info = $this->info + array('sanitized' => FALSE, 'sanitize' => 'check_plain');
257
      $options += array('sanitize' => FALSE, 'decode' => FALSE);
258
      if ($options['sanitize'] && !$info['sanitized']) {
259
        return call_user_func($info['sanitize'], $data);
260
      }
261
      elseif ($options['decode'] && $info['sanitized']) {
262
        return decode_entities(strip_tags($data));
263
      }
264
    }
265
    return $data;
266
  }
267
}
268

    
269
/**
270
 * Provides a general wrapper for any data structure. For this to work the
271
 * metadata has to be passed during construction.
272
 */
273
class EntityStructureWrapper extends EntityMetadataWrapper implements IteratorAggregate {
274

    
275
  protected $propertyInfo = array(), $propertyInfoAltered = FALSE;
276
  protected $langcode = LANGUAGE_NONE;
277

    
278
  protected $propertyInfoDefaults = array(
279
    'type' => 'text',
280
    'getter callback' => 'entity_property_verbatim_get',
281
    'clear' => array(),
282
  );
283

    
284
  /**
285
   * Construct a new EntityStructureWrapper object.
286
   *
287
   * @param $type
288
   *   The type of the passed data.
289
   * @param $data
290
   *   Optional. The data to wrap.
291
   * @param $info
292
   *   Used to for specifying metadata about the data and internally to pass
293
   *   info about properties down the tree. For specifying metadata known keys
294
   *   are:
295
   *   - property info: An array of info about the properties of the wrapped
296
   *     data structure. It has to contain an array of property info in the same
297
   *     structure as used by hook_entity_property_info().
298
   */
299
  public function __construct($type, $data = NULL, $info = array()) {
300
    parent::__construct($type, $data, $info);
301
    $this->info += array('property defaults' => array());
302
    $info += array('property info' => array());
303
    $this->propertyInfo['properties'] = $info['property info'];
304
  }
305

    
306
  /**
307
   * May be used to lazy-load additional info about the data, depending on the
308
   * concrete passed data.
309
   */
310
  protected function spotInfo() {
311
    // Apply the callback if set, such that the caller may alter the info.
312
    if (!empty($this->info['property info alter']) && !$this->propertyInfoAltered) {
313
      $this->propertyInfo = call_user_func($this->info['property info alter'], $this, $this->propertyInfo);
314
      $this->propertyInfoAltered = TRUE;
315
    }
316
  }
317

    
318
  /**
319
   * Gets the info about the given property.
320
   *
321
   * @param $name
322
   *   The name of the property. If not given, info about all properties will
323
   *   be returned.
324
   * @throws EntityMetadataWrapperException
325
   *   If there is no such property.
326
   * @return
327
   *   An array of info about the property.
328
   */
329
  public function getPropertyInfo($name = NULL) {
330
    $this->spotInfo();
331
    if (!isset($name)) {
332
      return $this->propertyInfo['properties'];
333
    }
334
    if (!isset($this->propertyInfo['properties'][$name])) {
335
      throw new EntityMetadataWrapperException('Unknown data property ' . check_plain($name) . '.');
336
    }
337
    return $this->propertyInfo['properties'][$name] + $this->info['property defaults'] + $this->propertyInfoDefaults;
338
  }
339

    
340
  /**
341
   * Returns a reference on the property info.
342
   *
343
   * If possible, use the property info alter callback for spotting metadata.
344
   * The reference may be used to alter the property info for any remaining
345
   * cases, e.g. if additional metadata has been asserted.
346
   */
347
  public function &refPropertyInfo() {
348
    return $this->propertyInfo;
349
  }
350

    
351
  /**
352
   * Sets a new language to use for retrieving properties.
353
   *
354
   * @param $langcode
355
   *   The language code of the language to set.
356
   * @return EntityWrapper
357
   */
358
  public function language($langcode = LANGUAGE_NONE) {
359
    if ($langcode != $this->langcode) {
360
      $this->langcode = $langcode;
361
      $this->cache = array();
362
    }
363
    return $this;
364
  }
365

    
366
  /**
367
   * Gets the language used for retrieving properties.
368
   *
369
   * @return String
370
   *   The language object of the language or NULL for the default language.
371
   *
372
   * @see EntityStructureWrapper::language()
373
   */
374
  public function getPropertyLanguage() {
375
    if ($this->langcode != LANGUAGE_NONE && $list = language_list()) {
376
      if (isset($list[$this->langcode])) {
377
        return $list[$this->langcode];
378
      }
379
    }
380
    return NULL;
381
  }
382

    
383
  /**
384
   * Get the wrapper for a property.
385
   *
386
   * @return
387
   *   An instance of EntityMetadataWrapper.
388
   */
389
  public function get($name) {
390
    // Look it up in the cache if possible.
391
    if (!array_key_exists($name, $this->cache)) {
392
      if ($info = $this->getPropertyInfo($name)) {
393
        $info += array('parent' => $this, 'name' => $name, 'langcode' => $this->langcode, 'property defaults' => array());
394
        $info['property defaults'] += $this->info['property defaults'];
395
        $this->cache[$name] = entity_metadata_wrapper($info['type'], NULL, $info);
396
      }
397
      else {
398
        throw new EntityMetadataWrapperException('There is no property ' . check_plain($name) . " for this entity.");
399
      }
400
    }
401
    return $this->cache[$name];
402
  }
403

    
404
  /**
405
   * Magic method: Get a wrapper for a property.
406
   */
407
  public function __get($name) {
408
    if (strpos($name, 'krumo') === 0) {
409
      // #914934 Ugly workaround to allow krumo to write its recursion property.
410
      // This is necessary to make dpm() work without throwing exceptions.
411
      return NULL;
412
    }
413
    $get = $this->get($name);
414
    return $get;
415
  }
416

    
417
  /**
418
   * Magic method: Set a property.
419
   */
420
  public function __set($name, $value) {
421
    if (strpos($name, 'krumo') === 0) {
422
      // #914934 Ugly workaround to allow krumo to write its recursion property.
423
      // This is necessary to make dpm() work without throwing exceptions.
424
      $this->$name = $value;
425
    }
426
    else {
427
      $this->get($name)->set($value);
428
    }
429
  }
430

    
431
  /**
432
   * Gets the value of a property.
433
   */
434
  protected function getPropertyValue($name, &$info) {
435
    $options = array('language' => $this->getPropertyLanguage(), 'absolute' => TRUE);
436
    $data = $this->value();
437
    if (!isset($data)) {
438
      throw new EntityMetadataWrapperException('Unable to get the data property ' . check_plain($name) . ' as the parent data structure is not set.');
439
    }
440
    return $info['getter callback']($data, $options, $name, $this->type, $info);
441
  }
442

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

    
458
  /**
459
   * Sets a property.
460
   */
461
  protected function setProperty($name, $value) {
462
    $info = $this->getPropertyInfo($name);
463
    if (!empty($info['setter callback'])) {
464
      $data = $this->value();
465

    
466
      // In case the data structure is not set, support simple auto-creation
467
      // for arrays. Else an exception is thrown.
468
      if (!isset($data)) {
469
        if (!empty($this->info['auto creation']) && !($this instanceof EntityDrupalWrapper)) {
470
          $data = $this->info['auto creation']($name, $this->info);
471
        }
472
        else {
473
          throw new EntityMetadataWrapperException('Unable to set the data property ' . check_plain($name) . ' as the parent data structure is not set.');
474
        }
475
      }
476

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

    
480
      // If the setter has not thrown any exceptions, proceed and apply the
481
      // update to the current and any parent wrappers as necessary.
482
      $data = $this->info['type'] == 'entity' ? $this : $data;
483
      $this->set($data);
484

    
485
      // Clear the cache of properties dependent on this value.
486
      foreach ($info['clear'] as $name) {
487
        if (isset($this->cache[$name])) {
488
          $this->cache[$name]->clear();
489
        }
490
      }
491
    }
492
    else {
493
      throw new EntityMetadataWrapperException('Entity property ' . check_plain($name) . " doesn't support writing.");
494
    }
495
  }
496

    
497
  protected function propertyAccess($name, $op, $account = NULL) {
498
    $info = $this->getPropertyInfo($name);
499

    
500
    // If a property should be edited and this is part of an entity, make sure
501
    // the user has update access for this entity.
502
    if ($op == 'edit') {
503
      $entity = $this;
504
      while (!($entity instanceof EntityDrupalWrapper) && isset($entity->info['parent'])) {
505
        $entity = $entity->info['parent'];
506
      }
507
      if ($entity instanceof EntityDrupalWrapper && $entity->entityAccess('update', $account) === FALSE) {
508
        return FALSE;
509
      }
510
    }
511
    if (!empty($info['access callback'])) {
512
      $data = $this->dataAvailable() ? $this->value() : NULL;
513
      return call_user_func($info['access callback'], $op, $name, $data, $account, $this->type);
514
    }
515
    elseif ($op == 'edit' && isset($info['setter permission'])) {
516
      return user_access($info['setter permission'], $account);
517
    }
518
    // If access is unknown, we return TRUE.
519
    return TRUE;
520
  }
521

    
522
  /**
523
   * Magic method: Can be used to check if a property is known.
524
   */
525
  public function __isset($name) {
526
    $this->spotInfo();
527
    return isset($this->propertyInfo['properties'][$name]);
528
  }
529

    
530
  public function getIterator() {
531
    $this->spotInfo();
532
    return new EntityMetadataWrapperIterator($this, array_keys($this->propertyInfo['properties']));
533
  }
534

    
535
  /**
536
   * Returns the identifier of the data structure. If there is none, NULL is
537
   * returned.
538
   */
539
  public function getIdentifier() {
540
    return isset($this->id) && $this->dataAvailable() ? $this->id->value() : NULL;
541
  }
542

    
543
  /**
544
   * Prepare for serializiation.
545
   */
546
  public function __sleep() {
547
    $vars = parent::__sleep();
548
    unset($vars['propertyInfoDefaults']);
549
    return $vars;
550
  }
551

    
552
  public function clear() {
553
    $this->propertyInfoAltered = FALSE;
554
    parent::clear();
555
  }
556
}
557

    
558
/**
559
 * Provides a wrapper for entities registrered in hook_entity_info().
560
 *
561
 * The wrapper eases applying getter and setter callbacks of entity properties
562
 * specified in hook_entity_property_info().
563
 */
564
class EntityDrupalWrapper extends EntityStructureWrapper {
565

    
566
  /**
567
   * Contains the entity id.
568
   */
569
  protected $id = FALSE;
570
  protected $bundle;
571
  protected $entityInfo;
572

    
573
  /**
574
   * Construct a new EntityDrupalWrapper object.
575
   *
576
   * @param $type
577
   *   The type of the passed data.
578
   * @param $data
579
   *   Optional. The entity to wrap or its identifier.
580
   * @param $info
581
   *   Optional. Used internally to pass info about properties down the tree.
582
   */
583
  public function __construct($type, $data = NULL, $info = array()) {
584
    parent::__construct($type, $data, $info);
585
    $this->setUp();
586
  }
587

    
588
  protected function setUp() {
589
    $this->propertyInfo = entity_get_property_info($this->type) + array('properties' => array());
590
    $info = $this->info + array('property info' => array(), 'bundle' => NULL);
591
    $this->propertyInfo['properties'] += $info['property info'];
592
    $this->bundle = $info['bundle'];
593
    $this->entityInfo = entity_get_info($this->type);
594
    if (isset($this->bundle)) {
595
      $this->spotBundleInfo(FALSE);
596
    }
597
  }
598

    
599
  /**
600
   * Sets the entity internally accepting both the entity id and object.
601
   */
602
  protected function setEntity($data) {
603
    // For entities we allow getter callbacks to return FALSE, which we
604
    // interpret like NULL values as unset properties.
605
    if (isset($data) && $data !== FALSE && !is_object($data)) {
606
      $this->id = $data;
607
      $this->data = FALSE;
608
    }
609
    elseif (is_object($data) && $data instanceof EntityDrupalWrapper) {
610
      // We got a wrapped entity passed, so take over its values.
611
      $this->id = $data->id;
612
      $this->data = $data->data;
613
      // For generic entity references, also update the entity type accordingly.
614
      if ($this->info['type'] == 'entity') {
615
        $this->type = $data->type;
616
      }
617
    }
618
    elseif (is_object($data)) {
619
      // We got the entity object passed.
620
      $this->data = $data;
621
      $id = entity_id($this->type, $data);
622
      $this->id = isset($id) ? $id : FALSE;
623
    }
624
    else {
625
      $this->id = FALSE;
626
      $this->data = NULL;
627
    }
628
  }
629

    
630
  /**
631
   * Used to lazy-load bundle info. So the wrapper can be loaded e.g. just
632
   * for setting without the data being loaded.
633
   */
634
  protected function spotInfo() {
635
    if (!$this->propertyInfoAltered) {
636
      if ($this->info['type'] == 'entity' && $this->dataAvailable() && $this->value()) {
637
        // Add in entity-type specific details.
638
        $this->setUp();
639
      }
640
      $this->spotBundleInfo(TRUE);
641
      parent::spotInfo();
642
      $this->propertyInfoAltered = TRUE;
643
    }
644
  }
645

    
646
  /**
647
   * Tries to determine the bundle and adds in the according property info.
648
   *
649
   * @param $load
650
   *   Whether the entity should be loaded to spot the info if necessary.
651
   */
652
  protected function spotBundleInfo($load = TRUE) {
653
    // Like entity_extract_ids() assume the entity type if no key is given.
654
    if (empty($this->entityInfo['entity keys']['bundle']) && $this->type != 'entity') {
655
      $this->bundle = $this->type;
656
    }
657
    // Detect the bundle if not set yet and add in properties from the bundle.
658
    elseif (!$this->bundle && $load && $this->dataAvailable()) {
659
      try {
660
        if ($entity = $this->value()) {
661
          list($id, $vid, $bundle) = entity_extract_ids($this->type, $entity);
662
          $this->bundle = $bundle;
663
        }
664
      }
665
      catch (EntityMetadataWrapperException $e) {
666
        // Loading data failed, so we cannot derive the used bundle.
667
      }
668
    }
669

    
670
    if ($this->bundle && isset($this->propertyInfo['bundles'][$this->bundle])) {
671
      $bundle_info = (array) $this->propertyInfo['bundles'][$this->bundle] + array('properties' => array());
672
      // Allow bundles to re-define existing properties, such that the bundle
673
      // can add in more bundle-specific details like the bundle of a referenced
674
      // entity.
675
      $this->propertyInfo['properties'] = $bundle_info['properties'] + $this->propertyInfo['properties'];
676
    }
677
  }
678

    
679
  /**
680
   * Returns the identifier of the wrapped entity.
681
   *
682
   * @see entity_id()
683
   */
684
  public function getIdentifier() {
685
    return $this->dataAvailable() ? $this->value(array('identifier' => TRUE)) : NULL;
686
  }
687

    
688
  /**
689
   * Returns the bundle of an entity, or FALSE if it has no bundles.
690
   */
691
  public function getBundle() {
692
    if ($this->dataAvailable()) {
693
      $this->spotInfo();
694
      return $this->bundle;
695
    }
696
  }
697

    
698
  /**
699
   * Overridden.
700
   *
701
   * @param $options
702
   *   An array of options. Known keys:
703
   *   - identifier: If set to TRUE, the entity identifier is returned.
704
   */
705
  public function value(array $options = array()) {
706
    // Try loading the data via the getter callback if there is none yet.
707
    if (!isset($this->data)) {
708
      $this->setEntity(parent::value());
709
    }
710
    if (!empty($options['identifier'])) {
711
      return $this->id;
712
    }
713
    elseif (!$this->data && !empty($this->id)) {
714
      // Lazy load the entity if necessary.
715
      $return = entity_load($this->type, array($this->id));
716
      // In case the entity cannot be loaded, we return NULL just as for empty
717
      // properties.
718
      $this->data = $return ? reset($return) : NULL;
719
    }
720
    return $this->data;
721
  }
722

    
723
  /**
724
   * Returns the entity prepared for rendering.
725
   *
726
   * @see entity_view()
727
   */
728
  public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
729
    return entity_view($this->type(), array($this->value()), $view_mode, $langcode, $page);
730
  }
731

    
732
  /**
733
   * Overridden to support setting the entity by either the object or the id.
734
   */
735
  public function set($value) {
736
    if (!$this->validate($value)) {
737
      throw new EntityMetadataWrapperException('Invalid data value given. Be sure it matches the required data type and format.');
738
    }
739
    if ($this->info['type'] == 'entity' && $value === $this) {
740
      // Nothing to do.
741
      return $this;
742
    }
743
    $previous_id = $this->id;
744
    $previous_type = $this->type;
745
    // Set value, so we get the identifier and pass it to the normal setter.
746
    $this->clear();
747
    $this->setEntity($value);
748
    // Generally, we have to update the parent only if the entity reference
749
    // has changed. In case of a generic entity reference, we pass the entity
750
    // wrapped. Else we just pass the id of the entity to the setter callback.
751
    if ($this->info['type'] == 'entity' && ($previous_id != $this->id || $previous_type != $this->type)) {
752
      // We need to clone the wrapper we pass through as value, so it does not
753
      // get cleared when the current wrapper instance gets cleared.
754
      $this->updateParent(clone $this);
755
    }
756
    // In case the entity has been unset, we cannot properly detect changes as
757
    // the previous id defaults to FALSE for unloaded entities too. So in that
758
    // case we just always update the parent.
759
    elseif ($this->id === FALSE && !$this->data) {
760
      $this->updateParent(NULL);
761
    }
762
    elseif ($previous_id !== $this->id) {
763
      $this->updateParent($this->id);
764
    }
765
    return $this;
766
  }
767

    
768
  /**
769
   * Overridden.
770
   */
771
  public function clear() {
772
    $this->id = NULL;
773
    $this->bundle = isset($this->info['bundle']) ? $this->info['bundle'] : NULL;
774
    if ($this->type != $this->info['type']) {
775
      // Reset entity info / property info based upon the info provided during
776
      // the creation of the wrapper.
777
      $this->type = $this->info['type'];
778
      $this->setUp();
779
    }
780
    parent::clear();
781
  }
782

    
783
  /**
784
   * Overridden.
785
   */
786
  public function type() {
787
    // In case of a generic entity wrapper, load the data first to determine
788
    // the type of the concrete entity.
789
    if ($this->dataAvailable() && $this->info['type'] == 'entity') {
790
      try {
791
        $this->value(array('identifier' => TRUE));
792
      }
793
      catch (EntityMetadataWrapperException $e) {
794
        // If loading data fails, we cannot determine the concrete entity type.
795
      }
796
    }
797
    return $this->type;
798
  }
799

    
800
  /**
801
   * {@inheritdoc}
802
   *
803
   * Note that this method checks property access, but can be used for checking
804
   * entity access *only* if the wrapper is not a property (i.e. has no parent
805
   * wrapper).
806
   * To be safe, better use EntityDrupalWrapper::entityAccess() for checking
807
   * entity access.
808
   */
809
  public function access($op, $account = NULL) {
810
    if (!empty($this->info['parent'])) {
811
      // If this is a property, make sure the user is able to view the
812
      // currently referenced entity also.
813
      if ($this->entityAccess('view', $account) === FALSE) {
814
        return FALSE;
815
      }
816
      if (parent::access($op, $account) === FALSE) {
817
        return FALSE;
818
      }
819
      // If access is unknown, we return TRUE.
820
      return TRUE;
821
    }
822
    else {
823
      // This is not a property, so fallback on entity access.
824
      return $this->entityAccess($op == 'edit' ? 'update' : 'view', $account);
825
    }
826
  }
827

    
828
  /**
829
   * Checks whether the operation $op is allowed on the entity.
830
   *
831
   * @see entity_access()
832
   */
833
  public function entityAccess($op, $account = NULL) {
834
    $entity = $this->dataAvailable() ? $this->value() : NULL;
835
    // The value() method could return FALSE on entities such as user 0, so we
836
    // need to use NULL instead to conform to the expectations of
837
    // entity_access().
838
    if ($entity === FALSE) {
839
      $entity = NULL;
840
    }
841
    return entity_access($op, $this->type, $entity, $account);
842
  }
843

    
844
  /**
845
   * Permanently save the wrapped entity.
846
   *
847
   * @throws EntityMetadataWrapperException
848
   *   If the entity type does not support saving.
849
   *
850
   * @return EntityDrupalWrapper
851
   */
852
  public function save() {
853
    if ($this->data) {
854
      if (!entity_type_supports($this->type, 'save')) {
855
        throw new EntityMetadataWrapperException("There is no information about how to save entities of type " . check_plain($this->type) . '.');
856
      }
857
      entity_save($this->type, $this->data);
858
      // On insert, update the identifier afterwards.
859
      if (!$this->id) {
860
        list($this->id, , ) = entity_extract_ids($this->type, $this->data);
861
      }
862
    }
863
    // If the entity hasn't been loaded yet, don't bother saving it.
864
    return $this;
865
  }
866

    
867
  /**
868
   * Permanently delete the wrapped entity.
869
   *
870
   * @return EntityDrupalWrapper
871
   */
872
  public function delete() {
873
    if ($this->dataAvailable() && $this->value()) {
874
      $return = entity_delete($this->type, $this->id);
875
      if ($return === FALSE) {
876
        throw new EntityMetadataWrapperException("There is no information about how to delete entities of type " . check_plain($this->type) . '.');
877
      }
878
    }
879
    return $this;
880
  }
881

    
882
  /**
883
   * Gets the info about the wrapped entity.
884
   */
885
  public function entityInfo() {
886
    return $this->entityInfo;
887
  }
888

    
889
  /**
890
   * Returns the name of the key used by the entity for given entity key.
891
   *
892
   * @param $name
893
   *   One of 'id', 'name', 'bundle' or 'revision'.
894
   * @return
895
   *   The name of the key used by the entity.
896
   */
897
  public function entityKey($name) {
898
    return isset($this->entityInfo['entity keys'][$name]) ? $this->entityInfo['entity keys'][$name] : FALSE;
899
  }
900

    
901
  /**
902
   * Returns the entity label.
903
   *
904
   * @see entity_label()
905
   */
906
  public function label() {
907
    if ($entity = $this->value()) {
908
      return entity_label($this->type, $entity);
909
    }
910
  }
911

    
912
  /**
913
   * Prepare for serializiation.
914
   */
915
  public function __sleep() {
916
    $vars = parent::__sleep();
917
    // Don't serialize the loaded entity and its property info.
918
    unset($vars['data'], $vars['propertyInfo'], $vars['propertyInfoAltered'], $vars['entityInfo']);
919
    // In case the entity is not saved yet, serialize the unsaved data.
920
    if ($this->dataAvailable() && $this->id === FALSE) {
921
      $vars['data'] = 'data';
922
    }
923
    return $vars;
924
  }
925

    
926
  public function __wakeup() {
927
    $this->setUp();
928
    if ($this->id !== FALSE) {
929
      // Make sure data is set, so the entity will be loaded when needed.
930
      $this->data = FALSE;
931
    }
932
  }
933
}
934

    
935
/**
936
 * Wraps a list of values.
937
 *
938
 * If the wrapped data is a list of data, its numerical indexes may be used to
939
 * retrieve wrappers for the list items. For that this wrapper implements
940
 * ArrayAccess so it may be used like a usual numerically indexed array.
941
 */
942
class EntityListWrapper extends EntityMetadataWrapper implements IteratorAggregate, ArrayAccess, Countable {
943

    
944
  /**
945
   * The type of contained items.
946
   */
947
  protected $itemType;
948

    
949
  /**
950
   * Whether this is a list of entities with a known entity type, i.e. for
951
   * generic list of entities (list<entity>) this is FALSE.
952
   */
953
  protected $isEntityList;
954

    
955

    
956
  public function __construct($type, $data = NULL, $info = array()) {
957
    parent::__construct($type, NULL, $info);
958

    
959
    $this->itemType = entity_property_list_extract_type($this->type);
960
    if (!$this->itemType) {
961
      $this->itemType = 'unknown';
962
    }
963
    $this->isEntityList = (bool) entity_get_info($this->itemType);
964

    
965
    if (isset($data)) {
966
      $this->set($data);
967
    }
968
  }
969

    
970
  /**
971
   * Get the wrapper for a single item.
972
   *
973
   * @return
974
   *   An instance of EntityMetadataWrapper.
975
   */
976
  public function get($delta) {
977
    // Look it up in the cache if possible.
978
    if (!array_key_exists($delta, $this->cache)) {
979
      if (!isset($delta)) {
980
        // The [] operator has been used so point at a new entry.
981
        $values = parent::value();
982
        $delta = $values ? max(array_keys($values)) + 1 : 0;
983
      }
984
      if (is_numeric($delta)) {
985
        $info = array('parent' => $this, 'name' => $delta) + $this->info;
986
        $this->cache[$delta] = entity_metadata_wrapper($this->itemType, NULL, $info);
987
      }
988
      else {
989
        throw new EntityMetadataWrapperException('There can be only numerical keyed items in a list.');
990
      }
991
    }
992
    return $this->cache[$delta];
993
  }
994

    
995
  protected function getPropertyValue($delta) {
996
    // Make use parent::value() to easily by-pass any entity-loading.
997
    $data = parent::value();
998
    if (isset($data[$delta])) {
999
      return $data[$delta];
1000
    }
1001
  }
1002

    
1003
  protected function getPropertyRaw($delta) {
1004
    return $this->getPropertyValue($delta);
1005
  }
1006

    
1007
  protected function setProperty($delta, $value) {
1008
    $data = parent::value();
1009
    if (is_numeric($delta)) {
1010
      $data[$delta] = $value;
1011
      $this->set($data);
1012
    }
1013
  }
1014

    
1015
  protected function propertyAccess($delta, $op, $account = NULL) {
1016
    return $this->access($op, $account);
1017
  }
1018

    
1019
  /**
1020
   * Returns the list as numerically indexed array.
1021
   *
1022
   * Note that a list of entities might contain stale entity references. In
1023
   * that case the wrapper and the identifier of a stale reference would be
1024
   * still accessible, however the entity object value would be NULL. That way,
1025
   * there may be NULL values in lists of entity objects due to stale entity
1026
   * references.
1027
   *
1028
   * @param $options
1029
   *   An array of options. Known keys:
1030
   *   - identifier: If set to TRUE for a list of entities, it won't be returned
1031
   *     as list of fully loaded entity objects, but as a list of entity ids.
1032
   *     Note that this list may contain ids of stale entity references.
1033
   */
1034
  public function value(array $options = array()) {
1035
    // For lists of entities fetch full entity objects before returning.
1036
    // Generic entity-wrappers need to be handled separately though.
1037
    if ($this->isEntityList && empty($options['identifier']) && $this->dataAvailable()) {
1038
      $list = parent::value();
1039
      $entities = $list ? entity_load($this->get(0)->type, $list) : array();
1040
      // Make sure to keep the array keys as present in the list.
1041
      foreach ($list as $key => $id) {
1042
        // In case the entity cannot be loaded, we return NULL just as for empty
1043
        // properties.
1044
        $list[$key] = isset($entities[$id]) ? $entities[$id] : NULL;
1045
      }
1046
      return $list;
1047
    }
1048
    return parent::value();
1049
  }
1050

    
1051
  public function set($values) {
1052
    // Support setting lists of fully loaded entities.
1053
    if ($this->isEntityList && $values && is_object(reset($values))) {
1054
      foreach ($values as $key => $value) {
1055
        // Ignore outdated NULL value references in lists of entities.
1056
        if (isset($value)) {
1057
          list($id, $vid, $bundle) = entity_extract_ids($this->itemType, $value);
1058
          $values[$key] = $id;
1059
        }
1060
      }
1061
    }
1062
    return parent::set($values);
1063
  }
1064

    
1065
  /**
1066
   * If we wrap a list, we return an iterator over the data list.
1067
   */
1068
  public function getIterator() {
1069
    // In case there is no data available, just iterate over the first item.
1070
    return new EntityMetadataWrapperIterator($this, $this->dataAvailable() ? array_keys(parent::value()) : array(0));
1071
  }
1072

    
1073
  /**
1074
   * Implements the ArrayAccess interface.
1075
   */
1076
  public function offsetGet($delta) {
1077
    return $this->get($delta);
1078
  }
1079

    
1080
  public function offsetExists($delta) {
1081
    return $this->dataAvailable() && ($data = $this->value()) && array_key_exists($delta, $data);
1082
  }
1083

    
1084
  public function offsetSet($delta, $value) {
1085
    $this->get($delta)->set($value);
1086
  }
1087

    
1088
  public function offsetUnset($delta) {
1089
    if ($this->offsetExists($delta)) {
1090
      unset($this->data[$delta]);
1091
      $this->set($this->data);
1092
    }
1093
  }
1094

    
1095
  public function count() {
1096
    return $this->dataAvailable() ? count($this->value()) : 0;
1097
  }
1098

    
1099
  /**
1100
   * Overridden.
1101
   */
1102
  public function validate($value) {
1103
    // Required lists may not be empty or unset.
1104
    if (!empty($this->info['required']) && empty($value)) {
1105
      return FALSE;
1106
    }
1107
    return parent::validate($value);
1108
  }
1109

    
1110
  /**
1111
   * Returns the label for the list of set values if available.
1112
   */
1113
  public function label() {
1114
    if ($options = $this->optionsList('view')) {
1115
      $options = entity_property_options_flatten($options);
1116
      $labels = array_intersect_key($options, array_flip((array) parent::value()));
1117
    }
1118
    else {
1119
      // Get each label on its own, e.g. to support getting labels of a list
1120
      // of entities.
1121
      $labels = array();
1122
      foreach ($this as $key => $property) {
1123
        $label = $property->label();
1124
        if (!$label) {
1125
          return NULL;
1126
        }
1127
        $labels[] = $label;
1128
      }
1129
    }
1130
    return isset($labels) ? implode(', ', $labels) : NULL;
1131
  }
1132
}
1133

    
1134
/**
1135
 * Provide a separate Exception so it can be caught separately.
1136
 */
1137
class EntityMetadataWrapperException extends Exception { }
1138

    
1139

    
1140
/**
1141
 * Allows to easily iterate over existing child wrappers.
1142
 */
1143
class EntityMetadataWrapperIterator implements RecursiveIterator {
1144

    
1145
  protected $position = 0;
1146
  protected $wrapper, $keys;
1147

    
1148
  public function __construct(EntityMetadataWrapper $wrapper, array $keys) {
1149
    $this->wrapper = $wrapper;
1150
    $this->keys = $keys;
1151
  }
1152

    
1153
  function rewind() {
1154
    $this->position = 0;
1155
  }
1156

    
1157
  function current() {
1158
    return $this->wrapper->get($this->keys[$this->position]);
1159
  }
1160

    
1161
  function key() {
1162
    return $this->keys[$this->position];
1163
  }
1164

    
1165
  function next() {
1166
    $this->position++;
1167
  }
1168

    
1169
  function valid() {
1170
    return isset($this->keys[$this->position]);
1171
  }
1172

    
1173
  public function hasChildren() {
1174
    return $this->current() instanceof IteratorAggregate;
1175
  }
1176

    
1177
  public function getChildren() {
1178
    return $this->current()->getIterator();
1179
  }
1180
}
1181

    
1182
/**
1183
 * An array object implementation keeping the reference on the given array so
1184
 * changes to the object are reflected in the passed array.
1185
 */
1186
class EntityMetadataArrayObject implements ArrayAccess, Countable, IteratorAggregate {
1187

    
1188
  protected $data;
1189

    
1190
  public function __construct(&$array) {
1191
    $this->data =& $array;
1192
  }
1193

    
1194
  public function &getArray() {
1195
    return $this->data;
1196
  }
1197

    
1198
  /**
1199
   * Implements the ArrayAccess interface.
1200
   */
1201
  public function offsetGet($delta) {
1202
    return $this->data[$delta];
1203
  }
1204

    
1205
  public function offsetExists($delta) {
1206
    return array_key_exists($delta, $this->data);
1207
  }
1208

    
1209
  public function offsetSet($delta, $value) {
1210
    $this->data[$delta] = $value;
1211
  }
1212

    
1213
  public function offsetUnset($delta) {
1214
    unset($this->data[$delta]);
1215
  }
1216

    
1217
  public function count() {
1218
    return count($this->data);
1219
  }
1220

    
1221
  public function getIterator() {
1222
    return new ArrayIterator($this->data);
1223
  }
1224
}