Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / Entity / ContentEntityBase.php
1 <?php
2
3 namespace Drupal\Core\Entity;
4
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Entity\Plugin\DataType\EntityReference;
7 use Drupal\Core\Field\BaseFieldDefinition;
8 use Drupal\Core\Language\Language;
9 use Drupal\Core\Language\LanguageInterface;
10 use Drupal\Core\Session\AccountInterface;
11 use Drupal\Core\StringTranslation\TranslatableMarkup;
12 use Drupal\Core\TypedData\TranslationStatusInterface;
13 use Drupal\Core\TypedData\TypedDataInterface;
14
15 /**
16  * Implements Entity Field API specific enhancements to the Entity class.
17  *
18  * @ingroup entity_api
19  */
20 abstract class ContentEntityBase extends Entity implements \IteratorAggregate, ContentEntityInterface, TranslationStatusInterface {
21
22   use EntityChangesDetectionTrait {
23     getFieldsToSkipFromTranslationChangesCheck as traitGetFieldsToSkipFromTranslationChangesCheck;
24   }
25
26   /**
27    * The plain data values of the contained fields.
28    *
29    * This always holds the original, unchanged values of the entity. The values
30    * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
31    * is used for values in default language.
32    *
33    * @todo: Add methods for getting original fields and for determining
34    * changes.
35    * @todo: Provide a better way for defining default values.
36    *
37    * @var array
38    */
39   protected $values = [];
40
41   /**
42    * The array of fields, each being an instance of FieldItemListInterface.
43    *
44    * @var array
45    */
46   protected $fields = [];
47
48   /**
49    * Local cache for field definitions.
50    *
51    * @see ContentEntityBase::getFieldDefinitions()
52    *
53    * @var array
54    */
55   protected $fieldDefinitions;
56
57   /**
58    * Local cache for the available language objects.
59    *
60    * @var \Drupal\Core\Language\LanguageInterface[]
61    */
62   protected $languages;
63
64   /**
65    * The language entity key.
66    *
67    * @var string
68    */
69   protected $langcodeKey;
70
71   /**
72    * The default langcode entity key.
73    *
74    * @var string
75    */
76   protected $defaultLangcodeKey;
77
78   /**
79    * Language code identifying the entity active language.
80    *
81    * This is the language field accessors will use to determine which field
82    * values manipulate.
83    *
84    * @var string
85    */
86   protected $activeLangcode = LanguageInterface::LANGCODE_DEFAULT;
87
88   /**
89    * Local cache for the default language code.
90    *
91    * @var string
92    */
93   protected $defaultLangcode;
94
95   /**
96    * An array of entity translation metadata.
97    *
98    * An associative array keyed by translation language code. Every value is an
99    * array containing the translation status and the translation object, if it has
100    * already been instantiated.
101    *
102    * @var array
103    */
104   protected $translations = [];
105
106   /**
107    * A flag indicating whether a translation object is being initialized.
108    *
109    * @var bool
110    */
111   protected $translationInitialize = FALSE;
112
113   /**
114    * Boolean indicating whether a new revision should be created on save.
115    *
116    * @var bool
117    */
118   protected $newRevision = FALSE;
119
120   /**
121    * Indicates whether this is the default revision.
122    *
123    * @var bool
124    */
125   protected $isDefaultRevision = TRUE;
126
127   /**
128    * Holds untranslatable entity keys such as the ID, bundle, and revision ID.
129    *
130    * @var array
131    */
132   protected $entityKeys = [];
133
134   /**
135    * Holds translatable entity keys such as the label.
136    *
137    * @var array
138    */
139   protected $translatableEntityKeys = [];
140
141   /**
142    * Whether entity validation was performed.
143    *
144    * @var bool
145    */
146   protected $validated = FALSE;
147
148   /**
149    * Whether entity validation is required before saving the entity.
150    *
151    * @var bool
152    */
153   protected $validationRequired = FALSE;
154
155   /**
156    * The loaded revision ID before the new revision was set.
157    *
158    * @var int
159    */
160   protected $loadedRevisionId;
161
162   /**
163    * The revision translation affected entity key.
164    *
165    * @var string
166    */
167   protected $revisionTranslationAffectedKey;
168
169   /**
170    * Whether the revision translation affected flag has been enforced.
171    *
172    * An array, keyed by the translation language code.
173    *
174    * @var bool[]
175    */
176   protected $enforceRevisionTranslationAffected = [];
177
178   /**
179    * Local cache for fields to skip from the checking for translation changes.
180    *
181    * @var array
182    */
183   protected static $fieldsToSkipFromTranslationChangesCheck = [];
184
185   /**
186    * {@inheritdoc}
187    */
188   public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
189     $this->entityTypeId = $entity_type;
190     $this->entityKeys['bundle'] = $bundle ? $bundle : $this->entityTypeId;
191     $this->langcodeKey = $this->getEntityType()->getKey('langcode');
192     $this->defaultLangcodeKey = $this->getEntityType()->getKey('default_langcode');
193     $this->revisionTranslationAffectedKey = $this->getEntityType()->getKey('revision_translation_affected');
194
195     foreach ($values as $key => $value) {
196       // If the key matches an existing property set the value to the property
197       // to set properties like isDefaultRevision.
198       // @todo: Should this be converted somehow?
199       if (property_exists($this, $key) && isset($value[LanguageInterface::LANGCODE_DEFAULT])) {
200         $this->$key = $value[LanguageInterface::LANGCODE_DEFAULT];
201       }
202     }
203
204     $this->values = $values;
205     foreach ($this->getEntityType()->getKeys() as $key => $field_name) {
206       if (isset($this->values[$field_name])) {
207         if (is_array($this->values[$field_name])) {
208           // We store untranslatable fields into an entity key without using a
209           // langcode key.
210           if (!$this->getFieldDefinition($field_name)->isTranslatable()) {
211             if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
212               if (is_array($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
213                 if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'])) {
214                   $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'];
215                 }
216               }
217               else {
218                 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT];
219               }
220             }
221           }
222           else {
223             // We save translatable fields such as the publishing status of a node
224             // into an entity key array keyed by langcode as a performance
225             // optimization, so we don't have to go through TypedData when we
226             // need these values.
227             foreach ($this->values[$field_name] as $langcode => $field_value) {
228               if (is_array($this->values[$field_name][$langcode])) {
229                 if (isset($this->values[$field_name][$langcode][0]['value'])) {
230                   $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode][0]['value'];
231                 }
232               }
233               else {
234                 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode];
235               }
236             }
237           }
238         }
239       }
240     }
241
242     // Initialize translations. Ensure we have at least an entry for the default
243     // language.
244     // We determine if the entity is new by checking in the entity values for
245     // the presence of the id entity key, as the usage of ::isNew() is not
246     // possible in the constructor.
247     $data = isset($values[$this->getEntityType()->getKey('id')]) ? ['status' => static::TRANSLATION_EXISTING] : ['status' => static::TRANSLATION_CREATED];
248     $this->translations[LanguageInterface::LANGCODE_DEFAULT] = $data;
249     $this->setDefaultLangcode();
250     if ($translations) {
251       foreach ($translations as $langcode) {
252         if ($langcode != $this->defaultLangcode && $langcode != LanguageInterface::LANGCODE_DEFAULT) {
253           $this->translations[$langcode] = $data;
254         }
255       }
256     }
257     if ($this->getEntityType()->isRevisionable()) {
258       // Store the loaded revision ID the entity has been loaded with to
259       // keep it safe from changes.
260       $this->updateLoadedRevisionId();
261     }
262   }
263
264   /**
265    * {@inheritdoc}
266    */
267   protected function getLanguages() {
268     if (empty($this->languages)) {
269       $this->languages = $this->languageManager()->getLanguages(LanguageInterface::STATE_ALL);
270       // If the entity references a language that is not or no longer available,
271       // we return a mock language object to avoid disrupting the consuming
272       // code.
273       if (!isset($this->languages[$this->defaultLangcode])) {
274         $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]);
275       }
276     }
277     return $this->languages;
278   }
279
280   /**
281    * {@inheritdoc}
282    */
283   public function postCreate(EntityStorageInterface $storage) {
284     $this->newRevision = TRUE;
285   }
286
287   /**
288    * {@inheritdoc}
289    */
290   public function setNewRevision($value = TRUE) {
291     if (!$this->getEntityType()->hasKey('revision')) {
292       throw new \LogicException("Entity type {$this->getEntityTypeId()} does not support revisions.");
293     }
294
295     if ($value && !$this->newRevision) {
296       // When saving a new revision, set any existing revision ID to NULL so as
297       // to ensure that a new revision will actually be created.
298       $this->set($this->getEntityType()->getKey('revision'), NULL);
299     }
300     elseif (!$value && $this->newRevision) {
301       // If ::setNewRevision(FALSE) is called after ::setNewRevision(TRUE) we
302       // have to restore the loaded revision ID.
303       $this->set($this->getEntityType()->getKey('revision'), $this->getLoadedRevisionId());
304     }
305
306     $this->newRevision = $value;
307   }
308
309   /**
310    * {@inheritdoc}
311    */
312   public function getLoadedRevisionId() {
313     return $this->loadedRevisionId;
314   }
315
316   /**
317    * {@inheritdoc}
318    */
319   public function updateLoadedRevisionId() {
320     $this->loadedRevisionId = $this->getRevisionId() ?: $this->loadedRevisionId;
321     return $this;
322   }
323
324   /**
325    * {@inheritdoc}
326    */
327   public function isNewRevision() {
328     return $this->newRevision || ($this->getEntityType()->hasKey('revision') && !$this->getRevisionId());
329   }
330
331   /**
332    * {@inheritdoc}
333    */
334   public function isDefaultRevision($new_value = NULL) {
335     $return = $this->isDefaultRevision;
336     if (isset($new_value)) {
337       $this->isDefaultRevision = (bool) $new_value;
338     }
339     // New entities should always ensure at least one default revision exists,
340     // creating an entity without a default revision is an invalid state.
341     return $this->isNew() || $return;
342   }
343
344   /**
345    * {@inheritdoc}
346    */
347   public function wasDefaultRevision() {
348     /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
349     $entity_type = $this->getEntityType();
350     if (!$entity_type->isRevisionable()) {
351       return TRUE;
352     }
353
354     $revision_default_key = $entity_type->getRevisionMetadataKey('revision_default');
355     $value = $this->isNew() || $this->get($revision_default_key)->value;
356     return $value;
357   }
358
359   /**
360    * {@inheritdoc}
361    */
362   public function isLatestRevision() {
363     /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
364     $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
365
366     return $this->getLoadedRevisionId() == $storage->getLatestRevisionId($this->id());
367   }
368
369   /**
370    * {@inheritdoc}
371    */
372   public function isLatestTranslationAffectedRevision() {
373     /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
374     $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
375
376     return $this->getLoadedRevisionId() == $storage->getLatestTranslationAffectedRevisionId($this->id(), $this->language()->getId());
377   }
378
379   /**
380    * {@inheritdoc}
381    */
382   public function isRevisionTranslationAffected() {
383     return $this->hasField($this->revisionTranslationAffectedKey) ? $this->get($this->revisionTranslationAffectedKey)->value : TRUE;
384   }
385
386   /**
387    * {@inheritdoc}
388    */
389   public function setRevisionTranslationAffected($affected) {
390     if ($this->hasField($this->revisionTranslationAffectedKey)) {
391       $this->set($this->revisionTranslationAffectedKey, $affected);
392     }
393     return $this;
394   }
395
396   /**
397    * {@inheritdoc}
398    */
399   public function isRevisionTranslationAffectedEnforced() {
400     return !empty($this->enforceRevisionTranslationAffected[$this->activeLangcode]);
401   }
402
403   /**
404    * {@inheritdoc}
405    */
406   public function setRevisionTranslationAffectedEnforced($enforced) {
407     $this->enforceRevisionTranslationAffected[$this->activeLangcode] = $enforced;
408     return $this;
409   }
410
411   /**
412    * {@inheritdoc}
413    */
414   public function isDefaultTranslation() {
415     return $this->activeLangcode === LanguageInterface::LANGCODE_DEFAULT;
416   }
417
418   /**
419    * {@inheritdoc}
420    */
421   public function getRevisionId() {
422     return $this->getEntityKey('revision');
423   }
424
425   /**
426    * {@inheritdoc}
427    */
428   public function isTranslatable() {
429     // Check the bundle is translatable, the entity has a language defined, and
430     // the site has more than one language.
431     $bundles = $this->entityManager()->getBundleInfo($this->entityTypeId);
432     return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual();
433   }
434
435   /**
436    * {@inheritdoc}
437    */
438   public function preSave(EntityStorageInterface $storage) {
439     // An entity requiring validation should not be saved if it has not been
440     // actually validated.
441     if ($this->validationRequired && !$this->validated) {
442       // @todo Make this an assertion in https://www.drupal.org/node/2408013.
443       throw new \LogicException('Entity validation was skipped.');
444     }
445     else {
446       $this->validated = FALSE;
447     }
448
449     parent::preSave($storage);
450   }
451
452   /**
453    * {@inheritdoc}
454    */
455   public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
456   }
457
458   /**
459    * {@inheritdoc}
460    */
461   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
462     parent::postSave($storage, $update);
463
464     // Update the status of all saved translations.
465     $removed = [];
466     foreach ($this->translations as $langcode => &$data) {
467       if ($data['status'] == static::TRANSLATION_REMOVED) {
468         $removed[$langcode] = TRUE;
469       }
470       else {
471         $data['status'] = static::TRANSLATION_EXISTING;
472       }
473     }
474     $this->translations = array_diff_key($this->translations, $removed);
475
476     // Reset the new revision flag.
477     $this->newRevision = FALSE;
478
479     // Reset the enforcement of the revision translation affected flag.
480     $this->enforceRevisionTranslationAffected = [];
481   }
482
483   /**
484    * {@inheritdoc}
485    */
486   public function validate() {
487     $this->validated = TRUE;
488     $violations = $this->getTypedData()->validate();
489     return new EntityConstraintViolationList($this, iterator_to_array($violations));
490   }
491
492   /**
493    * {@inheritdoc}
494    */
495   public function isValidationRequired() {
496     return (bool) $this->validationRequired;
497   }
498
499   /**
500    * {@inheritdoc}
501    */
502   public function setValidationRequired($required) {
503     $this->validationRequired = $required;
504     return $this;
505   }
506
507   /**
508    * Clear entity translation object cache to remove stale references.
509    */
510   protected function clearTranslationCache() {
511     foreach ($this->translations as &$translation) {
512       unset($translation['entity']);
513     }
514   }
515
516   /**
517    * {@inheritdoc}
518    */
519   public function __sleep() {
520     // Get the values of instantiated field objects, only serialize the values.
521     foreach ($this->fields as $name => $fields) {
522       foreach ($fields as $langcode => $field) {
523         $this->values[$name][$langcode] = $field->getValue();
524       }
525     }
526     $this->fields = [];
527     $this->fieldDefinitions = NULL;
528     $this->languages = NULL;
529     $this->clearTranslationCache();
530
531     return parent::__sleep();
532   }
533
534   /**
535    * {@inheritdoc}
536    */
537   public function id() {
538     return $this->getEntityKey('id');
539   }
540
541   /**
542    * {@inheritdoc}
543    */
544   public function bundle() {
545     return $this->getEntityKey('bundle');
546   }
547
548   /**
549    * {@inheritdoc}
550    */
551   public function uuid() {
552     return $this->getEntityKey('uuid');
553   }
554
555   /**
556    * {@inheritdoc}
557    */
558   public function hasField($field_name) {
559     return (bool) $this->getFieldDefinition($field_name);
560   }
561
562   /**
563    * {@inheritdoc}
564    */
565   public function get($field_name) {
566     if (!isset($this->fields[$field_name][$this->activeLangcode])) {
567       return $this->getTranslatedField($field_name, $this->activeLangcode);
568     }
569     return $this->fields[$field_name][$this->activeLangcode];
570   }
571
572   /**
573    * Gets a translated field.
574    *
575    * @return \Drupal\Core\Field\FieldItemListInterface
576    */
577   protected function getTranslatedField($name, $langcode) {
578     if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
579       throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
580     }
581     // Populate $this->fields to speed-up further look-ups and to keep track of
582     // fields objects, possibly holding changes to field values.
583     if (!isset($this->fields[$name][$langcode])) {
584       $definition = $this->getFieldDefinition($name);
585       if (!$definition) {
586         throw new \InvalidArgumentException("Field $name is unknown.");
587       }
588       // Non-translatable fields are always stored with
589       // LanguageInterface::LANGCODE_DEFAULT as key.
590
591       $default = $langcode == LanguageInterface::LANGCODE_DEFAULT;
592       if (!$default && !$definition->isTranslatable()) {
593         if (!isset($this->fields[$name][LanguageInterface::LANGCODE_DEFAULT])) {
594           $this->fields[$name][LanguageInterface::LANGCODE_DEFAULT] = $this->getTranslatedField($name, LanguageInterface::LANGCODE_DEFAULT);
595         }
596         $this->fields[$name][$langcode] = &$this->fields[$name][LanguageInterface::LANGCODE_DEFAULT];
597       }
598       else {
599         $value = NULL;
600         if (isset($this->values[$name][$langcode])) {
601           $value = $this->values[$name][$langcode];
602         }
603         $field = \Drupal::service('plugin.manager.field.field_type')->createFieldItemList($this->getTranslation($langcode), $name, $value);
604         if ($default) {
605           // $this->defaultLangcode might not be set if we are initializing the
606           // default language code cache, in which case there is no valid
607           // langcode to assign.
608           $field_langcode = isset($this->defaultLangcode) ? $this->defaultLangcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
609         }
610         else {
611           $field_langcode = $langcode;
612         }
613         $field->setLangcode($field_langcode);
614         $this->fields[$name][$langcode] = $field;
615       }
616     }
617     return $this->fields[$name][$langcode];
618   }
619
620   /**
621    * {@inheritdoc}
622    */
623   public function set($name, $value, $notify = TRUE) {
624     // Assign the value on the child and overrule notify such that we get
625     // notified to handle changes afterwards. We can ignore notify as there is
626     // no parent to notify anyway.
627     $this->get($name)->setValue($value, TRUE);
628     return $this;
629   }
630
631   /**
632    * {@inheritdoc}
633    */
634   public function getFields($include_computed = TRUE) {
635     $fields = [];
636     foreach ($this->getFieldDefinitions() as $name => $definition) {
637       if ($include_computed || !$definition->isComputed()) {
638         $fields[$name] = $this->get($name);
639       }
640     }
641     return $fields;
642   }
643
644   /**
645    * {@inheritdoc}
646    */
647   public function getTranslatableFields($include_computed = TRUE) {
648     $fields = [];
649     foreach ($this->getFieldDefinitions() as $name => $definition) {
650       if (($include_computed || !$definition->isComputed()) && $definition->isTranslatable()) {
651         $fields[$name] = $this->get($name);
652       }
653     }
654     return $fields;
655   }
656
657   /**
658    * {@inheritdoc}
659    */
660   public function getIterator() {
661     return new \ArrayIterator($this->getFields());
662   }
663
664   /**
665    * {@inheritdoc}
666    */
667   public function getFieldDefinition($name) {
668     if (!isset($this->fieldDefinitions)) {
669       $this->getFieldDefinitions();
670     }
671     if (isset($this->fieldDefinitions[$name])) {
672       return $this->fieldDefinitions[$name];
673     }
674   }
675
676   /**
677    * {@inheritdoc}
678    */
679   public function getFieldDefinitions() {
680     if (!isset($this->fieldDefinitions)) {
681       $this->fieldDefinitions = $this->entityManager()->getFieldDefinitions($this->entityTypeId, $this->bundle());
682     }
683     return $this->fieldDefinitions;
684   }
685
686   /**
687    * {@inheritdoc}
688    */
689   public function toArray() {
690     $values = [];
691     foreach ($this->getFields() as $name => $property) {
692       $values[$name] = $property->getValue();
693     }
694     return $values;
695   }
696
697   /**
698    * {@inheritdoc}
699    */
700   public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
701     if ($operation == 'create') {
702       return $this->entityManager()
703         ->getAccessControlHandler($this->entityTypeId)
704         ->createAccess($this->bundle(), $account, [], $return_as_object);
705     }
706     return $this->entityManager()
707       ->getAccessControlHandler($this->entityTypeId)
708       ->access($this, $operation, $account, $return_as_object);
709   }
710
711   /**
712    * {@inheritdoc}
713    */
714   public function language() {
715     $language = NULL;
716     if ($this->activeLangcode != LanguageInterface::LANGCODE_DEFAULT) {
717       if (!isset($this->languages[$this->activeLangcode])) {
718         $this->getLanguages();
719       }
720       $language = $this->languages[$this->activeLangcode];
721     }
722     else {
723       // @todo Avoid this check by getting the language from the language
724       //   manager directly in https://www.drupal.org/node/2303877.
725       if (!isset($this->languages[$this->defaultLangcode])) {
726         $this->getLanguages();
727       }
728       $language = $this->languages[$this->defaultLangcode];
729     }
730     return $language;
731   }
732
733   /**
734    * Populates the local cache for the default language code.
735    */
736   protected function setDefaultLangcode() {
737     // Get the language code if the property exists.
738     // Try to read the value directly from the list of entity keys which got
739     // initialized in __construct(). This avoids creating a field item object.
740     if (isset($this->translatableEntityKeys['langcode'][$this->activeLangcode])) {
741       $this->defaultLangcode = $this->translatableEntityKeys['langcode'][$this->activeLangcode];
742     }
743     elseif ($this->hasField($this->langcodeKey) && ($item = $this->get($this->langcodeKey)) && isset($item->language)) {
744       $this->defaultLangcode = $item->language->getId();
745       $this->translatableEntityKeys['langcode'][$this->activeLangcode] = $this->defaultLangcode;
746     }
747
748     if (empty($this->defaultLangcode)) {
749       // Make sure we return a proper language object, if the entity has a
750       // langcode field, default to the site's default language.
751       if ($this->hasField($this->langcodeKey)) {
752         $this->defaultLangcode = $this->languageManager()->getDefaultLanguage()->getId();
753       }
754       else {
755         $this->defaultLangcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
756       }
757     }
758
759     // This needs to be initialized manually as it is skipped when instantiating
760     // the language field object to avoid infinite recursion.
761     if (!empty($this->fields[$this->langcodeKey])) {
762       $this->fields[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT]->setLangcode($this->defaultLangcode);
763     }
764   }
765
766   /**
767    * Updates language for already instantiated fields.
768    */
769   protected function updateFieldLangcodes($langcode) {
770     foreach ($this->fields as $name => $items) {
771       if (!empty($items[LanguageInterface::LANGCODE_DEFAULT])) {
772         $items[LanguageInterface::LANGCODE_DEFAULT]->setLangcode($langcode);
773       }
774     }
775   }
776
777   /**
778    * {@inheritdoc}
779    */
780   public function onChange($name) {
781     // Check if the changed name is the value of any entity keys and if any of
782     // those values are currently cached, if so, reset it. Exclude the bundle
783     // from that check, as it ready only and must not change, unsetting it could
784     // lead to recursions.
785     foreach (array_keys($this->getEntityType()->getKeys(), $name, TRUE) as $key) {
786       if ($key != 'bundle') {
787         if (isset($this->entityKeys[$key])) {
788           unset($this->entityKeys[$key]);
789         }
790         elseif (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
791           unset($this->translatableEntityKeys[$key][$this->activeLangcode]);
792         }
793         // If the revision identifier field is being populated with the original
794         // value, we need to make sure the "new revision" flag is reset
795         // accordingly.
796         if ($key === 'revision' && $this->getRevisionId() == $this->getLoadedRevisionId() && !$this->isNew()) {
797           $this->newRevision = FALSE;
798         }
799       }
800     }
801
802     switch ($name) {
803       case $this->langcodeKey:
804         if ($this->isDefaultTranslation()) {
805           // Update the default internal language cache.
806           $this->setDefaultLangcode();
807           if (isset($this->translations[$this->defaultLangcode])) {
808             $message = new FormattableMarkup('A translation already exists for the specified language (@langcode).', ['@langcode' => $this->defaultLangcode]);
809             throw new \InvalidArgumentException($message);
810           }
811           $this->updateFieldLangcodes($this->defaultLangcode);
812         }
813         else {
814           // @todo Allow the translation language to be changed. See
815           //   https://www.drupal.org/node/2443989.
816           $items = $this->get($this->langcodeKey);
817           if ($items->value != $this->activeLangcode) {
818             $items->setValue($this->activeLangcode, FALSE);
819             $message = new FormattableMarkup('The translation language cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
820             throw new \LogicException($message);
821           }
822         }
823         break;
824
825       case $this->defaultLangcodeKey:
826         // @todo Use a standard method to make the default_langcode field
827         //   read-only. See https://www.drupal.org/node/2443991.
828         if (isset($this->values[$this->defaultLangcodeKey]) && $this->get($this->defaultLangcodeKey)->value != $this->isDefaultTranslation()) {
829           $this->get($this->defaultLangcodeKey)->setValue($this->isDefaultTranslation(), FALSE);
830           $message = new FormattableMarkup('The default translation flag cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
831           throw new \LogicException($message);
832         }
833         break;
834
835       case $this->revisionTranslationAffectedKey:
836         // If the revision translation affected flag is being set then enforce
837         // its value.
838         $this->setRevisionTranslationAffectedEnforced(TRUE);
839         break;
840     }
841   }
842
843   /**
844    * {@inheritdoc}
845    */
846   public function getTranslation($langcode) {
847     // Ensure we always use the default language code when dealing with the
848     // original entity language.
849     if ($langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode == $this->defaultLangcode) {
850       $langcode = LanguageInterface::LANGCODE_DEFAULT;
851     }
852
853     // Populate entity translation object cache so it will be available for all
854     // translation objects.
855     if (!isset($this->translations[$this->activeLangcode]['entity'])) {
856       $this->translations[$this->activeLangcode]['entity'] = $this;
857     }
858
859     // If we already have a translation object for the specified language we can
860     // just return it.
861     if (isset($this->translations[$langcode]['entity'])) {
862       $translation = $this->translations[$langcode]['entity'];
863     }
864     // Otherwise if an existing translation language was specified we need to
865     // instantiate the related translation.
866     elseif (isset($this->translations[$langcode])) {
867       $translation = $this->initializeTranslation($langcode);
868       $this->translations[$langcode]['entity'] = $translation;
869     }
870
871     if (empty($translation)) {
872       throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
873     }
874
875     return $translation;
876   }
877
878   /**
879    * {@inheritdoc}
880    */
881   public function getUntranslated() {
882     return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
883   }
884
885   /**
886    * Instantiates a translation object for an existing translation.
887    *
888    * The translated entity will be a clone of the current entity with the
889    * specified $langcode. All translations share the same field data structures
890    * to ensure that all of them deal with fresh data.
891    *
892    * @param string $langcode
893    *   The language code for the requested translation.
894    *
895    * @return \Drupal\Core\Entity\EntityInterface
896    *   The translation object. The content properties of the translation object
897    *   are stored as references to the main entity.
898    */
899   protected function initializeTranslation($langcode) {
900     // If the requested translation is valid, clone it with the current language
901     // as the active language. The $translationInitialize flag triggers a
902     // shallow (non-recursive) clone.
903     $this->translationInitialize = TRUE;
904     $translation = clone $this;
905     $this->translationInitialize = FALSE;
906
907     $translation->activeLangcode = $langcode;
908
909     // Ensure that changes to fields, values and translations are propagated
910     // to all the translation objects.
911     // @todo Consider converting these to ArrayObject.
912     $translation->values = &$this->values;
913     $translation->fields = &$this->fields;
914     $translation->translations = &$this->translations;
915     $translation->enforceIsNew = &$this->enforceIsNew;
916     $translation->newRevision = &$this->newRevision;
917     $translation->entityKeys = &$this->entityKeys;
918     $translation->translatableEntityKeys = &$this->translatableEntityKeys;
919     $translation->translationInitialize = FALSE;
920     $translation->typedData = NULL;
921     $translation->loadedRevisionId = &$this->loadedRevisionId;
922     $translation->isDefaultRevision = &$this->isDefaultRevision;
923     $translation->enforceRevisionTranslationAffected = &$this->enforceRevisionTranslationAffected;
924
925     return $translation;
926   }
927
928   /**
929    * {@inheritdoc}
930    */
931   public function hasTranslation($langcode) {
932     if ($langcode == $this->defaultLangcode) {
933       $langcode = LanguageInterface::LANGCODE_DEFAULT;
934     }
935     return !empty($this->translations[$langcode]['status']);
936   }
937
938   /**
939    * {@inheritdoc}
940    */
941   public function isNewTranslation() {
942     return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED;
943   }
944
945   /**
946    * {@inheritdoc}
947    */
948   public function addTranslation($langcode, array $values = []) {
949     // Make sure we do not attempt to create a translation if an invalid
950     // language is specified or the entity cannot be translated.
951     $this->getLanguages();
952     if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) {
953       throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
954     }
955     if ($this->languages[$this->defaultLangcode]->isLocked()) {
956       throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
957     }
958
959     // Initialize the translation object.
960     /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
961     $storage = $this->entityManager()->getStorage($this->getEntityTypeId());
962     $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
963     return $storage->createTranslation($this, $langcode, $values);
964   }
965
966   /**
967    * {@inheritdoc}
968    */
969   public function removeTranslation($langcode) {
970     if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) {
971       foreach ($this->getFieldDefinitions() as $name => $definition) {
972         if ($definition->isTranslatable()) {
973           unset($this->values[$name][$langcode]);
974           unset($this->fields[$name][$langcode]);
975         }
976       }
977       // If removing a translation which has not been saved yet, then we have
978       // to remove it completely so that ::getTranslationStatus returns the
979       // proper status.
980       if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) {
981         unset($this->translations[$langcode]);
982       }
983       else {
984         if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) {
985           $this->translations[$langcode]['status_existed'] = TRUE;
986         }
987         $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED;
988       }
989     }
990     else {
991       throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed.");
992     }
993   }
994
995   /**
996    * {@inheritdoc}
997    */
998   public function getTranslationStatus($langcode) {
999     if ($langcode == $this->defaultLangcode) {
1000       $langcode = LanguageInterface::LANGCODE_DEFAULT;
1001     }
1002     return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL;
1003   }
1004
1005   /**
1006    * {@inheritdoc}
1007    */
1008   public function getTranslationLanguages($include_default = TRUE) {
1009     $translations = array_filter($this->translations, function ($translation) {
1010       return $translation['status'];
1011     });
1012     unset($translations[LanguageInterface::LANGCODE_DEFAULT]);
1013
1014     if ($include_default) {
1015       $translations[$this->defaultLangcode] = TRUE;
1016     }
1017
1018     // Now load language objects based upon translation langcodes.
1019     return array_intersect_key($this->getLanguages(), $translations);
1020   }
1021
1022   /**
1023    * Updates the original values with the interim changes.
1024    */
1025   public function updateOriginalValues() {
1026     if (!$this->fields) {
1027       return;
1028     }
1029     foreach ($this->getFieldDefinitions() as $name => $definition) {
1030       if (!$definition->isComputed() && !empty($this->fields[$name])) {
1031         foreach ($this->fields[$name] as $langcode => $item) {
1032           $item->filterEmptyItems();
1033           $this->values[$name][$langcode] = $item->getValue();
1034         }
1035       }
1036     }
1037   }
1038
1039   /**
1040    * Implements the magic method for getting object properties.
1041    *
1042    * @todo: A lot of code still uses non-fields (e.g. $entity->content in view
1043    *   builders) by reference. Clean that up.
1044    */
1045   public function &__get($name) {
1046     // If this is an entity field, handle it accordingly. We first check whether
1047     // a field object has been already created. If not, we create one.
1048     if (isset($this->fields[$name][$this->activeLangcode])) {
1049       return $this->fields[$name][$this->activeLangcode];
1050     }
1051     // Inline getFieldDefinition() to speed things up.
1052     if (!isset($this->fieldDefinitions)) {
1053       $this->getFieldDefinitions();
1054     }
1055     if (isset($this->fieldDefinitions[$name])) {
1056       $return = $this->getTranslatedField($name, $this->activeLangcode);
1057       return $return;
1058     }
1059     // Else directly read/write plain values. That way, non-field entity
1060     // properties can always be accessed directly.
1061     if (!isset($this->values[$name])) {
1062       $this->values[$name] = NULL;
1063     }
1064     return $this->values[$name];
1065   }
1066
1067   /**
1068    * Implements the magic method for setting object properties.
1069    *
1070    * Uses default language always.
1071    */
1072   public function __set($name, $value) {
1073     // Inline getFieldDefinition() to speed things up.
1074     if (!isset($this->fieldDefinitions)) {
1075       $this->getFieldDefinitions();
1076     }
1077     // Handle Field API fields.
1078     if (isset($this->fieldDefinitions[$name])) {
1079       // Support setting values via property objects.
1080       if ($value instanceof TypedDataInterface) {
1081         $value = $value->getValue();
1082       }
1083       // If a FieldItemList object already exists, set its value.
1084       if (isset($this->fields[$name][$this->activeLangcode])) {
1085         $this->fields[$name][$this->activeLangcode]->setValue($value);
1086       }
1087       // If not, create one.
1088       else {
1089         $this->getTranslatedField($name, $this->activeLangcode)->setValue($value);
1090       }
1091     }
1092     // The translations array is unset when cloning the entity object, we just
1093     // need to restore it.
1094     elseif ($name == 'translations') {
1095       $this->translations = $value;
1096     }
1097     // Directly write non-field values.
1098     else {
1099       $this->values[$name] = $value;
1100     }
1101   }
1102
1103   /**
1104    * Implements the magic method for isset().
1105    */
1106   public function __isset($name) {
1107     // "Official" Field API fields are always set. For non-field properties,
1108     // check the internal values.
1109     return $this->hasField($name) ? TRUE : isset($this->values[$name]);
1110   }
1111
1112   /**
1113    * Implements the magic method for unset().
1114    */
1115   public function __unset($name) {
1116     // Unsetting a field means emptying it.
1117     if ($this->hasField($name)) {
1118       $this->get($name)->setValue([]);
1119     }
1120     // For non-field properties, unset the internal value.
1121     else {
1122       unset($this->values[$name]);
1123     }
1124   }
1125
1126   /**
1127    * {@inheritdoc}
1128    */
1129   public function createDuplicate() {
1130     if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
1131       throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
1132     }
1133
1134     $duplicate = clone $this;
1135     $entity_type = $this->getEntityType();
1136     if ($entity_type->hasKey('id')) {
1137       $duplicate->{$entity_type->getKey('id')}->value = NULL;
1138     }
1139     $duplicate->enforceIsNew();
1140
1141     // Check if the entity type supports UUIDs and generate a new one if so.
1142     if ($entity_type->hasKey('uuid')) {
1143       $duplicate->{$entity_type->getKey('uuid')}->value = $this->uuidGenerator()->generate();
1144     }
1145
1146     // Check whether the entity type supports revisions and initialize it if so.
1147     if ($entity_type->isRevisionable()) {
1148       $duplicate->{$entity_type->getKey('revision')}->value = NULL;
1149       $duplicate->loadedRevisionId = NULL;
1150     }
1151
1152     return $duplicate;
1153   }
1154
1155   /**
1156    * Magic method: Implements a deep clone.
1157    */
1158   public function __clone() {
1159     // Avoid deep-cloning when we are initializing a translation object, since
1160     // it will represent the same entity, only with a different active language.
1161     if ($this->translationInitialize) {
1162       return;
1163     }
1164
1165     // The translation is a different object, and needs its own TypedData
1166     // adapter object.
1167     $this->typedData = NULL;
1168     $definitions = $this->getFieldDefinitions();
1169
1170     // The translation cache has to be cleared before cloning the fields
1171     // below so that the call to getTranslation() does not re-use the
1172     // translation objects of the old entity but instead creates new
1173     // translation objects from the newly cloned entity. Otherwise the newly
1174     // cloned field item lists would hold references to the old translation
1175     // objects in their $parent property after the call to setContext().
1176     $this->clearTranslationCache();
1177
1178     // Because the new translation objects that are created below are
1179     // themselves created by *cloning* the newly cloned entity we need to
1180     // make sure that the references to property values are properly cloned
1181     // before cloning the fields. Otherwise calling
1182     // $items->getEntity()->isNew(), for example, would return the
1183     // $enforceIsNew value of the old entity.
1184
1185     // Ensure the translations array is actually cloned by overwriting the
1186     // original reference with one pointing to a copy of the array.
1187     $translations = $this->translations;
1188     $this->translations = &$translations;
1189
1190     // Ensure that the following properties are actually cloned by
1191     // overwriting the original references with ones pointing to copies of
1192     // them: enforceIsNew, newRevision, loadedRevisionId, fields, entityKeys,
1193     // translatableEntityKeys, values, isDefaultRevision and
1194     // enforceRevisionTranslationAffected.
1195     $enforce_is_new = $this->enforceIsNew;
1196     $this->enforceIsNew = &$enforce_is_new;
1197
1198     $new_revision = $this->newRevision;
1199     $this->newRevision = &$new_revision;
1200
1201     $original_revision_id = $this->loadedRevisionId;
1202     $this->loadedRevisionId = &$original_revision_id;
1203
1204     $fields = $this->fields;
1205     $this->fields = &$fields;
1206
1207     $entity_keys = $this->entityKeys;
1208     $this->entityKeys = &$entity_keys;
1209
1210     $translatable_entity_keys = $this->translatableEntityKeys;
1211     $this->translatableEntityKeys = &$translatable_entity_keys;
1212
1213     $values = $this->values;
1214     $this->values = &$values;
1215
1216     $default_revision = $this->isDefaultRevision;
1217     $this->isDefaultRevision = &$default_revision;
1218
1219     $is_revision_translation_affected_enforced = $this->enforceRevisionTranslationAffected;
1220     $this->enforceRevisionTranslationAffected = &$is_revision_translation_affected_enforced;
1221
1222     foreach ($this->fields as $name => $fields_by_langcode) {
1223       $this->fields[$name] = [];
1224       // Untranslatable fields may have multiple references for the same field
1225       // object keyed by language. To avoid creating different field objects
1226       // we retain just the original value, as references will be recreated
1227       // later as needed.
1228       if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) {
1229         $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]);
1230       }
1231       foreach ($fields_by_langcode as $langcode => $items) {
1232         $this->fields[$name][$langcode] = clone $items;
1233         $this->fields[$name][$langcode]->setContext($name, $this->getTranslation($langcode)->getTypedData());
1234       }
1235     }
1236   }
1237
1238   /**
1239    * {@inheritdoc}
1240    */
1241   public function label() {
1242     $label = NULL;
1243     $entity_type = $this->getEntityType();
1244     if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
1245       $label = call_user_func($label_callback, $this);
1246     }
1247     elseif (($label_key = $entity_type->getKey('label'))) {
1248       $label = $this->getEntityKey('label');
1249     }
1250     return $label;
1251   }
1252
1253   /**
1254    * {@inheritdoc}
1255    */
1256   public function referencedEntities() {
1257     $referenced_entities = [];
1258
1259     // Gather a list of referenced entities.
1260     foreach ($this->getFields() as $field_items) {
1261       foreach ($field_items as $field_item) {
1262         // Loop over all properties of a field item.
1263         foreach ($field_item->getProperties(TRUE) as $property) {
1264           if ($property instanceof EntityReference && $entity = $property->getValue()) {
1265             $referenced_entities[] = $entity;
1266           }
1267         }
1268       }
1269     }
1270
1271     return $referenced_entities;
1272   }
1273
1274   /**
1275    * Gets the value of the given entity key, if defined.
1276    *
1277    * @param string $key
1278    *   Name of the entity key, for example id, revision or bundle.
1279    *
1280    * @return mixed
1281    *   The value of the entity key, NULL if not defined.
1282    */
1283   protected function getEntityKey($key) {
1284     // If the value is known already, return it.
1285     if (isset($this->entityKeys[$key])) {
1286       return $this->entityKeys[$key];
1287     }
1288     if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
1289       return $this->translatableEntityKeys[$key][$this->activeLangcode];
1290     }
1291
1292     // Otherwise fetch the value by creating a field object.
1293     $value = NULL;
1294     if ($this->getEntityType()->hasKey($key)) {
1295       $field_name = $this->getEntityType()->getKey($key);
1296       $definition = $this->getFieldDefinition($field_name);
1297       $property = $definition->getFieldStorageDefinition()->getMainPropertyName();
1298       $value = $this->get($field_name)->$property;
1299
1300       // Put it in the right array, depending on whether it is translatable.
1301       if ($definition->isTranslatable()) {
1302         $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
1303       }
1304       else {
1305         $this->entityKeys[$key] = $value;
1306       }
1307     }
1308     else {
1309       $this->entityKeys[$key] = $value;
1310     }
1311     return $value;
1312   }
1313
1314   /**
1315    * {@inheritdoc}
1316    */
1317   public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
1318     $fields = [];
1319     if ($entity_type->hasKey('id')) {
1320       $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')
1321         ->setLabel(new TranslatableMarkup('ID'))
1322         ->setReadOnly(TRUE)
1323         ->setSetting('unsigned', TRUE);
1324     }
1325     if ($entity_type->hasKey('uuid')) {
1326       $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')
1327         ->setLabel(new TranslatableMarkup('UUID'))
1328         ->setReadOnly(TRUE);
1329     }
1330     if ($entity_type->hasKey('revision')) {
1331       $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')
1332         ->setLabel(new TranslatableMarkup('Revision ID'))
1333         ->setReadOnly(TRUE)
1334         ->setSetting('unsigned', TRUE);
1335     }
1336     if ($entity_type->hasKey('langcode')) {
1337       $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language')
1338         ->setLabel(new TranslatableMarkup('Language'))
1339         ->setDisplayOptions('view', [
1340           'region' => 'hidden',
1341         ])
1342         ->setDisplayOptions('form', [
1343           'type' => 'language_select',
1344           'weight' => 2,
1345         ]);
1346       if ($entity_type->isRevisionable()) {
1347         $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
1348       }
1349       if ($entity_type->isTranslatable()) {
1350         $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
1351       }
1352     }
1353     if ($entity_type->hasKey('bundle')) {
1354       if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
1355         $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference')
1356           ->setLabel($entity_type->getBundleLabel())
1357           ->setSetting('target_type', $bundle_entity_type_id)
1358           ->setRequired(TRUE)
1359           ->setReadOnly(TRUE);
1360       }
1361       else {
1362         $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')
1363           ->setLabel($entity_type->getBundleLabel())
1364           ->setRequired(TRUE)
1365           ->setReadOnly(TRUE);
1366       }
1367     }
1368
1369     return $fields;
1370   }
1371
1372   /**
1373    * {@inheritdoc}
1374    */
1375   public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
1376     return [];
1377   }
1378
1379   /**
1380    * Returns an array of field names to skip in ::hasTranslationChanges.
1381    *
1382    * @return array
1383    *   An array of field names.
1384    */
1385   protected function getFieldsToSkipFromTranslationChangesCheck() {
1386     $bundle = $this->bundle();
1387     if (!isset(static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle])) {
1388       static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle] = $this->traitGetFieldsToSkipFromTranslationChangesCheck($this);
1389     }
1390     return static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle];
1391   }
1392
1393   /**
1394    * {@inheritdoc}
1395    */
1396   public function hasTranslationChanges() {
1397     if ($this->isNew()) {
1398       return TRUE;
1399     }
1400
1401     // $this->original only exists during save. See
1402     // \Drupal\Core\Entity\EntityStorageBase::save(). If it exists we re-use it
1403     // here for performance reasons.
1404     /** @var \Drupal\Core\Entity\ContentEntityBase $original */
1405     $original = $this->original ? $this->original : NULL;
1406
1407     if (!$original) {
1408       $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id();
1409       $original = $this->entityManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id);
1410     }
1411
1412     // If the current translation has just been added, we have a change.
1413     $translated = count($this->translations) > 1;
1414     if ($translated && !$original->hasTranslation($this->activeLangcode)) {
1415       return TRUE;
1416     }
1417
1418     // Compare field item current values with the original ones to determine
1419     // whether we have changes. If a field is not translatable and the entity is
1420     // translated we skip it because, depending on the use case, it would make
1421     // sense to mark all translations as changed or none of them. We skip also
1422     // computed fields as comparing them with their original values might not be
1423     // possible or be meaningless.
1424     /** @var \Drupal\Core\Entity\ContentEntityBase $translation */
1425     $translation = $original->getTranslation($this->activeLangcode);
1426     $langcode = $this->language()->getId();
1427
1428     // The list of fields to skip from the comparision.
1429     $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck();
1430
1431     // We also check untranslatable fields, so that a change to those will mark
1432     // all translations as affected, unless they are configured to only affect
1433     // the default translation.
1434     $skip_untranslatable_fields = !$this->isDefaultTranslation() && $this->isDefaultTranslationAffectedOnly();
1435
1436     foreach ($this->getFieldDefinitions() as $field_name => $definition) {
1437       // @todo Avoid special-casing the following fields. See
1438       //    https://www.drupal.org/node/2329253.
1439       if (in_array($field_name, $skip_fields, TRUE) || ($skip_untranslatable_fields && !$definition->isTranslatable())) {
1440         continue;
1441       }
1442       $items = $this->get($field_name)->filterEmptyItems();
1443       $original_items = $translation->get($field_name)->filterEmptyItems();
1444       if ($items->hasAffectingChanges($original_items, $langcode)) {
1445         return TRUE;
1446       }
1447     }
1448
1449     return FALSE;
1450   }
1451
1452   /**
1453    * {@inheritdoc}
1454    */
1455   public function isDefaultTranslationAffectedOnly() {
1456     $bundle_name = $this->bundle();
1457     $bundle_info = \Drupal::service('entity_type.bundle.info')
1458       ->getBundleInfo($this->getEntityTypeId());
1459     return !empty($bundle_info[$bundle_name]['untranslatable_fields.default_translation_affected']);
1460   }
1461
1462 }