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 = 'revision_translation_affected';
326 return $this->hasField($field_name) ? $this->get($field_name)->value : TRUE;
332 public function setRevisionTranslationAffected($affected) {
333 $field_name = '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]);
720 case $this->langcodeKey:
721 if ($this->isDefaultTranslation()) {
722 // Update the default internal language cache.
723 $this->setDefaultLangcode();
724 if (isset($this->translations[$this->defaultLangcode])) {
725 $message = SafeMarkup::format('A translation already exists for the specified language (@langcode).', ['@langcode' => $this->defaultLangcode]);
726 throw new \InvalidArgumentException($message);
728 $this->updateFieldLangcodes($this->defaultLangcode);
731 // @todo Allow the translation language to be changed. See
732 // https://www.drupal.org/node/2443989.
733 $items = $this->get($this->langcodeKey);
734 if ($items->value != $this->activeLangcode) {
735 $items->setValue($this->activeLangcode, FALSE);
736 $message = SafeMarkup::format('The translation language cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
737 throw new \LogicException($message);
742 case $this->defaultLangcodeKey:
743 // @todo Use a standard method to make the default_langcode field
744 // read-only. See https://www.drupal.org/node/2443991.
745 if (isset($this->values[$this->defaultLangcodeKey]) && $this->get($this->defaultLangcodeKey)->value != $this->isDefaultTranslation()) {
746 $this->get($this->defaultLangcodeKey)->setValue($this->isDefaultTranslation(), FALSE);
747 $message = SafeMarkup::format('The default translation flag cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
748 throw new \LogicException($message);
757 public function getTranslation($langcode) {
758 // Ensure we always use the default language code when dealing with the
759 // original entity language.
760 if ($langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode == $this->defaultLangcode) {
761 $langcode = LanguageInterface::LANGCODE_DEFAULT;
764 // Populate entity translation object cache so it will be available for all
765 // translation objects.
766 if ($langcode == $this->activeLangcode) {
767 $this->translations[$langcode]['entity'] = $this;
770 // If we already have a translation object for the specified language we can
772 if (isset($this->translations[$langcode]['entity'])) {
773 $translation = $this->translations[$langcode]['entity'];
775 // Otherwise if an existing translation language was specified we need to
776 // instantiate the related translation.
777 elseif (isset($this->translations[$langcode])) {
778 $translation = $this->initializeTranslation($langcode);
779 $this->translations[$langcode]['entity'] = $translation;
782 if (empty($translation)) {
783 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
792 public function getUntranslated() {
793 return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
797 * Instantiates a translation object for an existing translation.
799 * The translated entity will be a clone of the current entity with the
800 * specified $langcode. All translations share the same field data structures
801 * to ensure that all of them deal with fresh data.
803 * @param string $langcode
804 * The language code for the requested translation.
806 * @return \Drupal\Core\Entity\EntityInterface
807 * The translation object. The content properties of the translation object
808 * are stored as references to the main entity.
810 protected function initializeTranslation($langcode) {
811 // If the requested translation is valid, clone it with the current language
812 // as the active language. The $translationInitialize flag triggers a
813 // shallow (non-recursive) clone.
814 $this->translationInitialize = TRUE;
815 $translation = clone $this;
816 $this->translationInitialize = FALSE;
818 $translation->activeLangcode = $langcode;
820 // Ensure that changes to fields, values and translations are propagated
821 // to all the translation objects.
822 // @todo Consider converting these to ArrayObject.
823 $translation->values = &$this->values;
824 $translation->fields = &$this->fields;
825 $translation->translations = &$this->translations;
826 $translation->enforceIsNew = &$this->enforceIsNew;
827 $translation->newRevision = &$this->newRevision;
828 $translation->entityKeys = &$this->entityKeys;
829 $translation->translatableEntityKeys = &$this->translatableEntityKeys;
830 $translation->translationInitialize = FALSE;
831 $translation->typedData = NULL;
832 $translation->loadedRevisionId = &$this->loadedRevisionId;
833 $translation->isDefaultRevision = &$this->isDefaultRevision;
841 public function hasTranslation($langcode) {
842 if ($langcode == $this->defaultLangcode) {
843 $langcode = LanguageInterface::LANGCODE_DEFAULT;
845 return !empty($this->translations[$langcode]['status']);
851 public function isNewTranslation() {
852 return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED;
858 public function addTranslation($langcode, array $values = []) {
859 // Make sure we do not attempt to create a translation if an invalid
860 // language is specified or the entity cannot be translated.
861 $this->getLanguages();
862 if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) {
863 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
865 if ($this->languages[$this->defaultLangcode]->isLocked()) {
866 throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
869 // Initialize the translation object.
870 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
871 $storage = $this->entityManager()->getStorage($this->getEntityTypeId());
872 $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
873 return $storage->createTranslation($this, $langcode, $values);
879 public function removeTranslation($langcode) {
880 if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) {
881 foreach ($this->getFieldDefinitions() as $name => $definition) {
882 if ($definition->isTranslatable()) {
883 unset($this->values[$name][$langcode]);
884 unset($this->fields[$name][$langcode]);
887 // If removing a translation which has not been saved yet, then we have
888 // to remove it completely so that ::getTranslationStatus returns the
890 if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) {
891 unset($this->translations[$langcode]);
894 if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) {
895 $this->translations[$langcode]['status_existed'] = TRUE;
897 $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED;
901 throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed.");
908 public function getTranslationStatus($langcode) {
909 if ($langcode == $this->defaultLangcode) {
910 $langcode = LanguageInterface::LANGCODE_DEFAULT;
912 return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL;
918 public function getTranslationLanguages($include_default = TRUE) {
919 $translations = array_filter($this->translations, function($translation) { return $translation['status']; });
920 unset($translations[LanguageInterface::LANGCODE_DEFAULT]);
922 if ($include_default) {
923 $translations[$this->defaultLangcode] = TRUE;
926 // Now load language objects based upon translation langcodes.
927 return array_intersect_key($this->getLanguages(), $translations);
931 * Updates the original values with the interim changes.
933 public function updateOriginalValues() {
934 if (!$this->fields) {
937 foreach ($this->getFieldDefinitions() as $name => $definition) {
938 if (!$definition->isComputed() && !empty($this->fields[$name])) {
939 foreach ($this->fields[$name] as $langcode => $item) {
940 $item->filterEmptyItems();
941 $this->values[$name][$langcode] = $item->getValue();
948 * Implements the magic method for getting object properties.
950 * @todo: A lot of code still uses non-fields (e.g. $entity->content in view
951 * builders) by reference. Clean that up.
953 public function &__get($name) {
954 // If this is an entity field, handle it accordingly. We first check whether
955 // a field object has been already created. If not, we create one.
956 if (isset($this->fields[$name][$this->activeLangcode])) {
957 return $this->fields[$name][$this->activeLangcode];
959 // Inline getFieldDefinition() to speed things up.
960 if (!isset($this->fieldDefinitions)) {
961 $this->getFieldDefinitions();
963 if (isset($this->fieldDefinitions[$name])) {
964 $return = $this->getTranslatedField($name, $this->activeLangcode);
967 // Else directly read/write plain values. That way, non-field entity
968 // properties can always be accessed directly.
969 if (!isset($this->values[$name])) {
970 $this->values[$name] = NULL;
972 return $this->values[$name];
976 * Implements the magic method for setting object properties.
978 * Uses default language always.
980 public function __set($name, $value) {
981 // Inline getFieldDefinition() to speed things up.
982 if (!isset($this->fieldDefinitions)) {
983 $this->getFieldDefinitions();
985 // Handle Field API fields.
986 if (isset($this->fieldDefinitions[$name])) {
987 // Support setting values via property objects.
988 if ($value instanceof TypedDataInterface) {
989 $value = $value->getValue();
991 // If a FieldItemList object already exists, set its value.
992 if (isset($this->fields[$name][$this->activeLangcode])) {
993 $this->fields[$name][$this->activeLangcode]->setValue($value);
995 // If not, create one.
997 $this->getTranslatedField($name, $this->activeLangcode)->setValue($value);
1000 // The translations array is unset when cloning the entity object, we just
1001 // need to restore it.
1002 elseif ($name == 'translations') {
1003 $this->translations = $value;
1005 // Directly write non-field values.
1007 $this->values[$name] = $value;
1012 * Implements the magic method for isset().
1014 public function __isset($name) {
1015 // "Official" Field API fields are always set. For non-field properties,
1016 // check the internal values.
1017 return $this->hasField($name) ? TRUE : isset($this->values[$name]);
1021 * Implements the magic method for unset().
1023 public function __unset($name) {
1024 // Unsetting a field means emptying it.
1025 if ($this->hasField($name)) {
1026 $this->get($name)->setValue([]);
1028 // For non-field properties, unset the internal value.
1030 unset($this->values[$name]);
1037 public function createDuplicate() {
1038 if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
1039 throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
1042 $duplicate = clone $this;
1043 $entity_type = $this->getEntityType();
1044 $duplicate->{$entity_type->getKey('id')}->value = NULL;
1045 $duplicate->enforceIsNew();
1047 // Check if the entity type supports UUIDs and generate a new one if so.
1048 if ($entity_type->hasKey('uuid')) {
1049 $duplicate->{$entity_type->getKey('uuid')}->value = $this->uuidGenerator()->generate();
1052 // Check whether the entity type supports revisions and initialize it if so.
1053 if ($entity_type->isRevisionable()) {
1054 $duplicate->{$entity_type->getKey('revision')}->value = NULL;
1055 $duplicate->loadedRevisionId = NULL;
1062 * Magic method: Implements a deep clone.
1064 public function __clone() {
1065 // Avoid deep-cloning when we are initializing a translation object, since
1066 // it will represent the same entity, only with a different active language.
1067 if ($this->translationInitialize) {
1071 // The translation is a different object, and needs its own TypedData
1073 $this->typedData = NULL;
1074 $definitions = $this->getFieldDefinitions();
1076 // The translation cache has to be cleared before cloning the fields
1077 // below so that the call to getTranslation() does not re-use the
1078 // translation objects of the old entity but instead creates new
1079 // translation objects from the newly cloned entity. Otherwise the newly
1080 // cloned field item lists would hold references to the old translation
1081 // objects in their $parent property after the call to setContext().
1082 $this->clearTranslationCache();
1084 // Because the new translation objects that are created below are
1085 // themselves created by *cloning* the newly cloned entity we need to
1086 // make sure that the references to property values are properly cloned
1087 // before cloning the fields. Otherwise calling
1088 // $items->getEntity()->isNew(), for example, would return the
1089 // $enforceIsNew value of the old entity.
1091 // Ensure the translations array is actually cloned by overwriting the
1092 // original reference with one pointing to a copy of the array.
1093 $translations = $this->translations;
1094 $this->translations = &$translations;
1096 // Ensure that the following properties are actually cloned by
1097 // overwriting the original references with ones pointing to copies of
1098 // them: enforceIsNew, newRevision, loadedRevisionId, fields, entityKeys,
1099 // translatableEntityKeys, values and isDefaultRevision.
1100 $enforce_is_new = $this->enforceIsNew;
1101 $this->enforceIsNew = &$enforce_is_new;
1103 $new_revision = $this->newRevision;
1104 $this->newRevision = &$new_revision;
1106 $original_revision_id = $this->loadedRevisionId;
1107 $this->loadedRevisionId = &$original_revision_id;
1109 $fields = $this->fields;
1110 $this->fields = &$fields;
1112 $entity_keys = $this->entityKeys;
1113 $this->entityKeys = &$entity_keys;
1115 $translatable_entity_keys = $this->translatableEntityKeys;
1116 $this->translatableEntityKeys = &$translatable_entity_keys;
1118 $values = $this->values;
1119 $this->values = &$values;
1121 $default_revision = $this->isDefaultRevision;
1122 $this->isDefaultRevision = &$default_revision;
1124 foreach ($this->fields as $name => $fields_by_langcode) {
1125 $this->fields[$name] = [];
1126 // Untranslatable fields may have multiple references for the same field
1127 // object keyed by language. To avoid creating different field objects
1128 // we retain just the original value, as references will be recreated
1130 if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) {
1131 $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]);
1133 foreach ($fields_by_langcode as $langcode => $items) {
1134 $this->fields[$name][$langcode] = clone $items;
1135 $this->fields[$name][$langcode]->setContext($name, $this->getTranslation($langcode)->getTypedData());
1143 public function label() {
1145 $entity_type = $this->getEntityType();
1146 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
1147 $label = call_user_func($label_callback, $this);
1149 elseif (($label_key = $entity_type->getKey('label'))) {
1150 $label = $this->getEntityKey('label');
1158 public function referencedEntities() {
1159 $referenced_entities = [];
1161 // Gather a list of referenced entities.
1162 foreach ($this->getFields() as $field_items) {
1163 foreach ($field_items as $field_item) {
1164 // Loop over all properties of a field item.
1165 foreach ($field_item->getProperties(TRUE) as $property) {
1166 if ($property instanceof EntityReference && $entity = $property->getValue()) {
1167 $referenced_entities[] = $entity;
1173 return $referenced_entities;
1177 * Gets the value of the given entity key, if defined.
1179 * @param string $key
1180 * Name of the entity key, for example id, revision or bundle.
1183 * The value of the entity key, NULL if not defined.
1185 protected function getEntityKey($key) {
1186 // If the value is known already, return it.
1187 if (isset($this->entityKeys[$key])) {
1188 return $this->entityKeys[$key];
1190 if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
1191 return $this->translatableEntityKeys[$key][$this->activeLangcode];
1194 // Otherwise fetch the value by creating a field object.
1196 if ($this->getEntityType()->hasKey($key)) {
1197 $field_name = $this->getEntityType()->getKey($key);
1198 $definition = $this->getFieldDefinition($field_name);
1199 $property = $definition->getFieldStorageDefinition()->getMainPropertyName();
1200 $value = $this->get($field_name)->$property;
1202 // Put it in the right array, depending on whether it is translatable.
1203 if ($definition->isTranslatable()) {
1204 $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
1207 $this->entityKeys[$key] = $value;
1211 $this->entityKeys[$key] = $value;
1219 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
1221 if ($entity_type->hasKey('id')) {
1222 $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')
1223 ->setLabel(new TranslatableMarkup('ID'))
1225 ->setSetting('unsigned', TRUE);
1227 if ($entity_type->hasKey('uuid')) {
1228 $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')
1229 ->setLabel(new TranslatableMarkup('UUID'))
1230 ->setReadOnly(TRUE);
1232 if ($entity_type->hasKey('revision')) {
1233 $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')
1234 ->setLabel(new TranslatableMarkup('Revision ID'))
1236 ->setSetting('unsigned', TRUE);
1238 if ($entity_type->hasKey('langcode')) {
1239 $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language')
1240 ->setLabel(new TranslatableMarkup('Language'))
1241 ->setDisplayOptions('view', [
1242 'region' => 'hidden',
1244 ->setDisplayOptions('form', [
1245 'type' => 'language_select',
1248 if ($entity_type->isRevisionable()) {
1249 $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
1251 if ($entity_type->isTranslatable()) {
1252 $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
1255 if ($entity_type->hasKey('bundle')) {
1256 if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
1257 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference')
1258 ->setLabel($entity_type->getBundleLabel())
1259 ->setSetting('target_type', $bundle_entity_type_id)
1261 ->setReadOnly(TRUE);
1264 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')
1265 ->setLabel($entity_type->getBundleLabel())
1267 ->setReadOnly(TRUE);
1277 public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
1282 * Returns an array of field names to skip in ::hasTranslationChanges.
1285 * An array of field names.
1287 protected function getFieldsToSkipFromTranslationChangesCheck() {
1288 // A list of known revision metadata fields which should be skipped from
1290 // @todo Replace the hard coded list of revision metadata fields with the
1291 // solution from https://www.drupal.org/node/2615016.
1293 $this->getEntityType()->getKey('revision'),
1294 'revision_translation_affected',
1297 'revision_timestamp',
1300 'revision_log_message',
1309 public function hasTranslationChanges() {
1310 if ($this->isNew()) {
1314 // $this->original only exists during save. See
1315 // \Drupal\Core\Entity\EntityStorageBase::save(). If it exists we re-use it
1316 // here for performance reasons.
1317 /** @var \Drupal\Core\Entity\ContentEntityBase $original */
1318 $original = $this->original ? $this->original : NULL;
1321 $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id();
1322 $original = $this->entityManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id);
1325 // If the current translation has just been added, we have a change.
1326 $translated = count($this->translations) > 1;
1327 if ($translated && !$original->hasTranslation($this->activeLangcode)) {
1331 // Compare field item current values with the original ones to determine
1332 // whether we have changes. If a field is not translatable and the entity is
1333 // translated we skip it because, depending on the use case, it would make
1334 // sense to mark all translations as changed or none of them. We skip also
1335 // computed fields as comparing them with their original values might not be
1336 // possible or be meaningless.
1337 /** @var \Drupal\Core\Entity\ContentEntityBase $translation */
1338 $translation = $original->getTranslation($this->activeLangcode);
1340 // The list of fields to skip from the comparision.
1341 $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck();
1343 foreach ($this->getFieldDefinitions() as $field_name => $definition) {
1344 // @todo Avoid special-casing the following fields. See
1345 // https://www.drupal.org/node/2329253.
1346 if (in_array($field_name, $skip_fields, TRUE)) {
1349 $field = $this->get($field_name);
1350 // When saving entities in the user interface, the changed timestamp is
1351 // automatically incremented by ContentEntityForm::submitForm() even if
1352 // nothing was actually changed. Thus, the changed time needs to be
1353 // ignored when determining whether there are any actual changes in the
1355 if (!($field instanceof ChangedFieldItemList) && !$definition->isComputed()) {
1356 $items = $field->filterEmptyItems();
1357 $original_items = $translation->get($field_name)->filterEmptyItems();
1358 if (!$items->equals($original_items)) {