Projet

Général

Profil

Paste
Télécharger (21,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / field_collection / field_collection.entity.inc @ 950416da

1
<?php
2

    
3
/**
4
 * Class for field_collection_item entities.
5
 */
6
class FieldCollectionItemEntity extends Entity {
7

    
8
  /**
9
   * Field collection field info.
10
   *
11
   * @var array
12
   */
13
  protected $fieldInfo;
14

    
15
  /**
16
   * The host entity object.
17
   *
18
   * @var object
19
   */
20
  protected $hostEntity;
21

    
22
  /**
23
   * The host entity ID.
24
   *
25
   * @var integer
26
   */
27
  protected $hostEntityId;
28

    
29
  /**
30
   * The host entity revision ID if this is not the default revision.
31
   *
32
   * @var integer
33
   */
34
  protected $hostEntityRevisionId;
35

    
36
  /**
37
   * The host entity type.
38
   *
39
   * @var string
40
   */
41
  protected $hostEntityType;
42

    
43
  /**
44
   * The language under which the field collection item is stored.
45
   *
46
   * @var string
47
   */
48
  protected $langcode = LANGUAGE_NONE;
49

    
50
  /**
51
   * Entity ID.
52
   *
53
   * @var integer
54
   */
55
  public $item_id;
56

    
57
  /**
58
   * Field collection revision ID.
59
   *
60
   * @var integer
61
   */
62
  public $revision_id;
63

    
64
  /**
65
   * The name of the field-collection field this item is associated with.
66
   *
67
   * @var string
68
   */
69
  public $field_name;
70

    
71
  /**
72
   * Whether this revision is the default revision.
73
   *
74
   * @var bool
75
   */
76
  public $default_revision = TRUE;
77

    
78
  /**
79
   * Whether the field collection item is archived, i.e. not in use.
80
   *
81
   * @see FieldCollectionItemEntity::isInUse()
82
   * @var bool
83
   */
84
  public $archived = FALSE;
85

    
86
  /**
87
   * Constructs the entity object.
88
   */
89
  public function __construct(array $values = array(), $entityType = NULL) {
90
    parent::__construct($values, 'field_collection_item');
91
    // Workaround issues http://drupal.org/node/1084268 and
92
    // http://drupal.org/node/1264440:
93
    // Check if the required property is set before checking for the field's
94
    // type. If the property is not set, we are hitting a PDO or a core's bug.
95
    // FIXME: Remove when #1264440 is fixed and the required PHP version is
96
    //  properly identified and documented in the module documentation.
97
    if (isset($this->field_name)) {
98
      // Ok, we have the field name property, we can proceed and check the field's type
99
      $field_info = $this->fieldInfo();
100
      if (!$field_info || $field_info['type'] != 'field_collection') {
101
        throw new Exception("Invalid field name given: {$this->field_name} is not a Field Collection field.");
102
      }
103
    }
104
  }
105

    
106
  /**
107
   * Provides info about the field on the host entity, which embeds this
108
   * field collection item.
109
   */
110
  public function fieldInfo() {
111
    return field_info_field($this->field_name);
112
  }
113

    
114
  /**
115
   * Provides info of the field instance containing the reference to this
116
   * field collection item.
117
   */
118
  public function instanceInfo() {
119
    if ($this->fetchHostDetails()) {
120
      return field_info_instance($this->hostEntityType(), $this->field_name, $this->hostEntityBundle());
121
    }
122
  }
123

    
124
  /**
125
   * Returns the field instance label translated to interface language.
126
   */
127
  public function translatedInstanceLabel($langcode = NULL) {
128
    if ($info = $this->instanceInfo()) {
129
      if (module_exists('i18n_field')) {
130
        return i18n_string("field:{$this->field_name}:{$info['bundle']}:label", $info['label'], array('langcode' => $langcode));
131
      }
132
      return $info['label'];
133
    }
134
  }
135

    
136
  /**
137
   * Specifies the default label, which is picked up by label() by default.
138
   */
139
  public function defaultLabel() {
140
    if ($this->fetchHostDetails()) {
141
      $field = $this->fieldInfo();
142
      $label = $this->translatedInstanceLabel();
143
      $host  = $this->hostEntity();
144

    
145
      if ($new_label = module_invoke_all('field_collection_item_label', $this, $host, $field, $label)) {
146
        return array_pop($new_label);
147
      }
148
      elseif ($field['cardinality'] == 1) {
149
        return $label;
150
      }
151
      elseif ($this->item_id) {
152
        return t('!instance_label @count', array('!instance_label' => $label, '@count' => $this->delta() + 1));
153
      }
154
      else {
155
        return t('New !instance_label', array('!instance_label' => $label));
156
      }
157
    }
158
    return t('Unconnected field collection item');
159
  }
160

    
161
  /**
162
   * Returns the path used to view the entity.
163
   */
164
  public function path() {
165
    if ($this->item_id) {
166
      return field_collection_field_get_path($this->fieldInfo()) . '/' . $this->item_id;
167
    }
168
  }
169

    
170
  /**
171
   * Returns the URI as returned by entity_uri().
172
   */
173
  public function defaultUri() {
174
    return array(
175
      'path' => $this->path(),
176
    );
177
  }
178

    
179
  /**
180
   * Sets the host entity. Only possible during creation of a item.
181
   *
182
   * @param $create_link
183
   *   (optional) Whether a field-item linking the host entity to the field
184
   *   collection item should be created.
185
   */
186
  public function setHostEntity($entity_type, $entity, $langcode = LANGUAGE_NONE, $create_link = TRUE) {
187
    if (!empty($this->is_new)) {
188
      $this->hostEntityType = $entity_type;
189
      $this->hostEntity = $entity;
190
      $this->langcode = $langcode;
191

    
192
      list($this->hostEntityId, $this->hostEntityRevisionId) = entity_extract_ids($this->hostEntityType, $this->hostEntity);
193
      // If the host entity is not saved yet, set the id to FALSE. So
194
      // fetchHostDetails() does not try to load the host entity details.
195
      // Checking value of $this->hostEntityId.
196
      if (!isset($this->hostEntityId)) {
197
        $this->hostEntityId = FALSE;
198
      }
199
      // We are create a new field collection for a non-default entity, thus
200
      // set archived to TRUE.
201
      if (!entity_revision_is_default($entity_type, $entity)) {
202
        $this->hostEntityId = FALSE;
203
        $this->archived = TRUE;
204
      }
205
      if ($create_link) {
206
        $entity->{$this->field_name}[$this->langcode][] = array('entity' => $this);
207
      }
208
    }
209
    else {
210
      throw new Exception('The host entity may be set only during creation of a field collection item.');
211
    }
212
  }
213

    
214
  /**
215
   * Updates the wrapped host entity object.
216
   *
217
   * @param object $entity
218
   *   Host entity.
219
   * @param string $host_entity_type
220
   *   The entity type of the entity the field collection is attached to.
221
   */
222
  public function updateHostEntity($entity, $host_entity_type = NULL) {
223
    $this->fetchHostDetails();
224
    // If it isn't possible to retrieve hostEntityType due to the fact that it's
225
    // not saved in the DB yet then fill in info about the hostEntity manually.
226
    // This happens when creating a new revision of a field collection entity
227
    // and it needs to relate to the new revision of the host entity.
228
    if (!$this->hostEntityType) {
229
      $this->hostEntityType = $host_entity_type;
230
      $this->hostEntity = $entity;
231
      list($this->hostEntityId, $this->hostEntityRevisionId) = entity_extract_ids($this->hostEntityType, $this->hostEntity);
232
    }
233
    list($recieved_id) = entity_extract_ids($this->hostEntityType, $entity);
234

    
235
    if ($this->isInUse() && !empty($this->hostEntityId)) {
236
      $current_id = $this->hostEntityId;
237
    }
238
    else {
239
      $current_host = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
240
      list($current_id) = entity_extract_ids($this->hostEntityType, $current_host);
241
    }
242

    
243
    if ($current_id == $recieved_id) {
244
      $this->hostEntity = $entity;
245
      $delta = $this->delta();
246
      if (isset($entity->{$this->field_name}[$this->langcode()][$delta]['entity'])) {
247
        $entity->{$this->field_name}[$this->langcode()][$delta]['entity'] = $this;
248
      }
249
    }
250
    else {
251
      throw new Exception('The host entity cannot be changed.');
252
    }
253
  }
254

    
255
  /**
256
   * Returns the host entity, which embeds this field collection item.
257
   */
258
  public function hostEntity() {
259
    if ($this->fetchHostDetails()) {
260
      if (!isset($this->hostEntity) && $this->isInUse()) {
261
        $this->hostEntity = entity_load_single($this->hostEntityType, $this->hostEntityId);
262
      }
263
      elseif (!isset($this->hostEntity) && $this->hostEntityRevisionId) {
264
        $this->hostEntity = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
265
      }
266
      return $this->hostEntity;
267
    }
268
  }
269

    
270
  /**
271
   * Returns the entity type of the host entity, which embeds this
272
   * field collection item.
273
   */
274
  public function hostEntityType() {
275
    if ($this->fetchHostDetails()) {
276
      return $this->hostEntityType;
277
    }
278
  }
279

    
280
  /**
281
   * Returns the id of the host entity, which embeds this field collection item.
282
   */
283
  public function hostEntityId() {
284
    if ($this->fetchHostDetails()) {
285
      if (!$this->hostEntityId && $this->hostEntityRevisionId) {
286
        $this->hostEntityId = entity_id($this->hostEntityType, $this->hostEntity());
287
      }
288
      return $this->hostEntityId;
289
    }
290
  }
291

    
292
  /**
293
   * Returns the bundle of the host entity, which embeds this field collection
294
   * item.
295
   */
296
  public function hostEntityBundle() {
297
    if ($entity = $this->hostEntity()) {
298
      list($id, $rev_id, $bundle) = entity_extract_ids($this->hostEntityType, $entity);
299
      return $bundle;
300
    }
301
  }
302

    
303
  protected function fetchHostDetails() {
304
    if (!isset($this->hostEntityId) || (!$this->hostEntityId && $this->hostEntityRevisionId)) {
305
      if ($this->item_id) {
306
        // For saved field collections, query the field data to determine the
307
        // right host entity.
308
        $query = new EntityFieldQuery();
309
        $query->fieldCondition($this->fieldInfo(), 'revision_id', $this->revision_id);
310
        if (!$this->isInUse()) {
311
          $query->age(FIELD_LOAD_REVISION);
312
        }
313
        $result = $query->execute();
314
        if ($result) {
315
          $this->hostEntityType = key($result);
316
          $data = current($result);
317

    
318
          if ($this->isInUse()) {
319
            $data_array_keys = array_keys($data);
320
            $this->hostEntityId = $data ? end($data_array_keys) : FALSE;
321
            $this->hostEntityRevisionId = FALSE;
322
          }
323
          // If we are querying for revisions, we get the revision ID.
324
          else {
325
            $data_array_keys = array_keys($data);
326
            $this->hostEntityId = FALSE;
327
            $this->hostEntityRevisionId = $data ? end($data_array_keys) : FALSE;
328
          }
329
        }
330
        else {
331
          // No host entity available yet.
332
          $this->hostEntityId = FALSE;
333
        }
334
      }
335
      else {
336
        // No host entity available yet.
337
        $this->hostEntityId = FALSE;
338
      }
339
    }
340
    return !empty($this->hostEntityId) || !empty($this->hostEntity) || !empty($this->hostEntityRevisionId);
341
  }
342

    
343
  /**
344
   * Determines the $delta of the reference pointing to this field collection
345
   * item.
346
   */
347
  public function delta() {
348
    if (($entity = $this->hostEntity()) && isset($entity->{$this->field_name})) {
349
      foreach ($entity->{$this->field_name} as $langcode => &$data) {
350
        if (!empty($data)) {
351
          foreach ($data as $delta => $item) {
352
            if (isset($item['value']) && $item['value'] == $this->item_id) {
353
              $this->langcode = $langcode;
354
              return $delta;
355
            }
356
            elseif (isset($item['entity']) && $item['entity'] === $this) {
357
              $this->langcode = $langcode;
358
              return $delta;
359
            }
360
          }
361
        }
362
      }
363
      // If we don't find the delta in the current values (cause the item
364
      // is being deleted, for example), we search the delta in the originalcontent.
365
      if (!empty($entity->original)) {
366
        foreach ($entity->original->{$this->field_name} as $langcode => &$data) {
367
          if (!empty($data)) {
368
            foreach ($data as $delta => $item) {
369
              if (isset($item['value']) && $item['value'] == $this->item_id) {
370
                $this->langcode = $langcode;
371
                return $delta;
372
              }
373
              elseif (isset($item['entity']) && $item['entity'] === $this) {
374
                $this->langcode = $langcode;
375
                return $delta;
376
              }
377
            }
378
          }
379
        }
380
      }
381
    }
382
  }
383

    
384
  /**
385
   * Determines the language code under which the item is stored.
386
   */
387
  public function langcode() {
388
    if ($this->delta() === NULL || empty($this->langcode)) {
389
      $this->langcode = field_collection_entity_language('field_collection_item', $this);
390
    }
391

    
392
    if (empty($this->langcode) || ($this->langcode != LANGUAGE_NONE && (!module_exists('entity_translation') || !entity_translation_enabled('field_collection_item')))) {
393
      $this->langcode = LANGUAGE_NONE;
394
    }
395

    
396
    return $this->langcode;
397
  }
398

    
399
  /**
400
   * Determines whether this field collection item revision is in use.
401
   *
402
   * Field collection items may be contained in from non-default host entity
403
   * revisions. If the field collection item does not appear in the default
404
   * host entity revision, the item is actually not used by default and so
405
   * marked as 'archived'.
406
   * If the field collection item appears in the default revision of the host
407
   * entity, the default revision of the field collection item is in use there
408
   * and the collection is not marked as archived.
409
   */
410
  public function isInUse() {
411
    return $this->default_revision && !$this->archived;
412
  }
413

    
414
  /**
415
   * Save the field collection item.
416
   *
417
   * By default, always save the host entity, so modules are able to react
418
   * upon changes to the content of the host and any 'last updated' dates of
419
   * entities get updated.
420
   *
421
   * For creating an item a host entity has to be specified via setHostEntity()
422
   * before this function is invoked. For the link between the entities to be
423
   * fully established, the host entity object has to be updated to include a
424
   * reference on this field collection item during saving. So do not skip
425
   * saving the host for creating items.
426
   *
427
   * @param $skip_host_save
428
   *   (internal) If TRUE is passed, the host entity is not saved automatically
429
   *   and therefore no link is created between the host and the item or
430
   *   revision updates might be skipped. Use with care.
431
   */
432
  public function save($skip_host_save = FALSE) {
433
    // Make sure we have a host entity during creation.
434
    if (!empty($this->is_new) && !(isset($this->hostEntityId) || isset($this->hostEntity) || isset($this->hostEntityRevisionId))) {
435
      throw new Exception("Unable to create a field collection item without a given host entity.");
436
    }
437

    
438
    // Copy the values of translatable fields for a new field collection item.
439
    if (field_collection_item_is_translatable() && !empty($this->is_new) && $this->langcode() == LANGUAGE_NONE) {
440
      $this->copyTranslations();
441
    }
442

    
443
    // Only save directly if we are told to skip saving the host entity. Else,
444
    // we always save via the host as saving the host might trigger saving
445
    // field collection items anyway (e.g. if a new revision is created).
446
    if ($skip_host_save) {
447
      return entity_get_controller($this->entityType)->save($this);
448
    }
449
    else {
450
      $host_entity = $this->hostEntity();
451
      if (!$host_entity) {
452
        throw new Exception("Unable to save a field collection item without a valid reference to a host entity.");
453
      }
454
      // If this is creating a new revision, also do so for the host entity.
455
      if (!empty($this->revision) || !empty($this->is_new_revision)) {
456
        $host_entity->revision = TRUE;
457
        if (!empty($this->default_revision)) {
458
          entity_revision_set_default($this->hostEntityType, $host_entity);
459
        }
460
      }
461
      // Set the host entity reference, so the item will be saved with the host.
462
      // @see field_collection_field_presave()
463
      $delta = $this->delta();
464
      if (isset($delta)) {
465
        $host_entity->{$this->field_name}[$this->langcode()][$delta] = array('entity' => $this);
466
      }
467
      else {
468
        $host_entity->{$this->field_name}[$this->langcode()][] = array('entity' => $this);
469
      }
470

    
471
      return entity_save($this->hostEntityType, $host_entity);
472
    }
473
  }
474

    
475
  /**
476
   * Deletes the field collection item and the reference in the host entity.
477
   */
478
  public function delete($skip_host_save = FALSE) {
479
    parent::delete();
480
    if (!$skip_host_save) {
481
      $this->deleteHostEntityReference();
482
    }
483
  }
484

    
485
  /**
486
   * Copies text to all languages the collection item has a translation for.
487
   *
488
   * @param $source_language
489
   *   Language code to copy the text from.
490
   */
491
  public function copyTranslations($source_language = NULL) {
492
    // Get a handler for Entity Translation if there is one.
493
    $host_et_handler = NULL;
494
    if (module_exists('entity_translation')) {
495
      $host_et_handler = entity_translation_get_handler($this->hostEntityType(), $this->hostEntity());
496
    }
497
    if (is_null($host_et_handler)) {
498
      return;
499
    }
500

    
501
    $host_languages = array_keys($host_et_handler->getTranslations()->data);
502
    if (empty($host_languages)) {
503
      $host_languages = array(entity_language($this->hostEntityType(), $this->hostEntity()));
504
    }
505
    $source_language = isset($source_language) ? $source_language : $host_et_handler->getLanguage();
506
    $target_languages = array_diff($host_languages, array($source_language));
507
    $fields_instances = array_keys(field_info_instances('field_collection_item', $this->field_name));
508
    $fields = field_info_fields();
509

    
510
    foreach ($fields_instances as $translatable_field) {
511
      if ($fields[$translatable_field]['translatable'] == 1) {
512
        foreach ($target_languages as $langcode) {
513
          if (isset($this->{$translatable_field}[$source_language])) {
514
            //Source (translatable_field) is set, therefore continue processing.
515
            if(!isset($this->{$translatable_field}[$langcode])) {
516
              //Destination (translatable_field) is not set, therefore safe to copy the translation.
517
              $this->{$translatable_field}[$langcode] = $this->{$translatable_field}[$source_language];
518
            }
519
          }
520
        }
521
        if ($source_language == LANGUAGE_NONE && count($this->{$translatable_field}) > 1) {
522
          $this->{$translatable_field}[$source_language] = NULL;
523
        }
524
      }
525
    }
526
  }
527

    
528
  /**
529
   * Deletes the host entity's reference of the field collection item.
530
   */
531
  protected function deleteHostEntityReference() {
532
    $delta = $this->delta();
533
    if ($this->item_id && isset($delta)) {
534
      unset($this->hostEntity->{$this->field_name}[$this->langcode()][$delta]);
535
      // Do not save when the host entity is being deleted. See
536
      // field_collection_field_delete().
537
      if (empty($this->hostEntity->field_collection_deleting)) {
538
        entity_save($this->hostEntityType(), $this->hostEntity());
539
      }
540
    }
541
  }
542

    
543
  /**
544
   * Intelligently delete a field collection item revision.
545
   *
546
   * If a host entity is revisioned with its field collection items, deleting
547
   * a field collection item on the default revision of the host should not
548
   * delete the collection item from archived revisions too. Instead, we delete
549
   * the current default revision and archive the field collection.
550
   */
551
  public function deleteRevision($skip_host_update = FALSE) {
552
    if (!$this->revision_id) {
553
      return;
554
    }
555

    
556
    if (!$skip_host_update) {
557
      // Just remove the item from the host, which cares about deleting the
558
      // item (depending on whether the update creates a new revision).
559
      $this->deleteHostEntityReference();
560
    }
561

    
562
    if (!$this->isDefaultRevision()) {
563
      entity_revision_delete('field_collection_item', $this->revision_id);
564
    }
565
    // If deleting the default revision, take care!
566
    else {
567
      $row = db_select('field_collection_item_revision', 'r')
568
        ->fields('r')
569
        ->condition('item_id', $this->item_id)
570
        ->condition('revision_id', $this->revision_id, '<>')
571
        ->execute()
572
        ->fetchAssoc();
573

    
574
      if ($row) {
575
        // Make the other revision the default revision and archive the item.
576
        db_update('field_collection_item')
577
          ->fields(array('archived' => 1, 'revision_id' => $row['revision_id']))
578
          ->condition('item_id', $this->item_id)
579
          ->execute();
580
        entity_get_controller('field_collection_item')->resetCache(array($this->item_id));
581
        entity_revision_delete('field_collection_item', $this->revision_id);
582
      }
583
      if (!$row && !isset($this->hostEntity()->{$this->field_name}[$this->langcode()][$this->delta()])) {
584
        // Delete if there is no existing revision or translation to be saved.
585
        $this->delete($skip_host_update);
586
      }
587
    }
588
  }
589

    
590
  /**
591
   * Export the field collection item.
592
   *
593
   * Since field collection entities are not directly exportable (i.e., do not
594
   * have 'exportable' set to TRUE in hook_entity_info()) and since Features
595
   * calls this method when exporting the field collection as a field attached
596
   * to another entity, we return the export in the format expected by
597
   * Features, rather than in the normal Entity::export() format.
598
   */
599
  public function export($prefix = '') {
600
    // Based on code in EntityDefaultFeaturesController::export_render().
601
    $export = "entity_import('" . $this->entityType() . "', '";
602
    $export .= addcslashes(parent::export(), '\\\'');
603
    $export .= "')";
604
    return $export;
605
  }
606

    
607
  /**
608
   * Generate an array for rendering the field collection item.
609
   */
610
  public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
611
    // Allow modules to change the view mode.
612
    $view_mode = key(entity_view_mode_prepare($this->entityType, array($this->item_id => $this), $view_mode, $langcode));
613
    return parent::view($view_mode, $langcode, $page);
614
  }
615

    
616
  /**
617
   * Magic method to only serialize what's necessary.
618
   */
619
  public function __sleep() {
620
    $vars = get_object_vars($this);
621
    unset($vars['entityInfo'], $vars['idKey'], $vars['nameKey'], $vars['statusKey']);
622
    unset($vars['fieldInfo']);
623
    // Also do not serialize the host entity, but only if it has already an id.
624
    if ($this->hostEntity && ($this->hostEntityId || $this->hostEntityRevisionId)) {
625
      unset($vars['hostEntity']);
626
    }
627

    
628
    // Also key the returned array with the variable names so the method may
629
    // be easily overridden and customized.
630
    return drupal_map_assoc(array_keys($vars));
631
  }
632

    
633
  /**
634
   * Magic method to invoke setUp() on unserialization.
635
   *
636
   * @todo: Remove this once it appears in a released entity API module version.
637
   */
638
  public function __wakeup() {
639
    $this->setUp();
640
  }
641
}