Projet

Général

Profil

Paste
Télécharger (22,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / field_collection / field_collection.entity.inc @ a1cafe7e

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

    
149
      if ($field['cardinality'] == 1) {
150
        return $label;
151
      }
152

    
153
      if ($this->item_id) {
154
        return t('!instance_label @count', array('!instance_label' => $label, '@count' => $this->delta() + 1));
155
      }
156

    
157
      return t('New !instance_label', array('!instance_label' => $label));
158
    }
159
    return t('Unconnected field collection item');
160
  }
161

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

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

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

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

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

    
236
    if (!empty($this->hostEntityId) && $this->isInUse()) {
237
      if (is_array($this->hostEntityId)) {
238
        $current_id = in_array($recieved_id, $this->hostEntityId)
239
          ? $recieved_id
240
          : FALSE;
241
      }
242
      else {
243
        $current_id = $this->hostEntityId;
244
      }
245
    }
246
    else {
247
      $current_host = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
248
      list($current_id) = $current_host ? entity_extract_ids($this->hostEntityType, $current_host) : array($recieved_id);
249
    }
250

    
251
    if ($current_id == $recieved_id) {
252
      $this->hostEntity = $entity;
253
      $delta = $this->delta();
254
      if (isset($entity->{$this->field_name}[$this->langcode()][$delta]['entity'])) {
255
        $entity->{$this->field_name}[$this->langcode()][$delta]['entity'] = $this;
256
      }
257
    }
258
    else {
259
      throw new Exception('The host entity cannot be changed.');
260
    }
261
  }
262

    
263
  /**
264
   * Returns the host entity, which embeds this field collection item.
265
   */
266
  public function hostEntity() {
267
    if ($this->fetchHostDetails()) {
268
      if (!isset($this->hostEntity) && $this->isInUse()) {
269
        $this->hostEntity = entity_load_single($this->hostEntityType, $this->hostEntityId);
270
      }
271
      elseif (!isset($this->hostEntity) && $this->hostEntityRevisionId) {
272
        $this->hostEntity = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
273
      }
274
      return $this->hostEntity;
275
    }
276
  }
277

    
278
  /**
279
   * Returns the entity type of the host entity, which embeds this
280
   * field collection item.
281
   */
282
  public function hostEntityType() {
283
    if ($this->fetchHostDetails()) {
284
      return $this->hostEntityType;
285
    }
286
  }
287

    
288
  /**
289
   * Returns the id of the host entity, which embeds this field collection item.
290
   */
291
  public function hostEntityId() {
292
    if ($this->fetchHostDetails()) {
293
      if (!$this->hostEntityId && $this->hostEntityRevisionId) {
294
        $this->hostEntityId = entity_id($this->hostEntityType, $this->hostEntity());
295
      }
296
      return $this->hostEntityId;
297
    }
298
  }
299

    
300
  /**
301
   * Returns the bundle of the host entity, which embeds this field collection
302
   * item.
303
   */
304
  public function hostEntityBundle() {
305
    if ($entity = $this->hostEntity()) {
306
      list($id, $rev_id, $bundle) = entity_extract_ids($this->hostEntityType, $entity);
307
      return $bundle;
308
    }
309
  }
310

    
311
  /**
312
   * Collects info about the field collection's host.
313
   *
314
   * @param $hostEntity
315
   *   The host entity object. (optional)
316
   */
