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