Projet

Général

Profil

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

root / drupal7 / sites / all / modules / entity / includes / entity.wrapper.inc @ 503b3f7b

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)) {
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
    return TRUE;
519
  }
520

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
859
  /**
860
   * Permanently delete the wrapped entity.
861
   *
862
   * @return EntityDrupalWrapper
863
   */
864
  public function delete() {
865
    if ($this->dataAvailable() && $this->value()) {
866
      $return = entity_delete($this->type, $this->id);
867
      if ($return === FALSE) {
868
        throw new EntityMetadataWrapperException("There is no information about how to delete entities of type " . check_plain($this->type) . '.');
869
      }
870
    }
871
    return $this;
872
  }
873

    
874
  /**
875
   * Gets the info about the wrapped entity.
876
   */
877
  public function entityInfo() {
878
    return $this->entityInfo;
879
  }
880

    
881
  /**
882
   * Returns the name of the key used by the entity for given entity key.
883
   *
884
   * @param $name
885
   *   One of 'id', 'name', 'bundle' or 'revision'.
886
   * @return
887
   *   The name of the key used by the entity.
888
   */
889
  public function entityKey($name) {
890
    return isset($this->entityInfo['entity keys'][$name]) ? $this->entityInfo['entity keys'][$name] : FALSE;
891
  }
892

    
893
  /**
894
   * Returns the entity label.
895
   *
896
   * @see entity_label()
897
   */
898
  public function label() {
899
    if ($entity = $this->value()) {
900
      return entity_label($this->type, $entity);
901
    }
902
  }
903

    
904
  /**
905
   * Prepare for serializiation.
906
   */
907
  public function __sleep() {
908
    $vars = parent::__sleep();
909
    // Don't serialize the loaded entity and its property info.
910
    unset($vars['data'], $vars['propertyInfo'], $vars['propertyInfoAltered'], $vars['entityInfo']);
911
    // In case the entity is not saved yet, serialize the unsaved data.
912
    if ($this->dataAvailable() && $this->id === FALSE) {
913
      $vars['data'] = 'data';
914
    }
915
    return $vars;
916
  }
917

    
918
  public function __wakeup() {
919
    $this->setUp();
920
    if ($this->id !== FALSE) {
921
      // Make sure data is set, so the entity will be loaded when needed.
922
      $this->data = FALSE;
923
    }
924
  }
925
}
926

    
927
/**
928
 * Wraps a list of values.
929
 *
930
 * If the wrapped data is a list of data, its numerical indexes may be used to
931
 * retrieve wrappers for the list items. For that this wrapper implements
932
 * ArrayAccess so it may be used like a usual numerically indexed array.
933
 */