317
  protected function fetchHostDetails($hostEntity = NULL) {
318
    if (!isset($this->hostEntityId) || (!$this->hostEntityId && $this->hostEntityRevisionId)) {
319
      if ($this->item_id) {
320
        // For saved field collections, query the field data to determine the
321
        // right host entity.
322
        $query = new EntityFieldQuery();
323
        $field_info = $this->fieldInfo();
324
        $query->fieldCondition($field_info, 'revision_id', $this->revision_id);
325
        if ($hostEntity) {
326
          $entity_type = key($field_info['bundles']);
327
          $bundle = current($field_info['bundles'][$entity_type]);
328
          $entity_info = entity_get_info($entity_type);
329
          $key = $entity_info['entity keys']['id'];
330
          $query->entityCondition('entity_type', $entity_type);
331
          $query->entityCondition('entity_id', $hostEntity->{$key});
332
          $query->entityCondition('bundle', $bundle);
333
          if (isset($entity_info['entity keys']['language'])) {
334
            $query->propertyCondition('language', $hostEntity->language);
335
          }
336
        }
337
        $query->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
338
        if (!$this->isInUse()) {
339
          $query->age(FIELD_LOAD_REVISION);
340
        }
341
        $result = $query->execute();
342
        if ($result) {
343
          $this->hostEntityType = key($result);
344
          $data = current($result);
345

    
346
          if ($this->isInUse()) {
347
            $data_array_keys = array_keys($data);
348
            $this->hostEntityId = $data ? end($data_array_keys) : FALSE;
349
            $this->hostEntityRevisionId = FALSE;
350
          }
351
          // If we are querying for revisions, we get the revision ID.
352
          else {
353
            $data_array_keys = array_keys($data);
354
            $this->hostEntityId = FALSE;
355
            $this->hostEntityRevisionId = $data ? end($data_array_keys) : FALSE;
356
          }
357
        }
358
        else {
359
          // No host entity available yet.
360
          $this->hostEntityId = FALSE;
361
        }
362
      }
363
      else {
364
        // No host entity available yet.
365
        $this->hostEntityId = FALSE;
366
      }
367
    }
368
    return !empty($this->hostEntityId) || !empty($this->hostEntity) || !empty($this->hostEntityRevisionId);
369
  }
370

    
371
  /**
372
   * Determines the $delta of the reference pointing to this field collection
373
   * item.
374
   */
375
  public function delta() {
376
    if (($entity = $this->hostEntity()) && isset($entity->{$this->field_name})) {
377
      foreach ($entity->{$this->field_name} as $langcode => &$data) {
378
        if (!empty($data)) {
379
          foreach ($data as $delta => $item) {
380
            if (isset($item['value']) && $item['value'] == $this->item_id) {
381
              $this->langcode = $langcode;
382
              return $delta;
383
            }
384

    
385
            if (isset($item['entity']) && $item['entity'] === $this) {
386
              $this->langcode = $langcode;
387
              return $delta;
388
            }
389
          }
390
        }
391
      }
392
      // If we don't find the delta in the current values (cause the item
393
      // is being deleted, for example), we search the delta in the originalcontent.
394
      if (!empty($entity->original)) {
395
        foreach ($entity->original->{$this->field_name} as $langcode => &$data) {
396
          if (!empty($data)) {
397
            foreach ($data as $delta => $item) {
398
              if (isset($item['value']) && $item['value'] == $this->item_id) {
399
                $this->langcode = $langcode;
400
                return $delta;
401
              }
402

    
403
              if (isset($item['entity']) && $item['entity'] === $this) {
404
                $this->langcode = $langcode;
405
                return $delta;
406
              }
407
            }
408
          }
409
        }
410
      }
411
    }
412
  }
413

    
414
  /**
415
   * Determines the language code under which the item is stored.
416
   */
417
  public function langcode() {
418
    if (empty($this->langcode) || $this->delta() === NULL) {
419
      $this->langcode = field_collection_entity_language('field_collection_item', $this);
420
    }
421

    
422
    if (empty($this->langcode) || ($this->langcode != LANGUAGE_NONE && (!module_exists('entity_translation') || !entity_translation_enabled('field_collection_item')))) {
423
      $this->langcode = LANGUAGE_NONE;
424
    }
425

    
426
    return $this->langcode;
427
  }
428

    
429
  /**
430
   * Determines whether this field collection item revision is in use.
431
   *
432
   * Field Collection items may be contained in from non-default host entity
433
   * revisions. If the field collection item does not appear in the default
434
   * host entity revision, the item is actually not used by default and so
435
   * marked as 'archived'.
436
   * If the field collection item appears in the default revision of the host
437
   * entity, the default revision of the field collection item is in use there
438
   * and the collection is not marked as archived.
439
   */
440
  public function isInUse() {
441
    return $this->default_revision && !$this->archived;
442
  }
443

    
444
  /**
445
   * Save the field collection item.
446
   *
447
   * By default, always save the host entity, so modules are able to react
448
   * upon changes to the content of the host and any 'last updated' dates of
449
   * entities get updated.
450
   *
451
   * For creating an item a host entity has to be specified via setHostEntity()
452
   * before this function is invoked. For the link between the entities to be
453
   * fully established, the host entity object has to be updated to include a
454
   * reference on this field collection item during saving. So do not skip
455
   * saving the host for creating items.
456
   *
457
   * @param $skip_host_save
458
   *   (internal) If TRUE is passed, the host entity is not saved automatically
459
   *   and therefore no link is created between the host and the item or
460
   *   revision updates might be skipped. Use with care.
461
   */
