Projet

Général

Profil

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

root / htmltest / sites / all / modules / entity / includes / entity.wrapper.inc @ dd54aff9

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
    return entity_access($op, $this->type, $entity, $account);
828
  }
829

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

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

    
868
  /**
869
   * Gets the info about the wrapped entity.
870
   */
871
  public function entityInfo() {
872
    return $this->entityInfo;
873
  }
874

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

    
887
  /**
888
   * Returns the entity label.
889
   *
890
   * @see entity_label()
891
   */
892
  public function label() {
893
    if ($entity = $this->value()) {
894
      return entity_label($this->type, $entity);
895
    }
896
  }
897

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

    
912
  public function __wakeup() {
913
    $this->setUp();
914
    if ($this->id !== FALSE) {
915
      // Make sure data is set, so the entity will be loaded when needed.
916
      $this->data = FALSE;
917
    }
918
  }
919
}
920

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

    
930
  /**
931
   * The type of contained items.
932
   */
933
  protected $itemType;
934

    
935
  /**
936
   * Whether this is a list of entities with a known entity type, i.e. for
937
   * generic list of entities (list<entity>) this is FALSE.
938
   */
939
  protected $isEntityList;
940

    
941

    
942
  public function __construct($type, $data = NULL, $info = array()) {
943
    parent::__construct($type, NULL, $info);
944

    
945
    $this->itemType = entity_property_list_extract_type($this->type);
946
    if (!$this->itemType) {
947
      $this->itemType = 'unknown';
948
    }
949
    $this->isEntityList = (bool) entity_get_info($this->itemType);
950

    
951
    if (isset($data)) {
952
      $this->set($data);
953
    }
954
  }
955

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

    
981
  protected function getPropertyValue($delta) {
982
    // Make use parent::value() to easily by-pass any entity-loading.
983
    $data = parent::value();
984
    if (isset($data[$delta])) {
985
      return $data[$delta];
986
    }
987
  }
988

    
989
  protected function getPropertyRaw($delta) {
990
    return $this->getPropertyValue($delta);
991
  }
992

    
993
  protected function setProperty($delta, $value) {
994
    $data = parent::value();
995
    if (is_numeric($delta)) {
996
      $data[$delta] = $value;
997
      $this->set($data);
998
    }
999
  }
1000

    
1001
  protected function propertyAccess($delta, $op, $account = NULL) {
1002
    return $this->access($op, $account);
1003
  }
1004

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

    
1037
  public function set($values) {
1038
    // Support setting lists of fully loaded entities.
1039
    if ($this->isEntityList && $values && is_object(reset($values))) {
1040
      foreach ($values as $key => $value) {
1041
        list($id, $vid, $bundle) = entity_extract_ids($this->itemType, $value);
1042
        $values[$key] = $id;
1043
      }
1044
    }
1045
    return parent::set($values);
1046
  }
1047

    
1048
  /**
1049
   * If we wrap a list, we return an iterator over the data list.
1050
   */
1051
  public function getIterator() {
1052
    // In case there is no data available, just iterate over the first item.
1053
    return new EntityMetadataWrapperIterator($this, $this->dataAvailable() ? array_keys(parent::value()) : array(0));
1054
  }
1055

    
1056
  /**
1057
   * Implements the ArrayAccess interface.
1058
   */
1059
  public function offsetGet($delta) {
1060
    return $this->get($delta);
1061
  }
1062

    
1063
  public function offsetExists($delta) {
1064
    return $this->dataAvailable() && ($data = $this->value()) && array_key_exists($delta, $data);
1065
  }
1066

    
1067
  public function offsetSet($delta, $value) {
1068
    $this->get($delta)->set($value);
1069
  }
1070

    
1071
  public function offsetUnset($delta) {
1072
    if ($this->offsetExists($delta)) {
1073
      unset($this->data[$delta]);
1074
      $this->set($this->data);
1075
    }
1076
  }
1077

    
1078
  public function count() {
1079
    return $this->dataAvailable() ? count($this->value()) : 0;
1080
  }
1081

    
1082
  /**
1083
   * Overridden.
1084
   */
1085
  public function validate($value) {
1086
    // Required lists may not be empty or unset.
1087
    if (!empty($this->info['required']) && empty($value)) {
1088
      return FALSE;
1089
    }
1090
    return parent::validate($value);
1091
  }
1092

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

    
1117
/**
1118
 * Provide a separate Exception so it can be caught separately.
1119
 */
1120
class EntityMetadataWrapperException extends Exception { }
1121

    
1122

    
1123
/**
1124
 * Allows to easily iterate over existing child wrappers.
1125
 */
1126
class EntityMetadataWrapperIterator implements RecursiveIterator {
1127

    
1128
  protected $position = 0;
1129
  protected $wrapper, $keys;
1130

    
1131
  public function __construct(EntityMetadataWrapper $wrapper, array $keys) {
1132
    $this->wrapper = $wrapper;
1133
    $this->keys = $keys;
1134
  }
1135

    
1136
  function rewind() {
1137
    $this->position = 0;
1138
  }
1139

    
1140
  function current() {
1141
    return $this->wrapper->get($this->keys[$this->position]);
1142
  }
1143

    
1144
  function key() {
1145
    return $this->keys[$this->position];
1146
  }
1147

    
1148
  function next() {
1149
    $this->position++;
1150
  }
1151

    
1152
  function valid() {
1153
    return isset($this->keys[$this->position]);
1154
  }
1155

    
1156
  public function hasChildren() {
1157
    return $this->current() instanceof IteratorAggregate;
1158
  }
1159

    
1160
  public function getChildren() {
1161
    return $this->current()->getIterator();
1162
  }
1163
}
1164

    
1165
/**
1166
 * An array object implementation keeping the reference on the given array so
1167
 * changes to the object are reflected in the passed array.
1168
 */
1169
class EntityMetadataArrayObject implements ArrayAccess, Countable, IteratorAggregate {
1170

    
1171
  protected $data;
1172

    
1173
  public function __construct(&$array) {
1174
    $this->data =& $array;
1175
  }
1176

    
1177
  public function &getArray() {
1178
    return $this->data;
1179
  }
1180

    
1181
  /**
1182
   * Implements the ArrayAccess interface.
1183
   */
1184
  public function offsetGet($delta) {
1185
    return $this->data[$delta];
1186
  }
1187

    
1188
  public function offsetExists($delta) {
1189
    return array_key_exists($delta, $this->data);
1190
  }
1191

    
1192
  public function offsetSet($delta, $value) {
1193
    $this->data[$delta] = $value;
1194
  }
1195

    
1196
  public function offsetUnset($delta) {
1197
    unset($this->data[$delta]);
1198
  }
1199

    
1200
  public function count() {
1201
    return count($this->data);
1202
  }
1203

    
1204
  public function getIterator() {
1205
    return new ArrayIterator($this->data);
1206
  }
1207
}