3 namespace Drupal\Core\Entity;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Entity\Plugin\DataType\EntityReference;
7 use Drupal\Core\Field\BaseFieldDefinition;
8 use Drupal\Core\Language\Language;
9 use Drupal\Core\Language\LanguageInterface;
10 use Drupal\Core\Session\AccountInterface;
11 use Drupal\Core\StringTranslation\TranslatableMarkup;
12 use Drupal\Core\TypedData\TranslationStatusInterface;
13 use Drupal\Core\TypedData\TypedDataInterface;
16 * Implements Entity Field API specific enhancements to the Entity class.
20 abstract class ContentEntityBase extends Entity implements \IteratorAggregate, ContentEntityInterface, TranslationStatusInterface {
22 use EntityChangesDetectionTrait {
23 getFieldsToSkipFromTranslationChangesCheck as traitGetFieldsToSkipFromTranslationChangesCheck;
27 * The plain data values of the contained fields.
29 * This always holds the original, unchanged values of the entity. The values
30 * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
31 * is used for values in default language.
33 * @todo: Add methods for getting original fields and for determining
35 * @todo: Provide a better way for defining default values.
39 protected $values = [];
42 * The array of fields, each being an instance of FieldItemListInterface.
46 protected $fields = [];
49 * Local cache for field definitions.
51 * @see ContentEntityBase::getFieldDefinitions()
55 protected $fieldDefinitions;
58 * Local cache for the available language objects.
60 * @var \Drupal\Core\Language\LanguageInterface[]
65 * The language entity key.
69 protected $langcodeKey;
72 * The default langcode entity key.
76 protected $defaultLangcodeKey;
79 * Language code identifying the entity active language.
81 * This is the language field accessors will use to determine which field
86 protected $activeLangcode = LanguageInterface::LANGCODE_DEFAULT;
89 * Local cache for the default language code.
93 protected $defaultLangcode;
96 * An array of entity translation metadata.
98 * An associative array keyed by translation language code. Every value is an
99 * array containing the translation status and the translation object, if it has
100 * already been instantiated.
104 protected $translations = [];
107 * A flag indicating whether a translation object is being initialized.
111 protected $translationInitialize = FALSE;
114 * Boolean indicating whether a new revision should be created on save.
118 protected $newRevision = FALSE;
121 * Indicates whether this is the default revision.
125 protected $isDefaultRevision = TRUE;
128 * Holds untranslatable entity keys such as the ID, bundle, and revision ID.
132 protected $entityKeys = [];
135 * Holds translatable entity keys such as the label.
139 protected $translatableEntityKeys = [];
142 * Whether entity validation was performed.
146 protected $validated = FALSE;
149 * Whether entity validation is required before saving the entity.
153 protected $validationRequired = FALSE;
156 * The loaded revision ID before the new revision was set.
160 protected $loadedRevisionId;
163 * The revision translation affected entity key.
167 protected $revisionTranslationAffectedKey;
170 * Whether the revision translation affected flag has been enforced.
172 * An array, keyed by the translation language code.
176 protected $enforceRevisionTranslationAffected = [];
179 * Local cache for fields to skip from the checking for translation changes.
183 protected static $fieldsToSkipFromTranslationChangesCheck = [];
188 public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
189 $this->entityTypeId = $entity_type;
190 $this->entityKeys['bundle'] = $bundle ? $bundle : $this->entityTypeId;
191 $this->langcodeKey = $this->getEntityType()->getKey('langcode');
192 $this->defaultLangcodeKey = $this->getEntityType()->getKey('default_langcode');
193 $this->revisionTranslationAffectedKey = $this->getEntityType()->getKey('revision_translation_affected');
195 foreach ($values as $key => $value) {
196 // If the key matches an existing property set the value to the property
197 // to set properties like isDefaultRevision.
198 // @todo: Should this be converted somehow?
199 if (property_exists($this, $key) && isset($value[LanguageInterface::LANGCODE_DEFAULT])) {
200 $this->$key = $value[LanguageInterface::LANGCODE_DEFAULT];
204 $this->values = $values;
205 foreach ($this->getEntityType()->getKeys() as $key => $field_name) {
206 if (isset($this->values[$field_name])) {
207 if (is_array($this->values[$field_name])) {
208 // We store untranslatable fields into an entity key without using a
210 if (!$this->getFieldDefinition($field_name)->isTranslatable()) {
211 if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
212 if (is_array($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
213 if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'])) {
214 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'];
218 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT];
223 // We save translatable fields such as the publishing status of a node
224 // into an entity key array keyed by langcode as a performance
225 // optimization, so we don't have to go through TypedData when we
226 // need these values.
227 foreach ($this->values[$field_name] as $langcode => $field_value) {
228 if (is_array($this->values[$field_name][$langcode])) {
229 if (isset($this->values[$field_name][$langcode][0]['value'])) {
230 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode][0]['value'];
234 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode];
242 // Initialize translations. Ensure we have at least an entry for the default
244 // We determine if the entity is new by checking in the entity values for
245 // the presence of the id entity key, as the usage of ::isNew() is not
246 // possible in the constructor.
247 $data = isset($values[$this->getEntityType()->getKey('id')]) ? ['status' => static::TRANSLATION_EXISTING] : ['status' => static::TRANSLATION_CREATED];
248 $this->translations[LanguageInterface::LANGCODE_DEFAULT] = $data;
249 $this->setDefaultLangcode();
251 foreach ($translations as $langcode) {
252 if ($langcode != $this->defaultLangcode && $langcode != LanguageInterface::LANGCODE_DEFAULT) {
253 $this->translations[$langcode] = $data;
257 if ($this->getEntityType()->isRevisionable()) {
258 // Store the loaded revision ID the entity has been loaded with to
259 // keep it safe from changes.
260 $this->updateLoadedRevisionId();
267 protected function getLanguages() {
268 if (empty($this->languages)) {
269 $this->languages = $this->languageManager()->getLanguages(LanguageInterface::STATE_ALL);
270 // If the entity references a language that is not or no longer available,
271 // we return a mock language object to avoid disrupting the consuming
273 if (!isset($this->languages[$this->defaultLangcode])) {
274 $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]);
277 return $this->languages;
283 public function postCreate(EntityStorageInterface $storage) {
284 $this->newRevision = TRUE;
290 public function setNewRevision($value = TRUE) {
291 if (!$this->getEntityType()->hasKey('revision')) {
292 throw new \LogicException("Entity type {$this->getEntityTypeId()} does not support revisions.");
295 if ($value && !$this->newRevision) {
296 // When saving a new revision, set any existing revision ID to NULL so as
297 // to ensure that a new revision will actually be created.
298 $this->set($this->getEntityType()->getKey('revision'), NULL);
300 elseif (!$value && $this->newRevision) {
301 // If ::setNewRevision(FALSE) is called after ::setNewRevision(TRUE) we
302 // have to restore the loaded revision ID.
303 $this->set($this->getEntityType()->getKey('revision'), $this->getLoadedRevisionId());
306 $this->newRevision = $value;
312 public function getLoadedRevisionId() {
313 return $this->loadedRevisionId;
319 public function updateLoadedRevisionId() {
320 $this->loadedRevisionId = $this->getRevisionId() ?: $this->loadedRevisionId;
327 public function isNewRevision() {
328 return $this->newRevision || ($this->getEntityType()->hasKey('revision') && !$this->getRevisionId());
334 public function isDefaultRevision($new_value = NULL) {
335 $return = $this->isDefaultRevision;
336 if (isset($new_value)) {
337 $this->isDefaultRevision = (bool) $new_value;
339 // New entities should always ensure at least one default revision exists,
340 // creating an entity without a default revision is an invalid state.
341 return $this->isNew() || $return;
347 public function wasDefaultRevision() {
348 /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
349 $entity_type = $this->getEntityType();
350 if (!$entity_type->isRevisionable()) {
354 $revision_default_key = $entity_type->getRevisionMetadataKey('revision_default');
355 $value = $this->isNew() || $this->get($revision_default_key)->value;
362 public function isLatestRevision() {
363 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
364 $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
366 return $this->getLoadedRevisionId() == $storage->getLatestRevisionId($this->id());
372 public function isLatestTranslationAffectedRevision() {
373 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
374 $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
376 return $this->getLoadedRevisionId() == $storage->getLatestTranslationAffectedRevisionId($this->id(), $this->language()->getId());
382 public function isRevisionTranslationAffected() {
383 return $this->hasField($this->revisionTranslationAffectedKey) ? $this->get($this->revisionTranslationAffectedKey)->value : TRUE;
389 public function setRevisionTranslationAffected($affected) {
390 if ($this->hasField($this->revisionTranslationAffectedKey)) {
391 $this->set($this->revisionTranslationAffectedKey, $affected);
399 public function isRevisionTranslationAffectedEnforced() {
400 return !empty($this->enforceRevisionTranslationAffected[$this->activeLangcode]);
406 public function setRevisionTranslationAffectedEnforced($enforced) {
407 $this->enforceRevisionTranslationAffected[$this->activeLangcode] = $enforced;
414 public function isDefaultTranslation() {
415 return $this->activeLangcode === LanguageInterface::LANGCODE_DEFAULT;
421 public function getRevisionId() {
422 return $this->getEntityKey('revision');
428 public function isTranslatable() {
429 // Check the bundle is translatable, the entity has a language defined, and
430 // the site has more than one language.
431 $bundles = $this->entityManager()->getBundleInfo($this->entityTypeId);
432 return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual();
438 public function preSave(EntityStorageInterface $storage) {
439 // An entity requiring validation should not be saved if it has not been
440 // actually validated.
441 if ($this->validationRequired && !$this->validated) {
442 // @todo Make this an assertion in https://www.drupal.org/node/2408013.
443 throw new \LogicException('Entity validation was skipped.');
446 $this->validated = FALSE;
449 parent::preSave($storage);
455 public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
461 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
462 parent::postSave($storage, $update);
464 // Update the status of all saved translations.
466 foreach ($this->translations as $langcode => &$data) {
467 if ($data['status'] == static::TRANSLATION_REMOVED) {
468 $removed[$langcode] = TRUE;
471 $data['status'] = static::TRANSLATION_EXISTING;
474 $this->translations = array_diff_key($this->translations, $removed);
476 // Reset the new revision flag.
477 $this->newRevision = FALSE;
479 // Reset the enforcement of the revision translation affected flag.
480 $this->enforceRevisionTranslationAffected = [];
486 public function validate() {
487 $this->validated = TRUE;
488 $violations = $this->getTypedData()->validate();
489 return new EntityConstraintViolationList($this, iterator_to_array($violations));
495 public function isValidationRequired() {
496 return (bool) $this->validationRequired;
502 public function setValidationRequired($required) {
503 $this->validationRequired = $required;
508 * Clear entity translation object cache to remove stale references.
510 protected function clearTranslationCache() {
511 foreach ($this->translations as &$translation) {
512 unset($translation['entity']);
519 public function __sleep() {
520 // Get the values of instantiated field objects, only serialize the values.
521 foreach ($this->fields as $name => $fields) {
522 foreach ($fields as $langcode => $field) {
523 $this->values[$name][$langcode] = $field->getValue();
527 $this->fieldDefinitions = NULL;
528 $this->languages = NULL;
529 $this->clearTranslationCache();
531 return parent::__sleep();
537 public function id() {
538 return $this->getEntityKey('id');
544 public function bundle() {
545 return $this->getEntityKey('bundle');
551 public function uuid() {
552 return $this->getEntityKey('uuid');
558 public function hasField($field_name) {
559 return (bool) $this->getFieldDefinition($field_name);
565 public function get($field_name) {
566 if (!isset($this->fields[$field_name][$this->activeLangcode])) {
567 return $this->getTranslatedField($field_name, $this->activeLangcode);
569 return $this->fields[$field_name][$this->activeLangcode];
573 * Gets a translated field.
575 * @return \Drupal\Core\Field\FieldItemListInterface
577 protected function getTranslatedField($name, $langcode) {
578 if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
579 throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
581 // Populate $this->fields to speed-up further look-ups and to keep track of
582 // fields objects, possibly holding changes to field values.
583 if (!isset($this->fields[$name][$langcode])) {
584 $definition = $this->getFieldDefinition($name);
586 throw new \InvalidArgumentException("Field $name is unknown.");
588 // Non-translatable fields are always stored with
589 // LanguageInterface::LANGCODE_DEFAULT as key.
591 $default = $langcode == LanguageInterface::LANGCODE_DEFAULT;
592 if (!$default && !$definition->isTranslatable()) {
593 if (!isset($this->fields[$name][LanguageInterface::LANGCODE_DEFAULT])) {
594 $this->fields[$name][LanguageInterface::LANGCODE_DEFAULT] = $this->getTranslatedField($name, LanguageInterface::LANGCODE_DEFAULT);
596 $this->fields[$name][$langcode] = &$this->fields[$name][LanguageInterface::LANGCODE_DEFAULT];
600 if (isset($this->values[$name][$langcode])) {
601 $value = $this->values[$name][$langcode];
603 $field = \Drupal::service('plugin.manager.field.field_type')->createFieldItemList($this->getTranslation($langcode), $name, $value);
605 // $this->defaultLangcode might not be set if we are initializing the
606 // default language code cache, in which case there is no valid
607 // langcode to assign.
608 $field_langcode = isset($this->defaultLangcode) ? $this->defaultLangcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
611 $field_langcode = $langcode;
613 $field->setLangcode($field_langcode);
614 $this->fields[$name][$langcode] = $field;
617 return $this->fields[$name][$langcode];
623 public function set($name, $value, $notify = TRUE) {
624 // Assign the value on the child and overrule notify such that we get
625 // notified to handle changes afterwards. We can ignore notify as there is
626 // no parent to notify anyway.
627 $this->get($name)->setValue($value, TRUE);
634 public function getFields($include_computed = TRUE) {
636 foreach ($this->getFieldDefinitions() as $name => $definition) {
637 if ($include_computed || !$definition->isComputed()) {
638 $fields[$name] = $this->get($name);
647 public function getTranslatableFields($include_computed = TRUE) {
649 foreach ($this->getFieldDefinitions() as $name => $definition) {
650 if (($include_computed || !$definition->isComputed()) && $definition->isTranslatable()) {
651 $fields[$name] = $this->get($name);
660 public function getIterator() {
661 return new \ArrayIterator($this->getFields());
667 public function getFieldDefinition($name) {
668 if (!isset($this->fieldDefinitions)) {
669 $this->getFieldDefinitions();
671 if (isset($this->fieldDefinitions[$name])) {
672 return $this->fieldDefinitions[$name];
679 public function getFieldDefinitions() {
680 if (!isset($this->fieldDefinitions)) {
681 $this->fieldDefinitions = $this->entityManager()->getFieldDefinitions($this->entityTypeId, $this->bundle());
683 return $this->fieldDefinitions;
689 public function toArray() {
691 foreach ($this->getFields() as $name => $property) {
692 $values[$name] = $property->getValue();
700 public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
701 if ($operation == 'create') {
702 return $this->entityManager()
703 ->getAccessControlHandler($this->entityTypeId)
704 ->createAccess($this->bundle(), $account, [], $return_as_object);
706 return $this->entityManager()
707 ->getAccessControlHandler($this->entityTypeId)
708 ->access($this, $operation, $account, $return_as_object);
714 public function language() {
716 if ($this->activeLangcode != LanguageInterface::LANGCODE_DEFAULT) {
717 if (!isset($this->languages[$this->activeLangcode])) {
718 $this->getLanguages();
720 $language = $this->languages[$this->activeLangcode];
723 // @todo Avoid this check by getting the language from the language
724 // manager directly in https://www.drupal.org/node/2303877.
725 if (!isset($this->languages[$this->defaultLangcode])) {
726 $this->getLanguages();
728 $language = $this->languages[$this->defaultLangcode];
734 * Populates the local cache for the default language code.
736 protected function setDefaultLangcode() {
737 // Get the language code if the property exists.
738 // Try to read the value directly from the list of entity keys which got
739 // initialized in __construct(). This avoids creating a field item object.
740 if (isset($this->translatableEntityKeys['langcode'][$this->activeLangcode])) {
741 $this->defaultLangcode = $this->translatableEntityKeys['langcode'][$this->activeLangcode];
743 elseif ($this->hasField($this->langcodeKey) && ($item = $this->get($this->langcodeKey)) && isset($item->language)) {
744 $this->defaultLangcode = $item->language->getId();
745 $this->translatableEntityKeys['langcode'][$this->activeLangcode] = $this->defaultLangcode;
748 if (empty($this->defaultLangcode)) {
749 // Make sure we return a proper language object, if the entity has a
750 // langcode field, default to the site's default language.
751 if ($this->hasField($this->langcodeKey)) {
752 $this->defaultLangcode = $this->languageManager()->getDefaultLanguage()->getId();
755 $this->defaultLangcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
759 // This needs to be initialized manually as it is skipped when instantiating
760 // the language field object to avoid infinite recursion.
761 if (!empty($this->fields[$this->langcodeKey])) {
762 $this->fields[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT]->setLangcode($this->defaultLangcode);
767 * Updates language for already instantiated fields.
769 protected function updateFieldLangcodes($langcode) {
770 foreach ($this->fields as $name => $items) {
771 if (!empty($items[LanguageInterface::LANGCODE_DEFAULT])) {
772 $items[LanguageInterface::LANGCODE_DEFAULT]->setLangcode($langcode);
780 public function onChange($name) {
781 // Check if the changed name is the value of any entity keys and if any of
782 // those values are currently cached, if so, reset it. Exclude the bundle
783 // from that check, as it ready only and must not change, unsetting it could
784 // lead to recursions.
785 foreach (array_keys($this->getEntityType()->getKeys(), $name, TRUE) as $key) {
786 if ($key != 'bundle') {
787 if (isset($this->entityKeys[$key])) {
788 unset($this->entityKeys[$key]);
790 elseif (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
791 unset($this->translatableEntityKeys[$key][$this->activeLangcode]);
793 // If the revision identifier field is being populated with the original
794 // value, we need to make sure the "new revision" flag is reset
796 if ($key === 'revision' && $this->getRevisionId() == $this->getLoadedRevisionId() && !$this->isNew()) {
797 $this->newRevision = FALSE;
803 case $this->langcodeKey:
804 if ($this->isDefaultTranslation()) {
805 // Update the default internal language cache.
806 $this->setDefaultLangcode();
807 if (isset($this->translations[$this->defaultLangcode])) {
808 $message = new FormattableMarkup('A translation already exists for the specified language (@langcode).', ['@langcode' => $this->defaultLangcode]);
809 throw new \InvalidArgumentException($message);
811 $this->updateFieldLangcodes($this->defaultLangcode);
814 // @todo Allow the translation language to be changed. See
815 // https://www.drupal.org/node/2443989.
816 $items = $this->get($this->langcodeKey);
817 if ($items->value != $this->activeLangcode) {
818 $items->setValue($this->activeLangcode, FALSE);
819 $message = new FormattableMarkup('The translation language cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
820 throw new \LogicException($message);
825 case $this->defaultLangcodeKey:
826 // @todo Use a standard method to make the default_langcode field
827 // read-only. See https://www.drupal.org/node/2443991.
828 if (isset($this->values[$this->defaultLangcodeKey]) && $this->get($this->defaultLangcodeKey)->value != $this->isDefaultTranslation()) {
829 $this->get($this->defaultLangcodeKey)->setValue($this->isDefaultTranslation(), FALSE);
830 $message = new FormattableMarkup('The default translation flag cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
831 throw new \LogicException($message);
835 case $this->revisionTranslationAffectedKey:
836 // If the revision translation affected flag is being set then enforce
838 $this->setRevisionTranslationAffectedEnforced(TRUE);
846 public function getTranslation($langcode) {
847 // Ensure we always use the default language code when dealing with the
848 // original entity language.
849 if ($langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode == $this->defaultLangcode) {
850 $langcode = LanguageInterface::LANGCODE_DEFAULT;
853 // Populate entity translation object cache so it will be available for all
854 // translation objects.
855 if (!isset($this->translations[$this->activeLangcode]['entity'])) {
856 $this->translations[$this->activeLangcode]['entity'] = $this;
859 // If we already have a translation object for the specified language we can
861 if (isset($this->translations[$langcode]['entity'])) {
862 $translation = $this->translations[$langcode]['entity'];
864 // Otherwise if an existing translation language was specified we need to
865 // instantiate the related translation.
866 elseif (isset($this->translations[$langcode])) {
867 $translation = $this->initializeTranslation($langcode);
868 $this->translations[$langcode]['entity'] = $translation;
871 if (empty($translation)) {
872 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
881 public function getUntranslated() {
882 return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
886 * Instantiates a translation object for an existing translation.
888 * The translated entity will be a clone of the current entity with the
889 * specified $langcode. All translations share the same field data structures
890 * to ensure that all of them deal with fresh data.
892 * @param string $langcode
893 * The language code for the requested translation.
895 * @return \Drupal\Core\Entity\EntityInterface
896 * The translation object. The content properties of the translation object
897 * are stored as references to the main entity.
899 protected function initializeTranslation($langcode) {
900 // If the requested translation is valid, clone it with the current language
901 // as the active language. The $translationInitialize flag triggers a
902 // shallow (non-recursive) clone.
903 $this->translationInitialize = TRUE;
904 $translation = clone $this;
905 $this->translationInitialize = FALSE;
907 $translation->activeLangcode = $langcode;
909 // Ensure that changes to fields, values and translations are propagated
910 // to all the translation objects.
911 // @todo Consider converting these to ArrayObject.
912 $translation->values = &$this->values;
913 $translation->fields = &$this->fields;
914 $translation->translations = &$this->translations;
915 $translation->enforceIsNew = &$this->enforceIsNew;
916 $translation->newRevision = &$this->newRevision;
917 $translation->entityKeys = &$this->entityKeys;
918 $translation->translatableEntityKeys = &$this->translatableEntityKeys;
919 $translation->translationInitialize = FALSE;
920 $translation->typedData = NULL;
921 $translation->loadedRevisionId = &$this->loadedRevisionId;
922 $translation->isDefaultRevision = &$this->isDefaultRevision;
923 $translation->enforceRevisionTranslationAffected = &$this->enforceRevisionTranslationAffected;
931 public function hasTranslation($langcode) {
932 if ($langcode == $this->defaultLangcode) {
933 $langcode = LanguageInterface::LANGCODE_DEFAULT;
935 return !empty($this->translations[$langcode]['status']);
941 public function isNewTranslation() {
942 return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED;
948 public function addTranslation($langcode, array $values = []) {
949 // Make sure we do not attempt to create a translation if an invalid
950 // language is specified or the entity cannot be translated.
951 $this->getLanguages();
952 if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) {
953 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
955 if ($this->languages[$this->defaultLangcode]->isLocked()) {
956 throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
959 // Initialize the translation object.
960 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
961 $storage = $this->entityManager()->getStorage($this->getEntityTypeId());
962 $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
963 return $storage->createTranslation($this, $langcode, $values);
969 public function removeTranslation($langcode) {
970 if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) {
971 foreach ($this->getFieldDefinitions() as $name => $definition) {
972 if ($definition->isTranslatable()) {
973 unset($this->values[$name][$langcode]);
974 unset($this->fields[$name][$langcode]);
977 // If removing a translation which has not been saved yet, then we have
978 // to remove it completely so that ::getTranslationStatus returns the
980 if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) {
981 unset($this->translations[$langcode]);
984 if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) {
985 $this->translations[$langcode]['status_existed'] = TRUE;
987 $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED;
991 throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed.");
998 public function getTranslationStatus($langcode) {
999 if ($langcode == $this->defaultLangcode) {
1000 $langcode = LanguageInterface::LANGCODE_DEFAULT;
1002 return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL;
1008 public function getTranslationLanguages($include_default = TRUE) {
1009 $translations = array_filter($this->translations, function ($translation) {
1010 return $translation['status'];
1012 unset($translations[LanguageInterface::LANGCODE_DEFAULT]);
1014 if ($include_default) {
1015 $translations[$this->defaultLangcode] = TRUE;
1018 // Now load language objects based upon translation langcodes.
1019 return array_intersect_key($this->getLanguages(), $translations);
1023 * Updates the original values with the interim changes.
1025 public function updateOriginalValues() {
1026 if (!$this->fields) {
1029 foreach ($this->getFieldDefinitions() as $name => $definition) {
1030 if (!$definition->isComputed() && !empty($this->fields[$name])) {
1031 foreach ($this->fields[$name] as $langcode => $item) {
1032 $item->filterEmptyItems();
1033 $this->values[$name][$langcode] = $item->getValue();
1040 * Implements the magic method for getting object properties.
1042 * @todo: A lot of code still uses non-fields (e.g. $entity->content in view
1043 * builders) by reference. Clean that up.
1045 public function &__get($name) {
1046 // If this is an entity field, handle it accordingly. We first check whether
1047 // a field object has been already created. If not, we create one.
1048 if (isset($this->fields[$name][$this->activeLangcode])) {
1049 return $this->fields[$name][$this->activeLangcode];
1051 // Inline getFieldDefinition() to speed things up.
1052 if (!isset($this->fieldDefinitions)) {
1053 $this->getFieldDefinitions();
1055 if (isset($this->fieldDefinitions[$name])) {
1056 $return = $this->getTranslatedField($name, $this->activeLangcode);
1059 // Else directly read/write plain values. That way, non-field entity
1060 // properties can always be accessed directly.
1061 if (!isset($this->values[$name])) {
1062 $this->values[$name] = NULL;
1064 return $this->values[$name];
1068 * Implements the magic method for setting object properties.
1070 * Uses default language always.
1072 public function __set($name, $value) {
1073 // Inline getFieldDefinition() to speed things up.
1074 if (!isset($this->fieldDefinitions)) {
1075 $this->getFieldDefinitions();
1077 // Handle Field API fields.
1078 if (isset($this->fieldDefinitions[$name])) {
1079 // Support setting values via property objects.
1080 if ($value instanceof TypedDataInterface) {
1081 $value = $value->getValue();
1083 // If a FieldItemList object already exists, set its value.
1084 if (isset($this->fields[$name][$this->activeLangcode])) {
1085 $this->fields[$name][$this->activeLangcode]->setValue($value);
1087 // If not, create one.
1089 $this->getTranslatedField($name, $this->activeLangcode)->setValue($value);
1092 // The translations array is unset when cloning the entity object, we just
1093 // need to restore it.
1094 elseif ($name == 'translations') {
1095 $this->translations = $value;
1097 // Directly write non-field values.
1099 $this->values[$name] = $value;
1104 * Implements the magic method for isset().
1106 public function __isset($name) {
1107 // "Official" Field API fields are always set. For non-field properties,
1108 // check the internal values.
1109 return $this->hasField($name) ? TRUE : isset($this->values[$name]);
1113 * Implements the magic method for unset().
1115 public function __unset($name) {
1116 // Unsetting a field means emptying it.
1117 if ($this->hasField($name)) {
1118 $this->get($name)->setValue([]);
1120 // For non-field properties, unset the internal value.
1122 unset($this->values[$name]);
1129 public function createDuplicate() {
1130 if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
1131 throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
1134 $duplicate = clone $this;
1135 $entity_type = $this->getEntityType();
1136 if ($entity_type->hasKey('id')) {
1137 $duplicate->{$entity_type->getKey('id')}->value = NULL;
1139 $duplicate->enforceIsNew();
1141 // Check if the entity type supports UUIDs and generate a new one if so.
1142 if ($entity_type->hasKey('uuid')) {
1143 $duplicate->{$entity_type->getKey('uuid')}->value = $this->uuidGenerator()->generate();
1146 // Check whether the entity type supports revisions and initialize it if so.
1147 if ($entity_type->isRevisionable()) {
1148 $duplicate->{$entity_type->getKey('revision')}->value = NULL;
1149 $duplicate->loadedRevisionId = NULL;
1156 * Magic method: Implements a deep clone.
1158 public function __clone() {
1159 // Avoid deep-cloning when we are initializing a translation object, since
1160 // it will represent the same entity, only with a different active language.
1161 if ($this->translationInitialize) {
1165 // The translation is a different object, and needs its own TypedData
1167 $this->typedData = NULL;
1168 $definitions = $this->getFieldDefinitions();
1170 // The translation cache has to be cleared before cloning the fields
1171 // below so that the call to getTranslation() does not re-use the
1172 // translation objects of the old entity but instead creates new
1173 // translation objects from the newly cloned entity. Otherwise the newly
1174 // cloned field item lists would hold references to the old translation
1175 // objects in their $parent property after the call to setContext().
1176 $this->clearTranslationCache();
1178 // Because the new translation objects that are created below are
1179 // themselves created by *cloning* the newly cloned entity we need to
1180 // make sure that the references to property values are properly cloned
1181 // before cloning the fields. Otherwise calling
1182 // $items->getEntity()->isNew(), for example, would return the
1183 // $enforceIsNew value of the old entity.
1185 // Ensure the translations array is actually cloned by overwriting the
1186 // original reference with one pointing to a copy of the array.
1187 $translations = $this->translations;
1188 $this->translations = &$translations;
1190 // Ensure that the following properties are actually cloned by
1191 // overwriting the original references with ones pointing to copies of
1192 // them: enforceIsNew, newRevision, loadedRevisionId, fields, entityKeys,
1193 // translatableEntityKeys, values, isDefaultRevision and
1194 // enforceRevisionTranslationAffected.
1195 $enforce_is_new = $this->enforceIsNew;
1196 $this->enforceIsNew = &$enforce_is_new;
1198 $new_revision = $this->newRevision;
1199 $this->newRevision = &$new_revision;
1201 $original_revision_id = $this->loadedRevisionId;
1202 $this->loadedRevisionId = &$original_revision_id;
1204 $fields = $this->fields;
1205 $this->fields = &$fields;
1207 $entity_keys = $this->entityKeys;
1208 $this->entityKeys = &$entity_keys;
1210 $translatable_entity_keys = $this->translatableEntityKeys;
1211 $this->translatableEntityKeys = &$translatable_entity_keys;
1213 $values = $this->values;
1214 $this->values = &$values;
1216 $default_revision = $this->isDefaultRevision;
1217 $this->isDefaultRevision = &$default_revision;
1219 $is_revision_translation_affected_enforced = $this->enforceRevisionTranslationAffected;
1220 $this->enforceRevisionTranslationAffected = &$is_revision_translation_affected_enforced;
1222 foreach ($this->fields as $name => $fields_by_langcode) {
1223 $this->fields[$name] = [];
1224 // Untranslatable fields may have multiple references for the same field
1225 // object keyed by language. To avoid creating different field objects
1226 // we retain just the original value, as references will be recreated
1228 if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) {
1229 $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]);
1231 foreach ($fields_by_langcode as $langcode => $items) {
1232 $this->fields[$name][$langcode] = clone $items;
1233 $this->fields[$name][$langcode]->setContext($name, $this->getTranslation($langcode)->getTypedData());
1241 public function label() {
1243 $entity_type = $this->getEntityType();
1244 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
1245 $label = call_user_func($label_callback, $this);
1247 elseif (($label_key = $entity_type->getKey('label'))) {
1248 $label = $this->getEntityKey('label');
1256 public function referencedEntities() {
1257 $referenced_entities = [];
1259 // Gather a list of referenced entities.
1260 foreach ($this->getFields() as $field_items) {
1261 foreach ($field_items as $field_item) {
1262 // Loop over all properties of a field item.
1263 foreach ($field_item->getProperties(TRUE) as $property) {
1264 if ($property instanceof EntityReference && $entity = $property->getValue()) {
1265 $referenced_entities[] = $entity;
1271 return $referenced_entities;
1275 * Gets the value of the given entity key, if defined.
1277 * @param string $key
1278 * Name of the entity key, for example id, revision or bundle.
1281 * The value of the entity key, NULL if not defined.
1283 protected function getEntityKey($key) {
1284 // If the value is known already, return it.
1285 if (isset($this->entityKeys[$key])) {
1286 return $this->entityKeys[$key];
1288 if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
1289 return $this->translatableEntityKeys[$key][$this->activeLangcode];
1292 // Otherwise fetch the value by creating a field object.
1294 if ($this->getEntityType()->hasKey($key)) {
1295 $field_name = $this->getEntityType()->getKey($key);
1296 $definition = $this->getFieldDefinition($field_name);
1297 $property = $definition->getFieldStorageDefinition()->getMainPropertyName();
1298 $value = $this->get($field_name)->$property;
1300 // Put it in the right array, depending on whether it is translatable.
1301 if ($definition->isTranslatable()) {
1302 $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
1305 $this->entityKeys[$key] = $value;
1309 $this->entityKeys[$key] = $value;
1317 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
1319 if ($entity_type->hasKey('id')) {
1320 $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')
1321 ->setLabel(new TranslatableMarkup('ID'))
1323 ->setSetting('unsigned', TRUE);
1325 if ($entity_type->hasKey('uuid')) {
1326 $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')
1327 ->setLabel(new TranslatableMarkup('UUID'))
1328 ->setReadOnly(TRUE);
1330 if ($entity_type->hasKey('revision')) {
1331 $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')
1332 ->setLabel(new TranslatableMarkup('Revision ID'))
1334 ->setSetting('unsigned', TRUE);
1336 if ($entity_type->hasKey('langcode')) {
1337 $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language')
1338 ->setLabel(new TranslatableMarkup('Language'))
1339 ->setDisplayOptions('view', [
1340 'region' => 'hidden',
1342 ->setDisplayOptions('form', [
1343 'type' => 'language_select',
1346 if ($entity_type->isRevisionable()) {
1347 $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
1349 if ($entity_type->isTranslatable()) {
1350 $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
1353 if ($entity_type->hasKey('bundle')) {
1354 if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
1355 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference')
1356 ->setLabel($entity_type->getBundleLabel())
1357 ->setSetting('target_type', $bundle_entity_type_id)
1359 ->setReadOnly(TRUE);
1362 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')
1363 ->setLabel($entity_type->getBundleLabel())
1365 ->setReadOnly(TRUE);
1375 public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
1380 * Returns an array of field names to skip in ::hasTranslationChanges.
1383 * An array of field names.
1385 protected function getFieldsToSkipFromTranslationChangesCheck() {
1386 $bundle = $this->bundle();
1387 if (!isset(static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle])) {
1388 static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle] = $this->traitGetFieldsToSkipFromTranslationChangesCheck($this);
1390 return static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle];
1396 public function hasTranslationChanges() {
1397 if ($this->isNew()) {
1401 // $this->original only exists during save. See
1402 // \Drupal\Core\Entity\EntityStorageBase::save(). If it exists we re-use it
1403 // here for performance reasons.
1404 /** @var \Drupal\Core\Entity\ContentEntityBase $original */
1405 $original = $this->original ? $this->original : NULL;
1408 $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id();
1409 $original = $this->entityManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id);
1412 // If the current translation has just been added, we have a change.
1413 $translated = count($this->translations) > 1;
1414 if ($translated && !$original->hasTranslation($this->activeLangcode)) {
1418 // Compare field item current values with the original ones to determine
1419 // whether we have changes. If a field is not translatable and the entity is
1420 // translated we skip it because, depending on the use case, it would make
1421 // sense to mark all translations as changed or none of them. We skip also
1422 // computed fields as comparing them with their original values might not be
1423 // possible or be meaningless.
1424 /** @var \Drupal\Core\Entity\ContentEntityBase $translation */
1425 $translation = $original->getTranslation($this->activeLangcode);
1426 $langcode = $this->language()->getId();
1428 // The list of fields to skip from the comparision.
1429 $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck();
1431 // We also check untranslatable fields, so that a change to those will mark
1432 // all translations as affected, unless they are configured to only affect
1433 // the default translation.
1434 $skip_untranslatable_fields = !$this->isDefaultTranslation() && $this->isDefaultTranslationAffectedOnly();
1436 foreach ($this->getFieldDefinitions() as $field_name => $definition) {
1437 // @todo Avoid special-casing the following fields. See
1438 // https://www.drupal.org/node/2329253.
1439 if (in_array($field_name, $skip_fields, TRUE) || ($skip_untranslatable_fields && !$definition->isTranslatable())) {
1442 $items = $this->get($field_name)->filterEmptyItems();
1443 $original_items = $translation->get($field_name)->filterEmptyItems();
1444 if ($items->hasAffectingChanges($original_items, $langcode)) {
1455 public function isDefaultTranslationAffectedOnly() {
1456 $bundle_name = $this->bundle();
1457 $bundle_info = \Drupal::service('entity_type.bundle.info')
1458 ->getBundleInfo($this->getEntityTypeId());
1459 return !empty($bundle_info[$bundle_name]['untranslatable_fields.default_translation_affected']);