462
  public function save($skip_host_save = FALSE) {
463
    // Make sure we have a host entity during creation.
464
    if (!empty($this->is_new) && !(isset($this->hostEntityId) || isset($this->hostEntity) || isset($this->hostEntityRevisionId))) {
465
      throw new Exception('Unable to create a field collection item without a given host entity.');
466
    }
467

    
468
    // Copy the values of translatable fields for a new field collection item.
469
    if (!empty($this->is_new) && field_collection_item_is_translatable() && $this->langcode() == LANGUAGE_NONE) {
470
      $this->copyTranslations();
471
    }
472

    
473
    // Only save directly if we are told to skip saving the host entity. Else,
474
    // we always save via the host as saving the host might trigger saving
475
    // field collection items anyway (e.g. if a new revision is created).
476
    if ($skip_host_save) {
477
      return entity_get_controller($this->entityType)->save($this);
478
    }
479

    
480
    $host_entity = $this->hostEntity();
481
    if (!$host_entity) {
482
      throw new Exception('Unable to save a field collection item without a valid reference to a host entity.');
483
    }
484
    // If this is creating a new revision, also do so for the host entity.
485
    if (!empty($this->revision) || !empty($this->is_new_revision)) {
486
      $host_entity->revision = TRUE;
487
      if (!empty($this->default_revision)) {
488
        entity_revision_set_default($this->hostEntityType, $host_entity);
489
      }
490
    }
491
    // Set the host entity reference, so the item will be saved with the host.
492
    // @see field_collection_field_presave()
493
    $delta = $this->delta();
494
    if (isset($delta)) {
495
      $host_entity->{$this->field_name}[$this->langcode()][$delta] = array('entity' => $this);
496
    }
497
    else {
498
      $host_entity->{$this->field_name}[$this->langcode()][] = array('entity' => $this);
499
    }
500

    
501
    return entity_save($this->hostEntityType, $host_entity);
502
  }
503

    
504
  /**
505
   * Deletes the field collection item and the reference in the host entity.
506
   */
507
  public function delete($skip_host_save = FALSE) {
508
    parent::delete();
509
    if (!$skip_host_save) {
510
      $this->deleteHostEntityReference();
511
    }
512
  }
513

    
514
  /**
515
   * Copies text to all languages the collection item has a translation for.
516
   *
517
   * @param $source_language
518
   *   Language code to copy the text from.
519
   */
520
  public function copyTranslations($source_language = NULL) {
521
    // Get a handler for Entity Translation if there is one.
522
    $host_et_handler = NULL;
523
    if (module_exists('entity_translation')) {
524
      $host_et_handler = entity_translation_get_handler($this->hostEntityType(), $this->hostEntity());
525
    }
526
    if (is_null($host_et_handler)) {
527
      return;
528
    }
529

    
530
    $host_languages = array_keys($host_et_handler->getTranslations()->data);
531
    if (empty($host_languages)) {
532
      $host_languages = array(entity_language($this->hostEntityType(), $this->hostEntity()));
533
    }
534
    $source_language = isset($source_language) ? $source_language : $host_et_handler->getLanguage();
535
    $target_languages = array_diff($host_languages, array($source_language));
536
    $fields_instances = array_keys(field_info_instances('field_collection_item', $this->field_name));
537
    $fields = field_info_fields();
538

    
539
    foreach ($fields_instances as $translatable_field) {
540
      if ($fields[$translatable_field]['translatable'] == 1) {
541
        foreach ($target_languages as $langcode) {
542
          // Source (translatable_field) is set, therefore continue
543
          // processing.
544
          if (isset($this->{$translatable_field}[$source_language])
545
            && !isset($this->{$translatable_field}[$langcode])) {
546
            // Destination (translatable_field) is not set, therefore safe to
547
            // copy the translation.
548
            $this->{$translatable_field}[$langcode] = $this->{$translatable_field}[$source_language];
549
          }
550
        }
551
        if ($source_language == LANGUAGE_NONE && count($this->{$translatable_field}) > 1) {
552
          $this->{$translatable_field}[$source_language] = NULL;
553
        }
554
      }
555
    }
556
  }
