Chris@0: entityTypeId = $entity_type; Chris@0: $this->entityKeys['bundle'] = $bundle ? $bundle : $this->entityTypeId; Chris@0: $this->langcodeKey = $this->getEntityType()->getKey('langcode'); Chris@0: $this->defaultLangcodeKey = $this->getEntityType()->getKey('default_langcode'); Chris@14: $this->revisionTranslationAffectedKey = $this->getEntityType()->getKey('revision_translation_affected'); Chris@0: Chris@0: foreach ($values as $key => $value) { Chris@0: // If the key matches an existing property set the value to the property Chris@0: // to set properties like isDefaultRevision. Chris@0: // @todo: Should this be converted somehow? Chris@0: if (property_exists($this, $key) && isset($value[LanguageInterface::LANGCODE_DEFAULT])) { Chris@0: $this->$key = $value[LanguageInterface::LANGCODE_DEFAULT]; Chris@0: } Chris@0: } Chris@0: Chris@0: $this->values = $values; Chris@0: foreach ($this->getEntityType()->getKeys() as $key => $field_name) { Chris@0: if (isset($this->values[$field_name])) { Chris@0: if (is_array($this->values[$field_name])) { Chris@0: // We store untranslatable fields into an entity key without using a Chris@0: // langcode key. Chris@0: if (!$this->getFieldDefinition($field_name)->isTranslatable()) { Chris@0: if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) { Chris@0: if (is_array($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) { Chris@0: if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'])) { Chris@0: $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value']; Chris@0: } Chris@0: } Chris@0: else { Chris@0: $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT]; Chris@0: } Chris@0: } Chris@0: } Chris@0: else { Chris@0: // We save translatable fields such as the publishing status of a node Chris@0: // into an entity key array keyed by langcode as a performance Chris@0: // optimization, so we don't have to go through TypedData when we Chris@0: // need these values. Chris@0: foreach ($this->values[$field_name] as $langcode => $field_value) { Chris@0: if (is_array($this->values[$field_name][$langcode])) { Chris@0: if (isset($this->values[$field_name][$langcode][0]['value'])) { Chris@0: $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode][0]['value']; Chris@0: } Chris@0: } Chris@0: else { Chris@0: $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode]; Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Initialize translations. Ensure we have at least an entry for the default Chris@0: // language. Chris@0: // We determine if the entity is new by checking in the entity values for Chris@0: // the presence of the id entity key, as the usage of ::isNew() is not Chris@0: // possible in the constructor. Chris@0: $data = isset($values[$this->getEntityType()->getKey('id')]) ? ['status' => static::TRANSLATION_EXISTING] : ['status' => static::TRANSLATION_CREATED]; Chris@0: $this->translations[LanguageInterface::LANGCODE_DEFAULT] = $data; Chris@0: $this->setDefaultLangcode(); Chris@0: if ($translations) { Chris@0: foreach ($translations as $langcode) { Chris@0: if ($langcode != $this->defaultLangcode && $langcode != LanguageInterface::LANGCODE_DEFAULT) { Chris@0: $this->translations[$langcode] = $data; Chris@0: } Chris@0: } Chris@0: } Chris@0: if ($this->getEntityType()->isRevisionable()) { Chris@0: // Store the loaded revision ID the entity has been loaded with to Chris@0: // keep it safe from changes. Chris@0: $this->updateLoadedRevisionId(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function getLanguages() { Chris@0: if (empty($this->languages)) { Chris@0: $this->languages = $this->languageManager()->getLanguages(LanguageInterface::STATE_ALL); Chris@0: // If the entity references a language that is not or no longer available, Chris@0: // we return a mock language object to avoid disrupting the consuming Chris@0: // code. Chris@0: if (!isset($this->languages[$this->defaultLangcode])) { Chris@0: $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]); Chris@0: } Chris@0: } Chris@0: return $this->languages; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function postCreate(EntityStorageInterface $storage) { Chris@0: $this->newRevision = TRUE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function setNewRevision($value = TRUE) { Chris@0: if (!$this->getEntityType()->hasKey('revision')) { Chris@0: throw new \LogicException("Entity type {$this->getEntityTypeId()} does not support revisions."); Chris@0: } Chris@0: Chris@0: if ($value && !$this->newRevision) { Chris@0: // When saving a new revision, set any existing revision ID to NULL so as Chris@0: // to ensure that a new revision will actually be created. Chris@0: $this->set($this->getEntityType()->getKey('revision'), NULL); Chris@14: } Chris@14: elseif (!$value && $this->newRevision) { Chris@14: // If ::setNewRevision(FALSE) is called after ::setNewRevision(TRUE) we Chris@14: // have to restore the loaded revision ID. Chris@14: $this->set($this->getEntityType()->getKey('revision'), $this->getLoadedRevisionId()); Chris@0: } Chris@0: Chris@0: $this->newRevision = $value; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getLoadedRevisionId() { Chris@0: return $this->loadedRevisionId; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function updateLoadedRevisionId() { Chris@0: $this->loadedRevisionId = $this->getRevisionId() ?: $this->loadedRevisionId; Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function isNewRevision() { Chris@0: return $this->newRevision || ($this->getEntityType()->hasKey('revision') && !$this->getRevisionId()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function isDefaultRevision($new_value = NULL) { Chris@0: $return = $this->isDefaultRevision; Chris@0: if (isset($new_value)) { Chris@0: $this->isDefaultRevision = (bool) $new_value; Chris@0: } Chris@0: // New entities should always ensure at least one default revision exists, Chris@0: // creating an entity without a default revision is an invalid state. Chris@0: return $this->isNew() || $return; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@14: public function wasDefaultRevision() { Chris@14: /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */ Chris@14: $entity_type = $this->getEntityType(); Chris@14: if (!$entity_type->isRevisionable()) { Chris@14: return TRUE; Chris@14: } Chris@14: Chris@14: $revision_default_key = $entity_type->getRevisionMetadataKey('revision_default'); Chris@14: $value = $this->isNew() || $this->get($revision_default_key)->value; Chris@14: return $value; Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@14: public function isLatestRevision() { Chris@14: /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */ Chris@14: $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId()); Chris@14: Chris@14: return $this->getLoadedRevisionId() == $storage->getLatestRevisionId($this->id()); Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@14: public function isLatestTranslationAffectedRevision() { Chris@14: /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */ Chris@14: $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId()); Chris@14: Chris@14: return $this->getLoadedRevisionId() == $storage->getLatestTranslationAffectedRevisionId($this->id(), $this->language()->getId()); Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@0: public function isRevisionTranslationAffected() { Chris@14: return $this->hasField($this->revisionTranslationAffectedKey) ? $this->get($this->revisionTranslationAffectedKey)->value : TRUE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function setRevisionTranslationAffected($affected) { Chris@14: if ($this->hasField($this->revisionTranslationAffectedKey)) { Chris@14: $this->set($this->revisionTranslationAffectedKey, $affected); Chris@0: } Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@14: public function isRevisionTranslationAffectedEnforced() { Chris@14: return !empty($this->enforceRevisionTranslationAffected[$this->activeLangcode]); Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@14: public function setRevisionTranslationAffectedEnforced($enforced) { Chris@14: $this->enforceRevisionTranslationAffected[$this->activeLangcode] = $enforced; Chris@14: return $this; Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@0: public function isDefaultTranslation() { Chris@0: return $this->activeLangcode === LanguageInterface::LANGCODE_DEFAULT; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getRevisionId() { Chris@0: return $this->getEntityKey('revision'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function isTranslatable() { Chris@14: // Check the bundle is translatable, the entity has a language defined, and Chris@14: // the site has more than one language. Chris@18: $bundles = $this->entityTypeBundleInfo()->getBundleInfo($this->entityTypeId); Chris@0: return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function preSave(EntityStorageInterface $storage) { Chris@0: // An entity requiring validation should not be saved if it has not been Chris@0: // actually validated. Chris@0: if ($this->validationRequired && !$this->validated) { Chris@0: // @todo Make this an assertion in https://www.drupal.org/node/2408013. Chris@0: throw new \LogicException('Entity validation was skipped.'); Chris@0: } Chris@0: else { Chris@0: $this->validated = FALSE; Chris@0: } Chris@0: Chris@0: parent::preSave($storage); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) { Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function postSave(EntityStorageInterface $storage, $update = TRUE) { Chris@0: parent::postSave($storage, $update); Chris@0: Chris@0: // Update the status of all saved translations. Chris@0: $removed = []; Chris@0: foreach ($this->translations as $langcode => &$data) { Chris@0: if ($data['status'] == static::TRANSLATION_REMOVED) { Chris@0: $removed[$langcode] = TRUE; Chris@0: } Chris@0: else { Chris@0: $data['status'] = static::TRANSLATION_EXISTING; Chris@0: } Chris@0: } Chris@0: $this->translations = array_diff_key($this->translations, $removed); Chris@14: Chris@14: // Reset the new revision flag. Chris@14: $this->newRevision = FALSE; Chris@14: Chris@14: // Reset the enforcement of the revision translation affected flag. Chris@14: $this->enforceRevisionTranslationAffected = []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function validate() { Chris@0: $this->validated = TRUE; Chris@0: $violations = $this->getTypedData()->validate(); Chris@0: return new EntityConstraintViolationList($this, iterator_to_array($violations)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function isValidationRequired() { Chris@0: return (bool) $this->validationRequired; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function setValidationRequired($required) { Chris@0: $this->validationRequired = $required; Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clear entity translation object cache to remove stale references. Chris@0: */ Chris@0: protected function clearTranslationCache() { Chris@0: foreach ($this->translations as &$translation) { Chris@0: unset($translation['entity']); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function __sleep() { Chris@0: // Get the values of instantiated field objects, only serialize the values. Chris@0: foreach ($this->fields as $name => $fields) { Chris@0: foreach ($fields as $langcode => $field) { Chris@0: $this->values[$name][$langcode] = $field->getValue(); Chris@0: } Chris@0: } Chris@0: $this->fields = []; Chris@0: $this->fieldDefinitions = NULL; Chris@0: $this->languages = NULL; Chris@0: $this->clearTranslationCache(); Chris@0: Chris@0: return parent::__sleep(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function id() { Chris@0: return $this->getEntityKey('id'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function bundle() { Chris@0: return $this->getEntityKey('bundle'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function uuid() { Chris@0: return $this->getEntityKey('uuid'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function hasField($field_name) { Chris@0: return (bool) $this->getFieldDefinition($field_name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function get($field_name) { Chris@0: if (!isset($this->fields[$field_name][$this->activeLangcode])) { Chris@0: return $this->getTranslatedField($field_name, $this->activeLangcode); Chris@0: } Chris@0: return $this->fields[$field_name][$this->activeLangcode]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a translated field. Chris@0: * Chris@0: * @return \Drupal\Core\Field\FieldItemListInterface Chris@0: */ Chris@0: protected function getTranslatedField($name, $langcode) { Chris@0: if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) { Chris@0: throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated."); Chris@0: } Chris@0: // Populate $this->fields to speed-up further look-ups and to keep track of Chris@0: // fields objects, possibly holding changes to field values. Chris@0: if (!isset($this->fields[$name][$langcode])) { Chris@0: $definition = $this->getFieldDefinition($name); Chris@0: if (!$definition) { Chris@0: throw new \InvalidArgumentException("Field $name is unknown."); Chris@0: } Chris@0: // Non-translatable fields are always stored with Chris@0: // LanguageInterface::LANGCODE_DEFAULT as key. Chris@0: Chris@0: $default = $langcode == LanguageInterface::LANGCODE_DEFAULT; Chris@0: if (!$default && !$definition->isTranslatable()) { Chris@0: if (!isset($this->fields[$name][LanguageInterface::LANGCODE_DEFAULT])) { Chris@0: $this->fields[$name][LanguageInterface::LANGCODE_DEFAULT] = $this->getTranslatedField($name, LanguageInterface::LANGCODE_DEFAULT); Chris@0: } Chris@0: $this->fields[$name][$langcode] = &$this->fields[$name][LanguageInterface::LANGCODE_DEFAULT]; Chris@0: } Chris@0: else { Chris@0: $value = NULL; Chris@0: if (isset($this->values[$name][$langcode])) { Chris@0: $value = $this->values[$name][$langcode]; Chris@0: } Chris@0: $field = \Drupal::service('plugin.manager.field.field_type')->createFieldItemList($this->getTranslation($langcode), $name, $value); Chris@0: if ($default) { Chris@0: // $this->defaultLangcode might not be set if we are initializing the Chris@0: // default language code cache, in which case there is no valid Chris@0: // langcode to assign. Chris@0: $field_langcode = isset($this->defaultLangcode) ? $this->defaultLangcode : LanguageInterface::LANGCODE_NOT_SPECIFIED; Chris@0: } Chris@0: else { Chris@0: $field_langcode = $langcode; Chris@0: } Chris@0: $field->setLangcode($field_langcode); Chris@0: $this->fields[$name][$langcode] = $field; Chris@0: } Chris@0: } Chris@0: return $this->fields[$name][$langcode]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function set($name, $value, $notify = TRUE) { Chris@0: // Assign the value on the child and overrule notify such that we get Chris@0: // notified to handle changes afterwards. We can ignore notify as there is Chris@0: // no parent to notify anyway. Chris@0: $this->get($name)->setValue($value, TRUE); Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getFields($include_computed = TRUE) { Chris@0: $fields = []; Chris@0: foreach ($this->getFieldDefinitions() as $name => $definition) { Chris@0: if ($include_computed || !$definition->isComputed()) { Chris@0: $fields[$name] = $this->get($name); Chris@0: } Chris@0: } Chris@0: return $fields; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getTranslatableFields($include_computed = TRUE) { Chris@0: $fields = []; Chris@0: foreach ($this->getFieldDefinitions() as $name => $definition) { Chris@0: if (($include_computed || !$definition->isComputed()) && $definition->isTranslatable()) { Chris@0: $fields[$name] = $this->get($name); Chris@0: } Chris@0: } Chris@0: return $fields; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getIterator() { Chris@0: return new \ArrayIterator($this->getFields()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getFieldDefinition($name) { Chris@0: if (!isset($this->fieldDefinitions)) { Chris@0: $this->getFieldDefinitions(); Chris@0: } Chris@0: if (isset($this->fieldDefinitions[$name])) { Chris@0: return $this->fieldDefinitions[$name]; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getFieldDefinitions() { Chris@0: if (!isset($this->fieldDefinitions)) { Chris@18: $this->fieldDefinitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($this->entityTypeId, $this->bundle()); Chris@0: } Chris@0: return $this->fieldDefinitions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function toArray() { Chris@0: $values = []; Chris@0: foreach ($this->getFields() as $name => $property) { Chris@0: $values[$name] = $property->getValue(); Chris@0: } Chris@0: return $values; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) { Chris@0: if ($operation == 'create') { Chris@18: return $this->entityTypeManager() Chris@0: ->getAccessControlHandler($this->entityTypeId) Chris@0: ->createAccess($this->bundle(), $account, [], $return_as_object); Chris@0: } Chris@18: return $this->entityTypeManager() Chris@0: ->getAccessControlHandler($this->entityTypeId) Chris@0: ->access($this, $operation, $account, $return_as_object); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function language() { Chris@0: $language = NULL; Chris@0: if ($this->activeLangcode != LanguageInterface::LANGCODE_DEFAULT) { Chris@0: if (!isset($this->languages[$this->activeLangcode])) { Chris@0: $this->getLanguages(); Chris@0: } Chris@0: $language = $this->languages[$this->activeLangcode]; Chris@0: } Chris@0: else { Chris@0: // @todo Avoid this check by getting the language from the language Chris@0: // manager directly in https://www.drupal.org/node/2303877. Chris@0: if (!isset($this->languages[$this->defaultLangcode])) { Chris@0: $this->getLanguages(); Chris@0: } Chris@0: $language = $this->languages[$this->defaultLangcode]; Chris@0: } Chris@0: return $language; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Populates the local cache for the default language code. Chris@0: */ Chris@0: protected function setDefaultLangcode() { Chris@0: // Get the language code if the property exists. Chris@0: // Try to read the value directly from the list of entity keys which got Chris@0: // initialized in __construct(). This avoids creating a field item object. Chris@0: if (isset($this->translatableEntityKeys['langcode'][$this->activeLangcode])) { Chris@0: $this->defaultLangcode = $this->translatableEntityKeys['langcode'][$this->activeLangcode]; Chris@0: } Chris@0: elseif ($this->hasField($this->langcodeKey) && ($item = $this->get($this->langcodeKey)) && isset($item->language)) { Chris@0: $this->defaultLangcode = $item->language->getId(); Chris@0: $this->translatableEntityKeys['langcode'][$this->activeLangcode] = $this->defaultLangcode; Chris@0: } Chris@0: Chris@0: if (empty($this->defaultLangcode)) { Chris@0: // Make sure we return a proper language object, if the entity has a Chris@0: // langcode field, default to the site's default language. Chris@0: if ($this->hasField($this->langcodeKey)) { Chris@0: $this->defaultLangcode = $this->languageManager()->getDefaultLanguage()->getId(); Chris@0: } Chris@0: else { Chris@0: $this->defaultLangcode = LanguageInterface::LANGCODE_NOT_SPECIFIED; Chris@0: } Chris@0: } Chris@0: Chris@0: // This needs to be initialized manually as it is skipped when instantiating Chris@0: // the language field object to avoid infinite recursion. Chris@0: if (!empty($this->fields[$this->langcodeKey])) { Chris@0: $this->fields[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT]->setLangcode($this->defaultLangcode); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Updates language for already instantiated fields. Chris@0: */ Chris@0: protected function updateFieldLangcodes($langcode) { Chris@0: foreach ($this->fields as $name => $items) { Chris@0: if (!empty($items[LanguageInterface::LANGCODE_DEFAULT])) { Chris@0: $items[LanguageInterface::LANGCODE_DEFAULT]->setLangcode($langcode); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function onChange($name) { Chris@16: // Check if the changed name is the value of any entity keys and if any of Chris@16: // those values are currently cached, if so, reset it. Exclude the bundle Chris@16: // from that check, as it ready only and must not change, unsetting it could Chris@0: // lead to recursions. Chris@16: foreach (array_keys($this->getEntityType()->getKeys(), $name, TRUE) as $key) { Chris@0: if ($key != 'bundle') { Chris@0: if (isset($this->entityKeys[$key])) { Chris@0: unset($this->entityKeys[$key]); Chris@0: } Chris@0: elseif (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) { Chris@0: unset($this->translatableEntityKeys[$key][$this->activeLangcode]); Chris@0: } Chris@12: // If the revision identifier field is being populated with the original Chris@12: // value, we need to make sure the "new revision" flag is reset Chris@12: // accordingly. Chris@14: if ($key === 'revision' && $this->getRevisionId() == $this->getLoadedRevisionId() && !$this->isNew()) { Chris@12: $this->newRevision = FALSE; Chris@12: } Chris@0: } Chris@0: } Chris@0: Chris@0: switch ($name) { Chris@0: case $this->langcodeKey: Chris@0: if ($this->isDefaultTranslation()) { Chris@0: // Update the default internal language cache. Chris@0: $this->setDefaultLangcode(); Chris@0: if (isset($this->translations[$this->defaultLangcode])) { Chris@17: $message = new FormattableMarkup('A translation already exists for the specified language (@langcode).', ['@langcode' => $this->defaultLangcode]); Chris@0: throw new \InvalidArgumentException($message); Chris@0: } Chris@0: $this->updateFieldLangcodes($this->defaultLangcode); Chris@0: } Chris@0: else { Chris@0: // @todo Allow the translation language to be changed. See Chris@0: // https://www.drupal.org/node/2443989. Chris@0: $items = $this->get($this->langcodeKey); Chris@0: if ($items->value != $this->activeLangcode) { Chris@0: $items->setValue($this->activeLangcode, FALSE); Chris@17: $message = new FormattableMarkup('The translation language cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]); Chris@0: throw new \LogicException($message); Chris@0: } Chris@0: } Chris@0: break; Chris@0: Chris@0: case $this->defaultLangcodeKey: Chris@0: // @todo Use a standard method to make the default_langcode field Chris@0: // read-only. See https://www.drupal.org/node/2443991. Chris@0: if (isset($this->values[$this->defaultLangcodeKey]) && $this->get($this->defaultLangcodeKey)->value != $this->isDefaultTranslation()) { Chris@0: $this->get($this->defaultLangcodeKey)->setValue($this->isDefaultTranslation(), FALSE); Chris@17: $message = new FormattableMarkup('The default translation flag cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]); Chris@0: throw new \LogicException($message); Chris@0: } Chris@0: break; Chris@14: Chris@14: case $this->revisionTranslationAffectedKey: Chris@14: // If the revision translation affected flag is being set then enforce Chris@14: // its value. Chris@14: $this->setRevisionTranslationAffectedEnforced(TRUE); Chris@14: break; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getTranslation($langcode) { Chris@0: // Ensure we always use the default language code when dealing with the Chris@0: // original entity language. Chris@0: if ($langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode == $this->defaultLangcode) { Chris@0: $langcode = LanguageInterface::LANGCODE_DEFAULT; Chris@0: } Chris@0: Chris@0: // Populate entity translation object cache so it will be available for all Chris@0: // translation objects. Chris@17: if (!isset($this->translations[$this->activeLangcode]['entity'])) { Chris@17: $this->translations[$this->activeLangcode]['entity'] = $this; Chris@0: } Chris@0: Chris@0: // If we already have a translation object for the specified language we can Chris@0: // just return it. Chris@0: if (isset($this->translations[$langcode]['entity'])) { Chris@0: $translation = $this->translations[$langcode]['entity']; Chris@0: } Chris@0: // Otherwise if an existing translation language was specified we need to Chris@0: // instantiate the related translation. Chris@0: elseif (isset($this->translations[$langcode])) { Chris@0: $translation = $this->initializeTranslation($langcode); Chris@0: $this->translations[$langcode]['entity'] = $translation; Chris@0: } Chris@0: Chris@0: if (empty($translation)) { Chris@0: throw new \InvalidArgumentException("Invalid translation language ($langcode) specified."); Chris@0: } Chris@0: Chris@0: return $translation; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getUntranslated() { Chris@0: return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Instantiates a translation object for an existing translation. Chris@0: * Chris@0: * The translated entity will be a clone of the current entity with the Chris@0: * specified $langcode. All translations share the same field data structures Chris@0: * to ensure that all of them deal with fresh data. Chris@0: * Chris@0: * @param string $langcode Chris@0: * The language code for the requested translation. Chris@0: * Chris@0: * @return \Drupal\Core\Entity\EntityInterface Chris@0: * The translation object. The content properties of the translation object Chris@0: * are stored as references to the main entity. Chris@0: */ Chris@0: protected function initializeTranslation($langcode) { Chris@0: // If the requested translation is valid, clone it with the current language Chris@0: // as the active language. The $translationInitialize flag triggers a Chris@0: // shallow (non-recursive) clone. Chris@0: $this->translationInitialize = TRUE; Chris@0: $translation = clone $this; Chris@0: $this->translationInitialize = FALSE; Chris@0: Chris@0: $translation->activeLangcode = $langcode; Chris@0: Chris@0: // Ensure that changes to fields, values and translations are propagated Chris@0: // to all the translation objects. Chris@0: // @todo Consider converting these to ArrayObject. Chris@0: $translation->values = &$this->values; Chris@0: $translation->fields = &$this->fields; Chris@0: $translation->translations = &$this->translations; Chris@0: $translation->enforceIsNew = &$this->enforceIsNew; Chris@0: $translation->newRevision = &$this->newRevision; Chris@0: $translation->entityKeys = &$this->entityKeys; Chris@0: $translation->translatableEntityKeys = &$this->translatableEntityKeys; Chris@0: $translation->translationInitialize = FALSE; Chris@0: $translation->typedData = NULL; Chris@0: $translation->loadedRevisionId = &$this->loadedRevisionId; Chris@0: $translation->isDefaultRevision = &$this->isDefaultRevision; Chris@14: $translation->enforceRevisionTranslationAffected = &$this->enforceRevisionTranslationAffected; Chris@18: $translation->isSyncing = &$this->isSyncing; Chris@0: Chris@0: return $translation; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function hasTranslation($langcode) { Chris@0: if ($langcode == $this->defaultLangcode) { Chris@0: $langcode = LanguageInterface::LANGCODE_DEFAULT; Chris@0: } Chris@0: return !empty($this->translations[$langcode]['status']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function isNewTranslation() { Chris@0: return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function addTranslation($langcode, array $values = []) { Chris@0: // Make sure we do not attempt to create a translation if an invalid Chris@0: // language is specified or the entity cannot be translated. Chris@0: $this->getLanguages(); Chris@0: if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) { Chris@0: throw new \InvalidArgumentException("Invalid translation language ($langcode) specified."); Chris@0: } Chris@0: if ($this->languages[$this->defaultLangcode]->isLocked()) { Chris@0: throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode})."); Chris@0: } Chris@0: Chris@0: // Initialize the translation object. Chris@0: /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */ Chris@18: $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId()); Chris@0: $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING; Chris@0: return $storage->createTranslation($this, $langcode, $values); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function removeTranslation($langcode) { Chris@0: if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) { Chris@0: foreach ($this->getFieldDefinitions() as $name => $definition) { Chris@0: if ($definition->isTranslatable()) { Chris@0: unset($this->values[$name][$langcode]); Chris@0: unset($this->fields[$name][$langcode]); Chris@0: } Chris@0: } Chris@0: // If removing a translation which has not been saved yet, then we have Chris@0: // to remove it completely so that ::getTranslationStatus returns the Chris@0: // proper status. Chris@0: if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) { Chris@0: unset($this->translations[$langcode]); Chris@0: } Chris@0: else { Chris@0: if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) { Chris@0: $this->translations[$langcode]['status_existed'] = TRUE; Chris@0: } Chris@0: $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED; Chris@0: } Chris@0: } Chris@0: else { Chris@0: throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed."); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getTranslationStatus($langcode) { Chris@0: if ($langcode == $this->defaultLangcode) { Chris@0: $langcode = LanguageInterface::LANGCODE_DEFAULT; Chris@0: } Chris@0: return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getTranslationLanguages($include_default = TRUE) { Chris@0: $translations = array_filter($this->translations, function ($translation) { Chris@0: return $translation['status']; Chris@0: }); Chris@0: unset($translations[LanguageInterface::LANGCODE_DEFAULT]); Chris@0: Chris@0: if ($include_default) { Chris@0: $translations[$this->defaultLangcode] = TRUE; Chris@0: } Chris@0: Chris@0: // Now load language objects based upon translation langcodes. Chris@0: return array_intersect_key($this->getLanguages(), $translations); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Updates the original values with the interim changes. Chris@0: */ Chris@0: public function updateOriginalValues() { Chris@0: if (!$this->fields) { Chris@0: return; Chris@0: } Chris@0: foreach ($this->getFieldDefinitions() as $name => $definition) { Chris@0: if (!$definition->isComputed() && !empty($this->fields[$name])) { Chris@0: foreach ($this->fields[$name] as $langcode => $item) { Chris@0: $item->filterEmptyItems(); Chris@0: $this->values[$name][$langcode] = $item->getValue(); Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements the magic method for getting object properties. Chris@0: * Chris@0: * @todo: A lot of code still uses non-fields (e.g. $entity->content in view Chris@0: * builders) by reference. Clean that up. Chris@0: */ Chris@0: public function &__get($name) { Chris@0: // If this is an entity field, handle it accordingly. We first check whether Chris@0: // a field object has been already created. If not, we create one. Chris@0: if (isset($this->fields[$name][$this->activeLangcode])) { Chris@0: return $this->fields[$name][$this->activeLangcode]; Chris@0: } Chris@0: // Inline getFieldDefinition() to speed things up. Chris@0: if (!isset($this->fieldDefinitions)) { Chris@0: $this->getFieldDefinitions(); Chris@0: } Chris@0: if (isset($this->fieldDefinitions[$name])) { Chris@0: $return = $this->getTranslatedField($name, $this->activeLangcode); Chris@0: return $return; Chris@0: } Chris@0: // Else directly read/write plain values. That way, non-field entity Chris@0: // properties can always be accessed directly. Chris@0: if (!isset($this->values[$name])) { Chris@0: $this->values[$name] = NULL; Chris@0: } Chris@0: return $this->values[$name]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements the magic method for setting object properties. Chris@0: * Chris@0: * Uses default language always. Chris@0: */ Chris@0: public function __set($name, $value) { Chris@0: // Inline getFieldDefinition() to speed things up. Chris@0: if (!isset($this->fieldDefinitions)) { Chris@0: $this->getFieldDefinitions(); Chris@0: } Chris@0: // Handle Field API fields. Chris@0: if (isset($this->fieldDefinitions[$name])) { Chris@0: // Support setting values via property objects. Chris@0: if ($value instanceof TypedDataInterface) { Chris@0: $value = $value->getValue(); Chris@0: } Chris@0: // If a FieldItemList object already exists, set its value. Chris@0: if (isset($this->fields[$name][$this->activeLangcode])) { Chris@0: $this->fields[$name][$this->activeLangcode]->setValue($value); Chris@0: } Chris@0: // If not, create one. Chris@0: else { Chris@0: $this->getTranslatedField($name, $this->activeLangcode)->setValue($value); Chris@0: } Chris@0: } Chris@0: // The translations array is unset when cloning the entity object, we just Chris@0: // need to restore it. Chris@0: elseif ($name == 'translations') { Chris@0: $this->translations = $value; Chris@0: } Chris@0: // Directly write non-field values. Chris@0: else { Chris@0: $this->values[$name] = $value; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements the magic method for isset(). Chris@0: */ Chris@0: public function __isset($name) { Chris@0: // "Official" Field API fields are always set. For non-field properties, Chris@0: // check the internal values. Chris@0: return $this->hasField($name) ? TRUE : isset($this->values[$name]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements the magic method for unset(). Chris@0: */ Chris@0: public function __unset($name) { Chris@0: // Unsetting a field means emptying it. Chris@0: if ($this->hasField($name)) { Chris@0: $this->get($name)->setValue([]); Chris@0: } Chris@0: // For non-field properties, unset the internal value. Chris@0: else { Chris@0: unset($this->values[$name]); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function createDuplicate() { Chris@0: if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) { Chris@0: throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated."); Chris@0: } Chris@0: Chris@0: $duplicate = clone $this; Chris@0: $entity_type = $this->getEntityType(); Chris@14: if ($entity_type->hasKey('id')) { Chris@14: $duplicate->{$entity_type->getKey('id')}->value = NULL; Chris@14: } Chris@0: $duplicate->enforceIsNew(); Chris@0: Chris@0: // Check if the entity type supports UUIDs and generate a new one if so. Chris@0: if ($entity_type->hasKey('uuid')) { Chris@0: $duplicate->{$entity_type->getKey('uuid')}->value = $this->uuidGenerator()->generate(); Chris@0: } Chris@0: Chris@0: // Check whether the entity type supports revisions and initialize it if so. Chris@0: if ($entity_type->isRevisionable()) { Chris@0: $duplicate->{$entity_type->getKey('revision')}->value = NULL; Chris@0: $duplicate->loadedRevisionId = NULL; Chris@0: } Chris@0: Chris@0: return $duplicate; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Magic method: Implements a deep clone. Chris@0: */ Chris@0: public function __clone() { Chris@0: // Avoid deep-cloning when we are initializing a translation object, since Chris@0: // it will represent the same entity, only with a different active language. Chris@0: if ($this->translationInitialize) { Chris@0: return; Chris@0: } Chris@0: Chris@0: // The translation is a different object, and needs its own TypedData Chris@0: // adapter object. Chris@0: $this->typedData = NULL; Chris@0: $definitions = $this->getFieldDefinitions(); Chris@0: Chris@0: // The translation cache has to be cleared before cloning the fields Chris@0: // below so that the call to getTranslation() does not re-use the Chris@0: // translation objects of the old entity but instead creates new Chris@0: // translation objects from the newly cloned entity. Otherwise the newly Chris@0: // cloned field item lists would hold references to the old translation Chris@0: // objects in their $parent property after the call to setContext(). Chris@0: $this->clearTranslationCache(); Chris@0: Chris@0: // Because the new translation objects that are created below are Chris@0: // themselves created by *cloning* the newly cloned entity we need to Chris@0: // make sure that the references to property values are properly cloned Chris@0: // before cloning the fields. Otherwise calling Chris@0: // $items->getEntity()->isNew(), for example, would return the Chris@0: // $enforceIsNew value of the old entity. Chris@0: Chris@0: // Ensure the translations array is actually cloned by overwriting the Chris@0: // original reference with one pointing to a copy of the array. Chris@0: $translations = $this->translations; Chris@0: $this->translations = &$translations; Chris@0: Chris@0: // Ensure that the following properties are actually cloned by Chris@0: // overwriting the original references with ones pointing to copies of Chris@0: // them: enforceIsNew, newRevision, loadedRevisionId, fields, entityKeys, Chris@14: // translatableEntityKeys, values, isDefaultRevision and Chris@14: // enforceRevisionTranslationAffected. Chris@0: $enforce_is_new = $this->enforceIsNew; Chris@0: $this->enforceIsNew = &$enforce_is_new; Chris@0: Chris@0: $new_revision = $this->newRevision; Chris@0: $this->newRevision = &$new_revision; Chris@0: Chris@0: $original_revision_id = $this->loadedRevisionId; Chris@0: $this->loadedRevisionId = &$original_revision_id; Chris@0: Chris@0: $fields = $this->fields; Chris@0: $this->fields = &$fields; Chris@0: Chris@0: $entity_keys = $this->entityKeys; Chris@0: $this->entityKeys = &$entity_keys; Chris@0: Chris@0: $translatable_entity_keys = $this->translatableEntityKeys; Chris@0: $this->translatableEntityKeys = &$translatable_entity_keys; Chris@0: Chris@0: $values = $this->values; Chris@0: $this->values = &$values; Chris@0: Chris@0: $default_revision = $this->isDefaultRevision; Chris@0: $this->isDefaultRevision = &$default_revision; Chris@0: Chris@14: $is_revision_translation_affected_enforced = $this->enforceRevisionTranslationAffected; Chris@14: $this->enforceRevisionTranslationAffected = &$is_revision_translation_affected_enforced; Chris@14: Chris@18: $is_syncing = $this->isSyncing; Chris@18: $this->isSyncing = &$is_syncing; Chris@18: Chris@0: foreach ($this->fields as $name => $fields_by_langcode) { Chris@0: $this->fields[$name] = []; Chris@0: // Untranslatable fields may have multiple references for the same field Chris@0: // object keyed by language. To avoid creating different field objects Chris@0: // we retain just the original value, as references will be recreated Chris@0: // later as needed. Chris@0: if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) { Chris@0: $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]); Chris@0: } Chris@0: foreach ($fields_by_langcode as $langcode => $items) { Chris@0: $this->fields[$name][$langcode] = clone $items; Chris@0: $this->fields[$name][$langcode]->setContext($name, $this->getTranslation($langcode)->getTypedData()); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function label() { Chris@0: $label = NULL; Chris@0: $entity_type = $this->getEntityType(); Chris@0: if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) { Chris@0: $label = call_user_func($label_callback, $this); Chris@0: } Chris@0: elseif (($label_key = $entity_type->getKey('label'))) { Chris@0: $label = $this->getEntityKey('label'); Chris@0: } Chris@0: return $label; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function referencedEntities() { Chris@0: $referenced_entities = []; Chris@0: Chris@0: // Gather a list of referenced entities. Chris@0: foreach ($this->getFields() as $field_items) { Chris@0: foreach ($field_items as $field_item) { Chris@0: // Loop over all properties of a field item. Chris@0: foreach ($field_item->getProperties(TRUE) as $property) { Chris@0: if ($property instanceof EntityReference && $entity = $property->getValue()) { Chris@0: $referenced_entities[] = $entity; Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return $referenced_entities; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the value of the given entity key, if defined. Chris@0: * Chris@0: * @param string $key Chris@0: * Name of the entity key, for example id, revision or bundle. Chris@0: * Chris@0: * @return mixed Chris@0: * The value of the entity key, NULL if not defined. Chris@0: */ Chris@0: protected function getEntityKey($key) { Chris@0: // If the value is known already, return it. Chris@0: if (isset($this->entityKeys[$key])) { Chris@0: return $this->entityKeys[$key]; Chris@0: } Chris@0: if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) { Chris@0: return $this->translatableEntityKeys[$key][$this->activeLangcode]; Chris@0: } Chris@0: Chris@0: // Otherwise fetch the value by creating a field object. Chris@0: $value = NULL; Chris@0: if ($this->getEntityType()->hasKey($key)) { Chris@0: $field_name = $this->getEntityType()->getKey($key); Chris@0: $definition = $this->getFieldDefinition($field_name); Chris@0: $property = $definition->getFieldStorageDefinition()->getMainPropertyName(); Chris@0: $value = $this->get($field_name)->$property; Chris@0: Chris@0: // Put it in the right array, depending on whether it is translatable. Chris@0: if ($definition->isTranslatable()) { Chris@0: $this->translatableEntityKeys[$key][$this->activeLangcode] = $value; Chris@0: } Chris@0: else { Chris@0: $this->entityKeys[$key] = $value; Chris@0: } Chris@0: } Chris@0: else { Chris@0: $this->entityKeys[$key] = $value; Chris@0: } Chris@0: return $value; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { Chris@0: $fields = []; Chris@0: if ($entity_type->hasKey('id')) { Chris@0: $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer') Chris@0: ->setLabel(new TranslatableMarkup('ID')) Chris@0: ->setReadOnly(TRUE) Chris@0: ->setSetting('unsigned', TRUE); Chris@0: } Chris@0: if ($entity_type->hasKey('uuid')) { Chris@0: $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid') Chris@0: ->setLabel(new TranslatableMarkup('UUID')) Chris@0: ->setReadOnly(TRUE); Chris@0: } Chris@0: if ($entity_type->hasKey('revision')) { Chris@0: $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer') Chris@0: ->setLabel(new TranslatableMarkup('Revision ID')) Chris@0: ->setReadOnly(TRUE) Chris@0: ->setSetting('unsigned', TRUE); Chris@0: } Chris@0: if ($entity_type->hasKey('langcode')) { Chris@0: $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language') Chris@0: ->setLabel(new TranslatableMarkup('Language')) Chris@0: ->setDisplayOptions('view', [ Chris@0: 'region' => 'hidden', Chris@0: ]) Chris@0: ->setDisplayOptions('form', [ Chris@0: 'type' => 'language_select', Chris@0: 'weight' => 2, Chris@0: ]); Chris@0: if ($entity_type->isRevisionable()) { Chris@0: $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE); Chris@0: } Chris@0: if ($entity_type->isTranslatable()) { Chris@0: $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE); Chris@0: } Chris@0: } Chris@0: if ($entity_type->hasKey('bundle')) { Chris@0: if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) { Chris@0: $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference') Chris@0: ->setLabel($entity_type->getBundleLabel()) Chris@0: ->setSetting('target_type', $bundle_entity_type_id) Chris@0: ->setRequired(TRUE) Chris@0: ->setReadOnly(TRUE); Chris@0: } Chris@0: else { Chris@0: $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string') Chris@0: ->setLabel($entity_type->getBundleLabel()) Chris@0: ->setRequired(TRUE) Chris@0: ->setReadOnly(TRUE); Chris@0: } Chris@0: } Chris@0: Chris@0: return $fields; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) { Chris@0: return []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns an array of field names to skip in ::hasTranslationChanges. Chris@0: * Chris@0: * @return array Chris@0: * An array of field names. Chris@0: */ Chris@0: protected function getFieldsToSkipFromTranslationChangesCheck() { Chris@17: $bundle = $this->bundle(); Chris@17: if (!isset(static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle])) { Chris@17: static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle] = $this->traitGetFieldsToSkipFromTranslationChangesCheck($this); Chris@17: } Chris@17: return static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function hasTranslationChanges() { Chris@0: if ($this->isNew()) { Chris@0: return TRUE; Chris@0: } Chris@0: Chris@0: // $this->original only exists during save. See Chris@0: // \Drupal\Core\Entity\EntityStorageBase::save(). If it exists we re-use it Chris@0: // here for performance reasons. Chris@0: /** @var \Drupal\Core\Entity\ContentEntityBase $original */ Chris@0: $original = $this->original ? $this->original : NULL; Chris@0: Chris@0: if (!$original) { Chris@0: $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id(); Chris@18: $original = $this->entityTypeManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id); Chris@0: } Chris@0: Chris@0: // If the current translation has just been added, we have a change. Chris@0: $translated = count($this->translations) > 1; Chris@0: if ($translated && !$original->hasTranslation($this->activeLangcode)) { Chris@0: return TRUE; Chris@0: } Chris@0: Chris@0: // Compare field item current values with the original ones to determine Chris@0: // whether we have changes. If a field is not translatable and the entity is Chris@0: // translated we skip it because, depending on the use case, it would make Chris@0: // sense to mark all translations as changed or none of them. We skip also Chris@0: // computed fields as comparing them with their original values might not be Chris@0: // possible or be meaningless. Chris@0: /** @var \Drupal\Core\Entity\ContentEntityBase $translation */ Chris@0: $translation = $original->getTranslation($this->activeLangcode); Chris@17: $langcode = $this->language()->getId(); Chris@0: Chris@0: // The list of fields to skip from the comparision. Chris@0: $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck(); Chris@0: Chris@14: // We also check untranslatable fields, so that a change to those will mark Chris@14: // all translations as affected, unless they are configured to only affect Chris@14: // the default translation. Chris@14: $skip_untranslatable_fields = !$this->isDefaultTranslation() && $this->isDefaultTranslationAffectedOnly(); Chris@14: Chris@0: foreach ($this->getFieldDefinitions() as $field_name => $definition) { Chris@0: // @todo Avoid special-casing the following fields. See Chris@0: // https://www.drupal.org/node/2329253. Chris@14: if (in_array($field_name, $skip_fields, TRUE) || ($skip_untranslatable_fields && !$definition->isTranslatable())) { Chris@0: continue; Chris@0: } Chris@17: $items = $this->get($field_name)->filterEmptyItems(); Chris@17: $original_items = $translation->get($field_name)->filterEmptyItems(); Chris@17: if ($items->hasAffectingChanges($original_items, $langcode)) { Chris@17: return TRUE; Chris@0: } Chris@0: } Chris@0: Chris@0: return FALSE; Chris@0: } Chris@0: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@14: public function isDefaultTranslationAffectedOnly() { Chris@14: $bundle_name = $this->bundle(); Chris@14: $bundle_info = \Drupal::service('entity_type.bundle.info') Chris@14: ->getBundleInfo($this->getEntityTypeId()); Chris@14: return !empty($bundle_info[$bundle_name]['untranslatable_fields.default_translation_affected']); Chris@14: } Chris@14: Chris@0: }