934
class EntityListWrapper extends EntityMetadataWrapper implements IteratorAggregate, ArrayAccess, Countable {
935

    
936
  /**
937
   * The type of contained items.
938
   */
939
  protected $itemType;
940

    
941
  /**
942
   * Whether this is a list of entities with a known entity type, i.e. for
943
   * generic list of entities (list<entity>) this is FALSE.
944
   */
945
  protected $isEntityList;
946

    
947

    
948
  public function __construct($type, $data = NULL, $info = array()) {
949
    parent::__construct($type, NULL, $info);
950

    
951
    $this->itemType = entity_property_list_extract_type($this->type);
952
    if (!$this->itemType) {
953
      $this->itemType = 'unknown';
954
    }
955
    $this->isEntityList = (bool) entity_get_info($this->itemType);
956

    
957
    if (isset($data)) {
958
      $this->set($data);
959
    }
960
  }
961

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

    
987
  protected function getPropertyValue($delta) {
988
    // Make use parent::value() to easily by-pass any entity-loading.
989
    $data = parent::value();
990
    if (isset($data[$delta])) {
991
      return $data[$delta];
992
    }
993
  }
994

    
995
  protected function getPropertyRaw($delta) {
996
    return $this->getPropertyValue($delta);
997
  }
998

    
999
  protected function setProperty($delta, $value) {
1000
    $data = parent::value();
1001
    if (is_numeric($delta)) {
1002
      $data[$delta] = $value;
1003
      $this->set($data);
1004
    }
1005
  }
1006

    
1007
  protected function propertyAccess($delta, $op, $account = NULL) {
1008
    return $this->access($op, $account);
1009
  }
1010

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

    
1043
  public function set($values) {
1044
    // Support setting lists of fully loaded entities.
1045
    if ($this->isEntityList && $values && is_object(reset($values))) {
1046
      foreach ($values as $key => $value) {
1047
        // Ignore outdated NULL value references in lists of entities.
1048
        if (isset($value)) {
1049
          list($id, $vid, $bundle) = entity_extract_ids($this->itemType, $value);
1050
          $values[$key] = $id;
1051
        }
1052
      }
1053
    }
1054
    return parent::set($values);
1055
  }
1056

    
1057
  /**
1058
   * If we wrap a list, we return an iterator over the data list.
1059
   */
1060
  public function getIterator() {
1061
    // In case there is no data available, just iterate over the first item.
1062
    return new EntityMetadataWrapperIterator($this, $this->dataAvailable() ? array_keys(parent::value()) : array(0));
1063
  }
1064

    
1065
  /**
1066
   * Implements the ArrayAccess interface.
1067
   */
1068
  public function offsetGet($delta) {
1069
    return $this->get($delta);
1070
  }
1071

    
1072
  public function offsetExists($delta) {
1073
    return $this->dataAvailable() && ($data = $this->value()) && array_key_exists($delta, $data);
1074
  }
1075

    
1076
  public function offsetSet($delta, $value) {
1077
    $this->get($delta)->set($value);
1078
  }
1079

    
1080
  public function offsetUnset($delta) {
1081
    if ($this->offsetExists($delta)) {
1082
      unset($this->data[$delta]);
1083
      $this->set($this->data);
1084
    }
1085
  }
1086

    
1087
  public function count() {
1088
    return $this->dataAvailable() ? count($this->value()) : 0;
1089
  }
1090

    
1091
  /**
1092
   * Overridden.
1093
   */
1094
  public function validate($value) {
1095
    // Required lists may not be empty or unset.
1096
    if (!empty($this->info['required']) && empty($value)) {
1097
      return FALSE;
1098
    }
1099
    return parent::validate($value);
1100
  }
1101

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

    
1126
/**
1127
 * Provide a separate Exception so it can be caught separately.
1128
 */
1129
class EntityMetadataWrapperException extends Exception { }
1130

    
1131

    
1132
/**
1133
 * Allows to easily iterate over existing child wrappers.
1134
 */
1135
class EntityMetadataWrapperIterator implements RecursiveIterator {
1136

    
1137
  protected $position = 0;
1138
  protected $wrapper, $keys;
1139

    
1140
  public function __construct(EntityMetadataWrapper $wrapper, array $keys) {
1141
    $this->wrapper = $wrapper;
1142
    $this->keys = $keys;
1143
  }
1144

    
1145
  function rewind() {
1146
    $this->position = 0;
1147
  }
1148

    
1149
  function current() {
1150
    return $this->wrapper->get($this->keys[$this->position]);
1151
  }
1152

    
1153
  function key() {
1154
    return $this->keys[$this->position];
1155
  }
1156

    
1157
  function next() {
1158
    $this->position++;
1159
  }
1160

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

    
1165
  public function hasChildren() {
1166
    return $this->current() instanceof IteratorAggregate;
1167
  }
1168

    
1169
  public function getChildren() {
1170
    return $this->current()->getIterator();
1171
  }
1172
}
1173

    
1174
/**
1175
 * An array object implementation keeping the reference on the given array so
1176
 * changes to the object are reflected in the passed array.
1177
 */
1178
class EntityMetadataArrayObject implements ArrayAccess, Countable, IteratorAggregate {
1179

    
1180
  protected $data;
1181

    
1182
  public function __construct(&$array) {
1183
    $this->data =& $array;
1184
  }
1185

    
1186
  public function &getArray() {
1187
    return $this->data;
1188
  }
1189

    
1190
  /**
1191
   * Implements the ArrayAccess interface.
1192
   */
1193
  public function offsetGet($delta) {
1194
    return $this->data[$delta];
1195
  }
1196

    
1197
  public function offsetExists($delta) {
1198
    return array_key_exists($delta, $this->data);
1199
  }
1200

    
1201
  public function offsetSet($delta, $value) {
1202
    $this->data[$delta] = $value;
1203
  }
1204

    
1205
  public function offsetUnset($delta) {
1206
    unset($this->data[$delta]);
1207
  }
1208

    
1209
  public function count() {
1210
    return count($this->data);
1211
  }
1212

    
1213
  public function getIterator() {
1214
    return new ArrayIterator($this->data);
1215
  }
1216
}