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 {
23 use EntityChangesDetectionTrait {
24 getFieldsToSkipFromTranslationChangesCheck as traitGetFieldsToSkipFromTranslationChangesCheck;
28 * The plain data values of the contained fields.
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.
34 * @todo: Add methods for getting original fields and for determining
36 * @todo: Provide a better way for defining default values.
40 protected $values = [];
43 * The array of fields, each being an instance of FieldItemListInterface.
47 protected $fields = [];
50 * Local cache for field definitions.
52 * @see ContentEntityBase::getFieldDefinitions()
56 protected $fieldDefinitions;
59 * Local cache for the available language objects.
61 * @var \Drupal\Core\Language\LanguageInterface[]
66 * The language entity key.
70 protected $langcodeKey;
73 * The default langcode entity key.
77 protected $defaultLangcodeKey;
80 * Language code identifying the entity active language.
82 * This is the language field accessors will use to determine which field
87 protected $activeLangcode = LanguageInterface::LANGCODE_DEFAULT;
90 * Local cache for the default language code.
94 protected $defaultLangcode;
97 * An array of entity translation metadata.
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.
105 protected $translations = [];
108 * A flag indicating whether a translation object is being initialized.
112 protected $translationInitialize = FALSE;
115 * Boolean indicating whether a new revision should be created on save.
119 protected $newRevision = FALSE;
122 * Indicates whether this is the default revision.
126 protected $isDefaultRevision = TRUE;
129 * Holds untranslatable entity keys such as the ID, bundle, and revision ID.
133 protected $entityKeys = [];
136 * Holds translatable entity keys such as the label.
140 protected $translatableEntityKeys = [];
143 * Whether entity validation was performed.
147 protected $validated = FALSE;
150 * Whether entity validation is required before saving the entity.
154 protected $validationRequired = FALSE;
157 * The loaded revision ID before the new revision was set.
161 protected $loadedRevisionId;
164 * The revision translation affected entity key.
168 protected $revisionTranslationAffectedKey;
171 * Whether the revision translation affected flag has been enforced.
173 * An array, keyed by the translation language code.
177 protected $enforceRevisionTranslationAffected = [];
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');
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];
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
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'];
212 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT];
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'];
228 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode];
236 // Initialize translations. Ensure we have at least an entry for the default
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();
245 foreach ($translations as $langcode) {
246 if ($langcode != $this->defaultLangcode && $langcode != LanguageInterface::LANGCODE_DEFAULT) {
247 $this->translations[$langcode] = $data;
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();
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
267 if (!isset($this->languages[$this->defaultLangcode])) {
268 $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]);
271 return $this->languages;
277 public function postCreate(EntityStorageInterface $storage) {
278 $this->newRevision = TRUE;
284 public function setNewRevision($value = TRUE) {
285 if (!$this->getEntityType()->hasKey('revision')) {
286 throw new \LogicException("Entity type {$this->getEntityTypeId()} does not support revisions.");
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);
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());
300 $this->newRevision = $value;
306 public function getLoadedRevisionId() {
307 return $this->loadedRevisionId;
313 public function updateLoadedRevisionId() {
314 $this->loadedRevisionId = $this->getRevisionId() ?: $this->loadedRevisionId;
321 public function isNewRevision() {
322 return $this->newRevision || ($this->getEntityType()->hasKey('revision') && !$this->getRevisionId());
328 public function isDefaultRevision($new_value = NULL) {
329 $return = $this->isDefaultRevision;
330 if (isset($new_value)) {
331 $this->isDefaultRevision = (bool) $new_value;
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;
341 public function wasDefaultRevision() {
342 /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
343 $entity_type = $this->getEntityType();
344 if (!$entity_type->isRevisionable()) {
348 $revision_default_key = $entity_type->getRevisionMetadataKey('revision_default');
349 $value = $this->isNew() || $this->get($revision_default_key)->value;
356 public function isLatestRevision() {
357 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
358 $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
360 return $this->getLoadedRevisionId() == $storage->getLatestRevisionId($this->id());
366 public function isLatestTranslationAffectedRevision() {
367 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
368 $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
370 return $this->getLoadedRevisionId() == $storage->getLatestTranslationAffectedRevisionId($this->id(), $this->language()->getId());
376 public function isRevisionTranslationAffected() {
377 return $this->hasField($this->revisionTranslationAffectedKey) ? $this->get($this->revisionTranslationAffectedKey)->value : TRUE;
383 public function setRevisionTranslationAffected($affected) {
384 if ($this->hasField($this->revisionTranslationAffectedKey)) {
385 $this->set($this->revisionTranslationAffectedKey, $affected);
393 public function isRevisionTranslationAffectedEnforced() {
394 return !empty($this->enforceRevisionTranslationAffected[$this->activeLangcode]);
400 public function setRevisionTranslationAffectedEnforced($enforced) {
401 $this->enforceRevisionTranslationAffected[$this->activeLangcode] = $enforced;
408 public function isDefaultTranslation() {
409 return $this->activeLangcode === LanguageInterface::LANGCODE_DEFAULT;
415 public function getRevisionId() {
416 return $this->getEntityKey('revision');
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();
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.');
440 $this->validated = FALSE;
443 parent::preSave($storage);
449 public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
455 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
456 parent::postSave($storage, $update);
458 // Update the status of all saved translations.
460 foreach ($this->translations as $langcode => &$data) {
461 if ($data['status'] == static::TRANSLATION_REMOVED) {
462 $removed[$langcode] = TRUE;
465 $data['status'] = static::TRANSLATION_EXISTING;
468 $this->translations = array_diff_key($this->translations, $removed);
470 // Reset the new revision flag.
471 $this->newRevision = FALSE;
473 // Reset the enforcement of the revision translation affected flag.
474 $this->enforceRevisionTranslationAffected = [];
480 public function validate() {
481 $this->validated = TRUE;
482 $violations = $this->getTypedData()->validate();
483 return new EntityConstraintViolationList($this, iterator_to_array($violations));
489 public function isValidationRequired() {
490 return (bool) $this->validationRequired;
496 public function setValidationRequired($required) {
497 $this->validationRequired = $required;
502 * Clear entity translation object cache to remove stale references.
504 protected function clearTranslationCache() {
505 foreach ($this->translations as &$translation) {
506 unset($translation['entity']);
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();
521 $this->fieldDefinitions = NULL;
522 $this->languages = NULL;
523 $this->clearTranslationCache();
525 return parent::__sleep();
531 public function id() {
532 return $this->getEntityKey('id');
538 public function bundle() {
539 return $this->getEntityKey('bundle');
545 public function uuid() {
546 return $this->getEntityKey('uuid');
552 public function hasField($field_name) {
553 return (bool) $this->getFieldDefinition($field_name);
559 public function get($field_name) {
560 if (!isset($this->fields[$field_name][$this->activeLangcode])) {
561 return $this->getTranslatedField($field_name, $this->activeLangcode);
563 return $this->fields[$field_name][$this->activeLangcode];
567 * Gets a translated field.
569 * @return \Drupal\Core\Field\FieldItemListInterface
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.");
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);
580 throw new \InvalidArgumentException("Field $name is unknown.");
582 // Non-translatable fields are always stored with
583 // LanguageInterface::LANGCODE_DEFAULT as key.
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);
590 $this->fields[$name][$langcode] = &$this->fields[$name][LanguageInterface::LANGCODE_DEFAULT];
594 if (isset($this->values[$name][$langcode])) {
595 $value = $this->values[$name][$langcode];
597 $field = \Drupal::service('plugin.manager.field.field_type')->createFieldItemList($this->getTranslation($langcode), $name, $value);
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;
605 $field_langcode = $langcode;
607 $field->setLangcode($field_langcode);
608 $this->fields[$name][$langcode] = $field;
611 return $this->fields[$name][$langcode];
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);
628 public function getFields($include_computed = TRUE) {
630 foreach ($this->getFieldDefinitions() as $name => $definition) {
631 if ($include_computed || !$definition->isComputed()) {
632 $fields[$name] = $this->get($name);
641 public function getTranslatableFields($include_computed = TRUE) {
643 foreach ($this->getFieldDefinitions() as $name => $definition) {
644 if (($include_computed || !$definition->isComputed()) && $definition->isTranslatable()) {
645 $fields[$name] = $this->get($name);
654 public function getIterator() {
655 return new \ArrayIterator($this->getFields());
661 public function getFieldDefinition($name) {
662 if (!isset($this->fieldDefinitions)) {
663 $this->getFieldDefinitions();
665 if (isset($this->fieldDefinitions[$name])) {
666 return $this->fieldDefinitions[$name];
673 public function getFieldDefinitions() {
674 if (!isset($this->fieldDefinitions)) {
675 $this->fieldDefinitions = $this->entityManager()->getFieldDefinitions($this->entityTypeId, $this->bundle());
677 return $this->fieldDefinitions;
683 public function toArray() {
685 foreach ($this->getFields() as $name => $property) {
686 $values[$name] = $property->getValue();
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);
700 return $this->entityManager()
701 ->getAccessControlHandler($this->entityTypeId)
702 ->access($this, $operation, $account, $return_as_object);
708 public function language() {
710 if ($this->activeLangcode != LanguageInterface::LANGCODE_DEFAULT) {
711 if (!isset($this->languages[$this->activeLangcode])) {
712 $this->getLanguages();
714 $language = $this->languages[$this->activeLangcode];
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();
722 $language = $this->languages[$this->defaultLangcode];
728 * Populates the local cache for the default language code.
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];
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;
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();
749 $this->defaultLangcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
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);
761 * Updates language for already instantiated fields.
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);
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]);
784 elseif (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
785 unset($this->translatableEntityKeys[$key][$this->activeLangcode]);
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
790 if ($key === 'revision' && $this->getRevisionId() == $this->getLoadedRevisionId() && !$this->isNew()) {
791 $this->newRevision = FALSE;
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);
805 $this->updateFieldLangcodes($this->defaultLangcode);
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);
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);
829 case $this->revisionTranslationAffectedKey:
830 // If the revision translation affected flag is being set then enforce
832 $this->setRevisionTranslationAffectedEnforced(TRUE);
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;
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;
853 // If we already have a translation object for the specified language we can
855 if (isset($this->translations[$langcode]['entity'])) {
856 $translation = $this->translations[$langcode]['entity'];
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;
865 if (empty($translation)) {
866 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
875 public function getUntranslated() {
876 return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
880 * Instantiates a translation object for an existing translation.
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.
886 * @param string $langcode
887 * The language code for the requested translation.
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.
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;
901 $translation->activeLangcode = $langcode;
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;
925 public function hasTranslation($langcode) {
926 if ($langcode == $this->defaultLangcode) {
927 $langcode = LanguageInterface::LANGCODE_DEFAULT;
929 return !empty($this->translations[$langcode]['status']);
935 public function isNewTranslation() {
936 return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED;
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.");
949 if ($this->languages[$this->defaultLangcode]->isLocked()) {
950 throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
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);
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]);
971 // If removing a translation which has not been saved yet, then we have
972 // to remove it completely so that ::getTranslationStatus returns the
974 if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) {
975 unset($this->translations[$langcode]);
978 if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) {
979 $this->translations[$langcode]['status_existed'] = TRUE;
981 $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED;
985 throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed.");
992 public function getTranslationStatus($langcode) {
993 if ($langcode == $this->defaultLangcode) {
994 $langcode = LanguageInterface::LANGCODE_DEFAULT;
996 return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL;
1002 public function getTranslationLanguages($include_default = TRUE) {
1003 $translations = array_filter($this->translations, function ($translation) {
1004 return $translation['status'];
1006 unset($translations[LanguageInterface::LANGCODE_DEFAULT]);
1008 if ($include_default) {
1009 $translations[$this->defaultLangcode] = TRUE;
1012 // Now load language objects based upon translation langcodes.
1013 return array_intersect_key($this->getLanguages(), $translations);
1017 * Updates the original values with the interim changes.
1019 public function updateOriginalValues() {
1020 if (!$this->fields) {
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();
1034 * Implements the magic method for getting object properties.
1036 * @todo: A lot of code still uses non-fields (e.g. $entity->content in view
1037 * builders) by reference. Clean that up.
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];
1045 // Inline getFieldDefinition() to speed things up.
1046 if (!isset($this->fieldDefinitions)) {
1047 $this->getFieldDefinitions();
1049 if (isset($this->fieldDefinitions[$name])) {
1050 $return = $this->getTranslatedField($name, $this->activeLangcode);
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;
1058 return $this->values[$name];
1062 * Implements the magic method for setting object properties.
1064 * Uses default language always.
1066 public function __set($name, $value) {
1067 // Inline getFieldDefinition() to speed things up.
1068 if (!isset($this->fieldDefinitions)) {
1069 $this->getFieldDefinitions();
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();
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);
1081 // If not, create one.
1083 $this->getTranslatedField($name, $this->activeLangcode)->setValue($value);
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;
1091 // Directly write non-field values.
1093 $this->values[$name] = $value;
1098 * Implements the magic method for isset().
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]);
1107 * Implements the magic method for unset().
1109 public function __unset($name) {
1110 // Unsetting a field means emptying it.
1111 if ($this->hasField($name)) {
1112 $this->get($name)->setValue([]);
1114 // For non-field properties, unset the internal value.
1116 unset($this->values[$name]);
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.");
1128 $duplicate = clone $this;
1129 $entity_type = $this->getEntityType();
1130 if ($entity_type->hasKey('id')) {
1131 $duplicate->{$entity_type->getKey('id')}->value = NULL;
1133 $duplicate->enforceIsNew();
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();
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;
1150 * Magic method: Implements a deep clone.
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) {
1159 // The translation is a different object, and needs its own TypedData
1161 $this->typedData = NULL;
1162 $definitions = $this->getFieldDefinitions();
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();
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.
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;
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;
1192 $new_revision = $this->newRevision;
1193 $this->newRevision = &$new_revision;
1195 $original_revision_id = $this->loadedRevisionId;
1196 $this->loadedRevisionId = &$original_revision_id;
1198 $fields = $this->fields;
1199 $this->fields = &$fields;
1201 $entity_keys = $this->entityKeys;
1202 $this->entityKeys = &$entity_keys;
1204 $translatable_entity_keys = $this->translatableEntityKeys;
1205 $this->translatableEntityKeys = &$translatable_entity_keys;
1207 $values = $this->values;
1208 $this->values = &$values;
1210 $default_revision = $this->isDefaultRevision;
1211 $this->isDefaultRevision = &$default_revision;
1213 $is_revision_translation_affected_enforced = $this->enforceRevisionTranslationAffected;
1214 $this->enforceRevisionTranslationAffected = &$is_revision_translation_affected_enforced;
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
1222 if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) {
1223 $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]);
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());
1235 public function label() {
1237 $entity_type = $this->getEntityType();
1238 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
1239 $label = call_user_func($label_callback, $this);
1241 elseif (($label_key = $entity_type->getKey('label'))) {
1242 $label = $this->getEntityKey('label');
1250 public function referencedEntities() {
1251 $referenced_entities = [];
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;
1265 return $referenced_entities;
1269 * Gets the value of the given entity key, if defined.
1271 * @param string $key
1272 * Name of the entity key, for example id, revision or bundle.
1275 * The value of the entity key, NULL if not defined.
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];
1282 if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
1283 return $this->translatableEntityKeys[$key][$this->activeLangcode];
1286 // Otherwise fetch the value by creating a field object.
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;
1294 // Put it in the right array, depending on whether it is translatable.
1295 if ($definition->isTranslatable()) {
1296 $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
1299 $this->entityKeys[$key] = $value;
1303 $this->entityKeys[$key] = $value;
1311 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
1313 if ($entity_type->hasKey('id')) {
1314 $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')
1315 ->setLabel(new TranslatableMarkup('ID'))
1317 ->setSetting('unsigned', TRUE);
1319 if ($entity_type->hasKey('uuid')) {
1320 $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')
1321 ->setLabel(new TranslatableMarkup('UUID'))
1322 ->setReadOnly(TRUE);
1324 if ($entity_type->hasKey('revision')) {
1325 $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')
1326 ->setLabel(new TranslatableMarkup('Revision ID'))
1328 ->setSetting('unsigned', TRUE);
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',
1336 ->setDisplayOptions('form', [
1337 'type' => 'language_select',
1340 if ($entity_type->isRevisionable()) {
1341 $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
1343 if ($entity_type->isTranslatable()) {
1344 $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
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)
1353 ->setReadOnly(TRUE);
1356 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')
1357 ->setLabel($entity_type->getBundleLabel())
1359 ->setReadOnly(TRUE);
1369 public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
1374 * Returns an array of field names to skip in ::hasTranslationChanges.
1377 * An array of field names.
1379 protected function getFieldsToSkipFromTranslationChangesCheck() {
1380 return $this->traitGetFieldsToSkipFromTranslationChangesCheck($this);
1386 public function hasTranslationChanges() {
1387 if ($this->isNew()) {
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;
1398 $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id();
1399 $original = $this->entityManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id);
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)) {
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);
1417 // The list of fields to skip from the comparision.
1418 $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck();
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();
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())) {
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
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)) {
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']);