557

    
558
  /**
559
   * Deletes the host entity's reference of the field collection item.
560
   */
561
  protected function deleteHostEntityReference() {
562
    $delta = $this->delta();
563
    if ($this->item_id && isset($delta)) {
564
      unset($this->hostEntity->{$this->field_name}[$this->langcode()][$delta]);
565
      // Do not save when the host entity is being deleted. See
566
      // field_collection_field_delete().
567
      if (empty($this->hostEntity->field_collection_deleting)) {
568
        entity_save($this->hostEntityType(), $this->hostEntity());
569
      }
570
    }
571
  }
572

    
573
  /**
574
   * Intelligently delete a field collection item revision.
575
   *
576
   * If a host entity is revisioned with its field collection items, deleting
577
   * a field collection item on the default revision of the host should not
578
   * delete the collection item from archived revisions too. Instead, we delete
579
   * the current default revision and archive the field collection.
580
   */
581
  public function deleteRevision($skip_host_update = FALSE) {
582
    if (!$this->revision_id) {
583
      return;
584
    }
585

    
586
    if (!$skip_host_update) {
587
      // Just remove the item from the host, which cares about deleting the
588
      // item (depending on whether the update creates a new revision).
589
      $this->deleteHostEntityReference();
590
    }
591

    
592
    if (!$this->isDefaultRevision()) {
593
      entity_revision_delete('field_collection_item', $this->revision_id);
594
    }
595
    // If deleting the default revision, take care!
596
    else {
597
      $row = db_select('field_collection_item_revision', 'r')
598
        ->fields('r')
599
        ->condition('item_id', $this->item_id)
600
        ->condition('revision_id', $this->revision_id, '<>')
601
        ->execute()
602
        ->fetchAssoc();
603

    
604
      if ($row) {
605
        // Make the other revision the default revision and archive the item.
606
        db_update('field_collection_item')
607
          ->fields(array('archived' => 1, 'revision_id' => $row['revision_id']))
608
          ->condition('item_id', $this->item_id)
609
          ->execute();
610
        entity_get_controller('field_collection_item')->resetCache(array($this->item_id));
611
        entity_revision_delete('field_collection_item', $this->revision_id);
612
      }
613
      else {
614
        // Delete if there is no existing revision or translation to be saved.
615
        $this->delete($skip_host_update);
616
      }
617
    }
618
  }
619

    
620
  /**
621
   * Export the field collection item.
622
   *
623
   * Since field collection entities are not directly exportable (i.e., do not
624
   * have 'exportable' set to TRUE in hook_entity_info()) and since Features
625
   * calls this method when exporting the field collection as a field attached
626
   * to another entity, we return the export in the format expected by
627
   * Features, rather than in the normal Entity::export() format.
628
   */
629
  public function export($prefix = '') {
630
    // Based on code in EntityDefaultFeaturesController::export_render().
631
    $export = "entity_import('" . $this->entityType() . "', '";
632
    $export .= addcslashes(parent::export(), '\\\'');
633
    $export .= "')";
634
    return $export;
635
  }
636

    
637
  /**
638
   * Generate an array for rendering the field collection item.
639
   */
640
  public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
641
    // Allow modules to change the view mode.
642
    $view_mode = key(entity_view_mode_prepare($this->entityType, array($this->item_id => $this), $view_mode, $langcode));
643
    return parent::view($view_mode, $langcode, $page);
644
  }
645

    
646
  /**
647
   * Magic method to only serialize what's necessary.
648
   */
649
  public function __sleep() {
650
    $vars = get_object_vars($this);
651
    unset($vars['entityInfo'], $vars['idKey'], $vars['nameKey'], $vars['statusKey']);
652
    unset($vars['fieldInfo']);
653
    // Also do not serialize the host entity, but only if it has already an id.
654
    if ($this->hostEntity && ($this->hostEntityId || $this->hostEntityRevisionId)) {
655
      unset($vars['hostEntity']);
656
    }
657

    
658
    // Also key the returned array with the variable names so the method may
659
    // be easily overridden and customized.
660
    return drupal_map_assoc(array_keys($vars));
661
  }
662

    
663
}