3 namespace Drupal\Core\Entity;
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;
17 * Implements Entity Field API specific enhancements to the Entity class.
21 abstract class ContentEntityBase extends Entity implements \IteratorAggregate, ContentEntityInterface, TranslationStatusInterface {
24 * The plain data values of the contained fields.
26 * This always holds the original, unchanged values of the entity. The values
27 * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
28 * is used for values in default language.
30 * @todo: Add methods for getting original fields and for determining
32 * @todo: Provide a better way for defining default values.
36 protected $values = [];
39 * The array of fields, each being an instance of FieldItemListInterface.
43 protected $fields = [];
46 * Local cache for field definitions.
48 * @see ContentEntityBase::getFieldDefinitions()
52 protected $fieldDefinitions;
55 * Local cache for the available language objects.
57 * @var \Drupal\Core\Language\LanguageInterface[]
62 * The language entity key.
66 protected $langcodeKey;
69 * The default langcode entity key.
73 protected $defaultLangcodeKey;
76 * Language code identifying the entity active language.
78 * This is the language field accessors will use to determine which field
83 protected $activeLangcode = LanguageInterface::LANGCODE_DEFAULT;
86 * Local cache for the default language code.
90 protected $defaultLangcode;
93 * An array of entity translation metadata.
95 * An associative array keyed by translation language code. Every value is an
96 * array containing the translation status and the translation object, if it has
97 * already been instantiated.
101 protected $translations = [];
104 * A flag indicating whether a translation object is being initialized.
108 protected $translationInitialize = FALSE;
111 * Boolean indicating whether a new revision should be created on save.
115 protected $newRevision = FALSE;
118 * Indicates whether this is the default revision.
122 protected $isDefaultRevision = TRUE;
125 * Holds untranslatable entity keys such as the ID, bundle, and revision ID.
129 protected $entityKeys = [];
132 * Holds translatable entity keys such as the label.
136 protected $translatableEntityKeys = [];
139 * Whether entity validation was performed.
143 protected $validated = FALSE;
146 * Whether entity validation is required before saving the entity.
150 protected $validationRequired = FALSE;
153 * The loaded revision ID before the new revision was set.
157 protected $loadedRevisionId;
162 public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
163 $this->entityTypeId = $entity_type;
164 $this->entityKeys['bundle'] = $bundle ? $bundle : $this->entityTypeId;
165 $this->langcodeKey = $this->getEntityType()->getKey('langcode');
166 $this->defaultLangcodeKey = $this->getEntityType()->getKey('default_langcode');
168 foreach ($values as $key => $value) {
169 // If the key matches an existing property set the value to the property
170 // to set properties like isDefaultRevision.
171 // @todo: Should this be converted somehow?
172 if (property_exists($this, $key) && isset($value[LanguageInterface::LANGCODE_DEFAULT])) {
173 $this->$key = $value[LanguageInterface::LANGCODE_DEFAULT];
177 $this->values = $values;
178 foreach ($this->getEntityType()->getKeys() as $key => $field_name) {
179 if (isset($this->values[$field_name])) {
180 if (is_array($this->values[$field_name])) {
181 // We store untranslatable fields into an entity key without using a
183 if (!$this->getFieldDefinition($field_name)->isTranslatable()) {
184 if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
185 if (is_array($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
186 if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'])) {
187 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'];
191 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT];
196 // We save translatable fields such as the publishing status of a node
197 // into an entity key array keyed by langcode as a performance
198 // optimization, so we don't have to go through TypedData when we
199 // need these values.
200 foreach ($this->values[$field_name] as $langcode => $field_value) {
201 if (is_array($this->values[$field_name][$langcode])) {
202 if (isset($this->values[$field_name][$langcode][0]['value'])) {
203 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode][0]['value'];
207 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode];
215 // Initialize translations. Ensure we have at least an entry for the default
217 // We determine if the entity is new by checking in the entity values for
218 // the presence of the id entity key, as the usage of ::isNew() is not
219 // possible in the constructor.
220 $data = isset($values[$this->getEntityType()->getKey('id')]) ? ['status' => static::TRANSLATION_EXISTING] : ['status' => static::TRANSLATION_CREATED];
221 $this->translations[LanguageInterface::LANGCODE_DEFAULT] = $data;
222 $this->setDefaultLangcode();
224 foreach ($translations as $langcode) {
225 if ($langcode != $this->defaultLangcode && $langcode != LanguageInterface::LANGCODE_DEFAULT) {
226 $this->translations[$langcode] = $data;
230 if ($this->getEntityType()->isRevisionable()) {
231 // Store the loaded revision ID the entity has been loaded with to
232 // keep it safe from changes.
233 $this->updateLoadedRevisionId();
240 protected function getLanguages() {
241 if (empty($this->languages)) {
242 $this->languages = $this->languageManager()->getLanguages(LanguageInterface::STATE_ALL);
243 // If the entity references a language that is not or no longer available,
244 // we return a mock language object to avoid disrupting the consuming
246 if (!isset($this->languages[$this->defaultLangcode])) {
247 $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]);
250 return $this->languages;
256 public function postCreate(EntityStorageInterface $storage) {
257 $this->newRevision = TRUE;
263 public function setNewRevision($value = TRUE) {
264 if (!$this->getEntityType()->hasKey('revision')) {
265 throw new \LogicException("Entity type {$this->getEntityTypeId()} does not support revisions.");
268 if ($value && !$this->newRevision) {
269 // When saving a new revision, set any existing revision ID to NULL so as
270 // to ensure that a new revision will actually be created.
271 $this->set($this->getEntityType()->getKey('revision'), NULL);
273 // Make sure that the flag tracking which translations are affected by the
274 // current revision is reset.
275 foreach ($this->translations as $langcode => $data) {
276 // But skip removed translations.
277 if ($this->hasTranslation($langcode)) {
278 $this->getTranslation($langcode)->setRevisionTranslationAffected(NULL);
283 $this->newRevision = $value;
289 public function getLoadedRevisionId() {
290 return $this->loadedRevisionId;
296 public function updateLoadedRevisionId() {
297 $this->loadedRevisionId = $this->getRevisionId() ?: $this->loadedRevisionId;
304 public function isNewRevision() {
305 return $this->newRevision || ($this->getEntityType()->hasKey('revision') && !$this->getRevisionId());
311 public function isDefaultRevision($new_value = NULL) {
312 $return = $this->isDefaultRevision;
313 if (isset($new_value)) {
314 $this->isDefaultRevision = (bool) $new_value;
316 // New entities should always ensure at least one default revision exists,
317 // creating an entity without a default revision is an invalid state.
318 return $this->isNew() || $return;
324 public function isRevisionTranslationAffected() {
325 $field_name = $this->getEntityType()->getKey('revision_translation_affected');
326 return $this->hasField($field_name) ? $this->get($field_name)->value : TRUE;
332 public function setRevisionTranslationAffected($affected) {
333 $field_name = $this->getEntityType()->getKey('revision_translation_affected');
334 if ($this->hasField($field_name)) {
335 $this->set($field_name, $affected);
343 public function isDefaultTranslation() {
344 return $this->activeLangcode === LanguageInterface::LANGCODE_DEFAULT;
350 public function getRevisionId() {
351 return $this->getEntityKey('revision');
357 public function isTranslatable() {
358 // Check that the bundle is translatable, the entity has a language defined
359 // and if we have more than one language on the site.
360 $bundles = $this->entityManager()->getBundleInfo($this->entityTypeId);
361 return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual();
367 public function preSave(EntityStorageInterface $storage) {
368 // An entity requiring validation should not be saved if it has not been
369 // actually validated.
370 if ($this->validationRequired && !$this->validated) {
371 // @todo Make this an assertion in https://www.drupal.org/node/2408013.
372 throw new \LogicException('Entity validation was skipped.');
375 $this->validated = FALSE;
378 parent::preSave($storage);
384 public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
390 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
391 parent::postSave($storage, $update);
393 // Update the status of all saved translations.
395 foreach ($this->translations as $langcode => &$data) {
396 if ($data['status'] == static::TRANSLATION_REMOVED) {
397 $removed[$langcode] = TRUE;
400 $data['status'] = static::TRANSLATION_EXISTING;
403 $this->translations = array_diff_key($this->translations, $removed);
409 public function validate() {
410 $this->validated = TRUE;
411 $violations = $this->getTypedData()->validate();
412 return new EntityConstraintViolationList($this, iterator_to_array($violations));
418 public function isValidationRequired() {
419 return (bool) $this->validationRequired;
425 public function setValidationRequired($required) {
426 $this->validationRequired = $required;
431 * Clear entity translation object cache to remove stale references.
433 protected function clearTranslationCache() {
434 foreach ($this->translations as &$translation) {
435 unset($translation['entity']);
442 public function __sleep() {
443 // Get the values of instantiated field objects, only serialize the values.
444 foreach ($this->fields as $name => $fields) {
445 foreach ($fields as $langcode => $field) {
446 $this->values[$name][$langcode] = $field->getValue();
450 $this->fieldDefinitions = NULL;
451 $this->languages = NULL;
452 $this->clearTranslationCache();
454 return parent::__sleep();
460 public function id() {
461 return $this->getEntityKey('id');
467 public function bundle() {
468 return $this->getEntityKey('bundle');
474 public function uuid() {
475 return $this->getEntityKey('uuid');
481 public function hasField($field_name) {
482 return (bool) $this->getFieldDefinition($field_name);
488 public function get($field_name) {
489 if (!isset($this->fields[$field_name][$this->activeLangcode])) {
490 return $this->getTranslatedField($field_name, $this->activeLangcode);
492 return $this->fields[$field_name][$this->activeLangcode];
496 * Gets a translated field.
498 * @return \Drupal\Core\Field\FieldItemListInterface
500 protected function getTranslatedField($name, $langcode) {
501 if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
502 throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
504 // Populate $this->fields to speed-up further look-ups and to keep track of
505 // fields objects, possibly holding changes to field values.
506 if (!isset($this->fields[$name][$langcode])) {
507 $definition = $this->getFieldDefinition($name);
509 throw new \InvalidArgumentException("Field $name is unknown.");
511 // Non-translatable fields are always stored with
512 // LanguageInterface::LANGCODE_DEFAULT as key.
514 $default = $langcode == LanguageInterface::LANGCODE_DEFAULT;
515 if (!$default && !$definition->isTranslatable()) {
516 if (!isset($this->fields[$name][LanguageInterface::LANGCODE_DEFAULT])) {
517 $this->fields[$name][LanguageInterface::LANGCODE_DEFAULT] = $this->getTranslatedField($name, LanguageInterface::LANGCODE_DEFAULT);
519 $this->fields[$name][$langcode] = &$this->fields[$name][LanguageInterface::LANGCODE_DEFAULT];
523 if (isset($this->values[$name][$langcode])) {
524 $value = $this->values[$name][$langcode];
526 $field = \Drupal::service('plugin.manager.field.field_type')->createFieldItemList($this->getTranslation($langcode), $name, $value);
528 // $this->defaultLangcode might not be set if we are initializing the
529 // default language code cache, in which case there is no valid
530 // langcode to assign.
531 $field_langcode = isset($this->defaultLangcode) ? $this->defaultLangcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
534 $field_langcode = $langcode;
536 $field->setLangcode($field_langcode);
537 $this->fields[$name][$langcode] = $field;
540 return $this->fields[$name][$langcode];
546 public function set($name, $value, $notify = TRUE) {
547 // Assign the value on the child and overrule notify such that we get
548 // notified to handle changes afterwards. We can ignore notify as there is
549 // no parent to notify anyway.
550 $this->get($name)->setValue($value, TRUE);
557 public function getFields($include_computed = TRUE) {
559 foreach ($this->getFieldDefinitions() as $name => $definition) {
560 if ($include_computed || !$definition->isComputed()) {
561 $fields[$name] = $this->get($name);
570 public function getTranslatableFields($include_computed = TRUE) {
572 foreach ($this->getFieldDefinitions() as $name => $definition) {
573 if (($include_computed || !$definition->isComputed()) && $definition->isTranslatable()) {
574 $fields[$name] = $this->get($name);
583 public function getIterator() {
584 return new \ArrayIterator($this->getFields());
590 public function getFieldDefinition($name) {
591 if (!isset($this->fieldDefinitions)) {
592 $this->getFieldDefinitions();
594 if (isset($this->fieldDefinitions[$name])) {
595 return $this->fieldDefinitions[$name];
602 public function getFieldDefinitions() {
603 if (!isset($this->fieldDefinitions)) {
604 $this->fieldDefinitions = $this->entityManager()->getFieldDefinitions($this->entityTypeId, $this->bundle());
606 return $this->fieldDefinitions;
612 public function toArray() {
614 foreach ($this->getFields() as $name => $property) {
615 $values[$name] = $property->getValue();
623 public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
624 if ($operation == 'create') {
625 return $this->entityManager()
626 ->getAccessControlHandler($this->entityTypeId)
627 ->createAccess($this->bundle(), $account, [], $return_as_object);
629 return $this->entityManager()
630 ->getAccessControlHandler($this->entityTypeId)
631 ->access($this, $operation, $account, $return_as_object);
637 public function language() {
639 if ($this->activeLangcode != LanguageInterface::LANGCODE_DEFAULT) {
640 if (!isset($this->languages[$this->activeLangcode])) {
641 $this->getLanguages();
643 $language = $this->languages[$this->activeLangcode];
646 // @todo Avoid this check by getting the language from the language
647 // manager directly in https://www.drupal.org/node/2303877.
648 if (!isset($this->languages[$this->defaultLangcode])) {
649 $this->getLanguages();
651 $language = $this->languages[$this->defaultLangcode];
657 * Populates the local cache for the default language code.
659 protected function setDefaultLangcode() {
660 // Get the language code if the property exists.
661 // Try to read the value directly from the list of entity keys which got
662 // initialized in __construct(). This avoids creating a field item object.
663 if (isset($this->translatableEntityKeys['langcode'][$this->activeLangcode])) {
664 $this->defaultLangcode = $this->translatableEntityKeys['langcode'][$this->activeLangcode];
666 elseif ($this->hasField($this->langcodeKey) && ($item = $this->get($this->langcodeKey)) && isset($item->language)) {
667 $this->defaultLangcode = $item->language->getId();
668 $this->translatableEntityKeys['langcode'][$this->activeLangcode] = $this->defaultLangcode;
671 if (empty($this->defaultLangcode)) {
672 // Make sure we return a proper language object, if the entity has a
673 // langcode field, default to the site's default language.
674 if ($this->hasField($this->langcodeKey)) {
675 $this->defaultLangcode = $this->languageManager()->getDefaultLanguage()->getId();
678 $this->defaultLangcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
682 // This needs to be initialized manually as it is skipped when instantiating
683 // the language field object to avoid infinite recursion.
684 if (!empty($this->fields[$this->langcodeKey])) {
685 $this->fields[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT]->setLangcode($this->defaultLangcode);
690 * Updates language for already instantiated fields.
692 protected function updateFieldLangcodes($langcode) {
693 foreach ($this->fields as $name => $items) {
694 if (!empty($items[LanguageInterface::LANGCODE_DEFAULT])) {
695 $items[LanguageInterface::LANGCODE_DEFAULT]->setLangcode($langcode);
703 public function onChange($name) {
704 // Check if the changed name is the value of an entity key and if the value
705 // of that is currently cached, if so, reset it. Exclude the bundle from
706 // that check, as it ready only and must not change, unsetting it could
707 // lead to recursions.
708 if ($key = array_search($name, $this->getEntityType()->getKeys())) {
709 if ($key != 'bundle') {
710 if (isset($this->entityKeys[$key])) {
711 unset($this->entityKeys[$key]);
713 elseif (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
714 unset($this->translatableEntityKeys[$key][$this->activeLangcode]);
716 // If the revision identifier field is being populated with the original
717 // value, we need to make sure the "new revision" flag is reset
719 if ($key === 'revision' && $this->getRevisionId() == $this->getLoadedRevisionId()) {
720 $this->newRevision = FALSE;
726 case $this->langcodeKey:
727 if ($this->isDefaultTranslation()) {
728 // Update the default internal language cache.
729 $this->setDefaultLangcode();
730 if (isset($this->translations[$this->defaultLangcode])) {
731 $message = SafeMarkup::format('A translation already exists for the specified language (@langcode).', ['@langcode' => $this->defaultLangcode]);
732 throw new \InvalidArgumentException($message);
734 $this->updateFieldLangcodes($this->defaultLangcode);
737 // @todo Allow the translation language to be changed. See
738 // https://www.drupal.org/node/2443989.
739 $items = $this->get($this->langcodeKey);
740 if ($items->value != $this->activeLangcode) {
741 $items->setValue($this->activeLangcode, FALSE);
742 $message = SafeMarkup::format('The translation language cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
743 throw new \LogicException($message);
748 case $this->defaultLangcodeKey:
749 // @todo Use a standard method to make the default_langcode field
750 // read-only. See https://www.drupal.org/node/2443991.
751 if (isset($this->values[$this->defaultLangcodeKey]) && $this->get($this->defaultLangcodeKey)->value != $this->isDefaultTranslation()) {
752 $this->get($this->defaultLangcodeKey)->setValue($this->isDefaultTranslation(), FALSE);
753 $message = SafeMarkup::format('The default translation flag cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
754 throw new \LogicException($message);
763 public function getTranslation($langcode) {
764 // Ensure we always use the default language code when dealing with the
765 // original entity language.
766 if ($langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode == $this->defaultLangcode) {
767 $langcode = LanguageInterface::LANGCODE_DEFAULT;
770 // Populate entity translation object cache so it will be available for all
771 // translation objects.
772 if ($langcode == $this->activeLangcode) {
773 $this->translations[$langcode]['entity'] = $this;
776 // If we already have a translation object for the specified language we can
778 if (isset($this->translations[$langcode]['entity'])) {
779 $translation = $this->translations[$langcode]['entity'];
781 // Otherwise if an existing translation language was specified we need to
782 // instantiate the related translation.
783 elseif (isset($this->translations[$langcode])) {
784 $translation = $this->initializeTranslation($langcode);
785 $this->translations[$langcode]['entity'] = $translation;
788 if (empty($translation)) {
789 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
798 public function getUntranslated() {
799 return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
803 * Instantiates a translation object for an existing translation.
805 * The translated entity will be a clone of the current entity with the
806 * specified $langcode. All translations share the same field data structures
807 * to ensure that all of them deal with fresh data.
809 * @param string $langcode
810 * The language code for the requested translation.
812 * @return \Drupal\Core\Entity\EntityInterface
813 * The translation object. The content properties of the translation object
814 * are stored as references to the main entity.
816 protected function initializeTranslation($langcode) {
817 // If the requested translation is valid, clone it with the current language
818 // as the active language. The $translationInitialize flag triggers a
819 // shallow (non-recursive) clone.
820 $this->translationInitialize = TRUE;
821 $translation = clone $this;
822 $this->translationInitialize = FALSE;
824 $translation->activeLangcode = $langcode;
826 // Ensure that changes to fields, values and translations are propagated
827 // to all the translation objects.
828 // @todo Consider converting these to ArrayObject.
829 $translation->values = &$this->values;
830 $translation->fields = &$this->fields;
831 $translation->translations = &$this->translations;
832 $translation->enforceIsNew = &$this->enforceIsNew;
833 $translation->newRevision = &$this->newRevision;
834 $translation->entityKeys = &$this->entityKeys;
835 $translation->translatableEntityKeys = &$this->translatableEntityKeys;
836 $translation->translationInitialize = FALSE;
837 $translation->typedData = NULL;
838 $translation->loadedRevisionId = &$this->loadedRevisionId;
839 $translation->isDefaultRevision = &$this->isDefaultRevision;
847 public function hasTranslation($langcode) {
848 if ($langcode == $this->defaultLangcode) {
849 $langcode = LanguageInterface::LANGCODE_DEFAULT;
851 return !empty($this->translations[$langcode]['status']);
857 public function isNewTranslation() {
858 return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED;
864 public function addTranslation($langcode, array $values = []) {
865 // Make sure we do not attempt to create a translation if an invalid
866 // language is specified or the entity cannot be translated.
867 $this->getLanguages();
868 if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) {
869 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
871 if ($this->languages[$this->defaultLangcode]->isLocked()) {
872 throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
875 // Initialize the translation object.
876 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
877 $storage = $this->entityManager()->getStorage($this->getEntityTypeId());
878 $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
879 return $storage->createTranslation($this, $langcode, $values);
885 public function removeTranslation($langcode) {
886 if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) {
887 foreach ($this->getFieldDefinitions() as $name => $definition) {
888 if ($definition->isTranslatable()) {
889 unset($this->values[$name][$langcode]);
890 unset($this->fields[$name][$langcode]);
893 // If removing a translation which has not been saved yet, then we have
894 // to remove it completely so that ::getTranslationStatus returns the
896 if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) {
897 unset($this->translations[$langcode]);
900 if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) {
901 $this->translations[$langcode]['status_existed'] = TRUE;
903 $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED;
907 throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed.");
914 public function getTranslationStatus($langcode) {
915 if ($langcode == $this->defaultLangcode) {
916 $langcode = LanguageInterface::LANGCODE_DEFAULT;
918 return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL;
924 public function getTranslationLanguages($include_default = TRUE) {
925 $translations = array_filter($this->translations, function ($translation) {
926 return $translation['status'];
928 unset($translations[LanguageInterface::LANGCODE_DEFAULT]);
930 if ($include_default) {
931 $translations[$this->defaultLangcode] = TRUE;
934 // Now load language objects based upon translation langcodes.
935 return array_intersect_key($this->getLanguages(), $translations);
939 * Updates the original values with the interim changes.
941 public function updateOriginalValues() {
942 if (!$this->fields) {
945 foreach ($this->getFieldDefinitions() as $name => $definition) {
946 if (!$definition->isComputed() && !empty($this->fields[$name])) {
947 foreach ($this->fields[$name] as $langcode => $item) {
948 $item->filterEmptyItems();
949 $this->values[$name][$langcode] = $item->getValue();
956 * Implements the magic method for getting object properties.
958 * @todo: A lot of code still uses non-fields (e.g. $entity->content in view
959 * builders) by reference. Clean that up.
961 public function &__get($name) {
962 // If this is an entity field, handle it accordingly. We first check whether
963 // a field object has been already created. If not, we create one.
964 if (isset($this->fields[$name][$this->activeLangcode])) {
965 return $this->fields[$name][$this->activeLangcode];
967 // Inline getFieldDefinition() to speed things up.
968 if (!isset($this->fieldDefinitions)) {
969 $this->getFieldDefinitions();
971 if (isset($this->fieldDefinitions[$name])) {
972 $return = $this->getTranslatedField($name, $this->activeLangcode);
975 // Else directly read/write plain values. That way, non-field entity
976 // properties can always be accessed directly.
977 if (!isset($this->values[$name])) {
978 $this->values[$name] = NULL;
980 return $this->values[$name];
984 * Implements the magic method for setting object properties.
986 * Uses default language always.
988 public function __set($name, $value) {
989 // Inline getFieldDefinition() to speed things up.
990 if (!isset($this->fieldDefinitions)) {
991 $this->getFieldDefinitions();
993 // Handle Field API fields.
994 if (isset($this->fieldDefinitions[$name])) {
995 // Support setting values via property objects.
996 if ($value instanceof TypedDataInterface) {
997 $value = $value->getValue();
999 // If a FieldItemList object already exists, set its value.
1000 if (isset($this->fields[$name][$this->activeLangcode])) {
1001 $this->fields[$name][$this->activeLangcode]->setValue($value);
1003 // If not, create one.
1005 $this->getTranslatedField($name, $this->activeLangcode)->setValue($value);
1008 // The translations array is unset when cloning the entity object, we just
1009 // need to restore it.
1010 elseif ($name == 'translations') {
1011 $this->translations = $value;
1013 // Directly write non-field values.
1015 $this->values[$name] = $value;
1020 * Implements the magic method for isset().
1022 public function __isset($name) {
1023 // "Official" Field API fields are always set. For non-field properties,
1024 // check the internal values.
1025 return $this->hasField($name) ? TRUE : isset($this->values[$name]);
1029 * Implements the magic method for unset().
1031 public function __unset($name) {
1032 // Unsetting a field means emptying it.
1033 if ($this->hasField($name)) {
1034 $this->get($name)->setValue([]);
1036 // For non-field properties, unset the internal value.
1038 unset($this->values[$name]);
1045 public function createDuplicate() {
1046 if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
1047 throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
1050 $duplicate = clone $this;
1051 $entity_type = $this->getEntityType();
1052 $duplicate->{$entity_type->getKey('id')}->value = NULL;
1053 $duplicate->enforceIsNew();
1055 // Check if the entity type supports UUIDs and generate a new one if so.
1056 if ($entity_type->hasKey('uuid')) {
1057 $duplicate->{$entity_type->getKey('uuid')}->value = $this->uuidGenerator()->generate();
1060 // Check whether the entity type supports revisions and initialize it if so.
1061 if ($entity_type->isRevisionable()) {
1062 $duplicate->{$entity_type->getKey('revision')}->value = NULL;
1063 $duplicate->loadedRevisionId = NULL;
1070 * Magic method: Implements a deep clone.
1072 public function __clone() {
1073 // Avoid deep-cloning when we are initializing a translation object, since
1074 // it will represent the same entity, only with a different active language.
1075 if ($this->translationInitialize) {
1079 // The translation is a different object, and needs its own TypedData
1081 $this->typedData = NULL;
1082 $definitions = $this->getFieldDefinitions();
1084 // The translation cache has to be cleared before cloning the fields
1085 // below so that the call to getTranslation() does not re-use the
1086 // translation objects of the old entity but instead creates new
1087 // translation objects from the newly cloned entity. Otherwise the newly
1088 // cloned field item lists would hold references to the old translation
1089 // objects in their $parent property after the call to setContext().
1090 $this->clearTranslationCache();
1092 // Because the new translation objects that are created below are
1093 // themselves created by *cloning* the newly cloned entity we need to
1094 // make sure that the references to property values are properly cloned
1095 // before cloning the fields. Otherwise calling
1096 // $items->getEntity()->isNew(), for example, would return the
1097 // $enforceIsNew value of the old entity.
1099 // Ensure the translations array is actually cloned by overwriting the
1100 // original reference with one pointing to a copy of the array.
1101 $translations = $this->translations;
1102 $this->translations = &$translations;
1104 // Ensure that the following properties are actually cloned by
1105 // overwriting the original references with ones pointing to copies of
1106 // them: enforceIsNew, newRevision, loadedRevisionId, fields, entityKeys,
1107 // translatableEntityKeys, values and isDefaultRevision.
1108 $enforce_is_new = $this->enforceIsNew;
1109 $this->enforceIsNew = &$enforce_is_new;
1111 $new_revision = $this->newRevision;
1112 $this->newRevision = &$new_revision;
1114 $original_revision_id = $this->loadedRevisionId;
1115 $this->loadedRevisionId = &$original_revision_id;
1117 $fields = $this->fields;
1118 $this->fields = &$fields;
1120 $entity_keys = $this->entityKeys;
1121 $this->entityKeys = &$entity_keys;
1123 $translatable_entity_keys = $this->translatableEntityKeys;
1124 $this->translatableEntityKeys = &$translatable_entity_keys;
1126 $values = $this->values;
1127 $this->values = &$values;
1129 $default_revision = $this->isDefaultRevision;
1130 $this->isDefaultRevision = &$default_revision;
1132 foreach ($this->fields as $name => $fields_by_langcode) {
1133 $this->fields[$name] = [];
1134 // Untranslatable fields may have multiple references for the same field
1135 // object keyed by language. To avoid creating different field objects
1136 // we retain just the original value, as references will be recreated
1138 if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) {
1139 $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]);
1141 foreach ($fields_by_langcode as $langcode => $items) {
1142 $this->fields[$name][$langcode] = clone $items;
1143 $this->fields[$name][$langcode]->setContext($name, $this->getTranslation($langcode)->getTypedData());
1151 public function label() {
1153 $entity_type = $this->getEntityType();
1154 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
1155 $label = call_user_func($label_callback, $this);
1157 elseif (($label_key = $entity_type->getKey('label'))) {
1158 $label = $this->getEntityKey('label');
1166 public function referencedEntities() {
1167 $referenced_entities = [];
1169 // Gather a list of referenced entities.
1170 foreach ($this->getFields() as $field_items) {
1171 foreach ($field_items as $field_item) {
1172 // Loop over all properties of a field item.
1173 foreach ($field_item->getProperties(TRUE) as $property) {
1174 if ($property instanceof EntityReference && $entity = $property->getValue()) {
1175 $referenced_entities[] = $entity;
1181 return $referenced_entities;
1185 * Gets the value of the given entity key, if defined.
1187 * @param string $key
1188 * Name of the entity key, for example id, revision or bundle.
1191 * The value of the entity key, NULL if not defined.
1193 protected function getEntityKey($key) {
1194 // If the value is known already, return it.
1195 if (isset($this->entityKeys[$key])) {
1196 return $this->entityKeys[$key];
1198 if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
1199 return $this->translatableEntityKeys[$key][$this->activeLangcode];
1202 // Otherwise fetch the value by creating a field object.
1204 if ($this->getEntityType()->hasKey($key)) {
1205 $field_name = $this->getEntityType()->getKey($key);
1206 $definition = $this->getFieldDefinition($field_name);
1207 $property = $definition->getFieldStorageDefinition()->getMainPropertyName();
1208 $value = $this->get($field_name)->$property;
1210 // Put it in the right array, depending on whether it is translatable.
1211 if ($definition->isTranslatable()) {
1212 $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
1215 $this->entityKeys[$key] = $value;
1219 $this->entityKeys[$key] = $value;
1227 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
1229 if ($entity_type->hasKey('id')) {
1230 $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')
1231 ->setLabel(new TranslatableMarkup('ID'))
1233 ->setSetting('unsigned', TRUE);
1235 if ($entity_type->hasKey('uuid')) {
1236 $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')
1237 ->setLabel(new TranslatableMarkup('UUID'))
1238 ->setReadOnly(TRUE);
1240 if ($entity_type->hasKey('revision')) {
1241 $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')
1242 ->setLabel(new TranslatableMarkup('Revision ID'))
1244 ->setSetting('unsigned', TRUE);
1246 if ($entity_type->hasKey('langcode')) {
1247 $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language')
1248 ->setLabel(new TranslatableMarkup('Language'))
1249 ->setDisplayOptions('view', [
1250 'region' => 'hidden',
1252 ->setDisplayOptions('form', [
1253 'type' => 'language_select',
1256 if ($entity_type->isRevisionable()) {
1257 $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
1259 if ($entity_type->isTranslatable()) {
1260 $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
1263 if ($entity_type->hasKey('bundle')) {
1264 if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
1265 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference')
1266 ->setLabel($entity_type->getBundleLabel())
1267 ->setSetting('target_type', $bundle_entity_type_id)
1269 ->setReadOnly(TRUE);
1272 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')
1273 ->setLabel($entity_type->getBundleLabel())
1275 ->setReadOnly(TRUE);
1285 public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
1290 * Returns an array of field names to skip in ::hasTranslationChanges.
1293 * An array of field names.
1295 protected function getFieldsToSkipFromTranslationChangesCheck() {
1296 /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
1297 $entity_type = $this->getEntityType();
1298 // A list of known revision metadata fields which should be skipped from
1301 $entity_type->getKey('revision'),
1302 'revision_translation_affected',
1304 $fields = array_merge($fields, array_values($entity_type->getRevisionMetadataKeys()));
1312 public function hasTranslationChanges() {
1313 if ($this->isNew()) {
1317 // $this->original only exists during save. See
1318 // \Drupal\Core\Entity\EntityStorageBase::save(). If it exists we re-use it
1319 // here for performance reasons.
1320 /** @var \Drupal\Core\Entity\ContentEntityBase $original */
1321 $original = $this->original ? $this->original : NULL;
1324 $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id();
1325 $original = $this->entityManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id);
1328 // If the current translation has just been added, we have a change.
1329 $translated = count($this->translations) > 1;
1330 if ($translated && !$original->hasTranslation($this->activeLangcode)) {
1334 // Compare field item current values with the original ones to determine
1335 // whether we have changes. If a field is not translatable and the entity is
1336 // translated we skip it because, depending on the use case, it would make
1337 // sense to mark all translations as changed or none of them. We skip also
1338 // computed fields as comparing them with their original values might not be
1339 // possible or be meaningless.
1340 /** @var \Drupal\Core\Entity\ContentEntityBase $translation */
1341 $translation = $original->getTranslation($this->activeLangcode);
1343 // The list of fields to skip from the comparision.
1344 $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck();
1346 foreach ($this->getFieldDefinitions() as $field_name => $definition) {
1347 // @todo Avoid special-casing the following fields. See
1348 // https://www.drupal.org/node/2329253.
1349 if (in_array($field_name, $skip_fields, TRUE)) {
1352 $field = $this->get($field_name);
1353 // When saving entities in the user interface, the changed timestamp is
1354 // automatically incremented by ContentEntityForm::submitForm() even if
1355 // nothing was actually changed. Thus, the changed time needs to be
1356 // ignored when determining whether there are any actual changes in the
1358 if (!($field instanceof ChangedFieldItemList) && !$definition->isComputed()) {
1359 $items = $field->filterEmptyItems();
1360 $original_items = $translation->get($field_name)->filterEmptyItems();
1361 if (!$items->equals($original_items)) {