View source
<?php
namespace Drupal\Core\Entity;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\MemoryCache\MemoryCacheInterface;
use Drupal\Core\Entity\Exception\AmbiguousBundleClassException;
use Drupal\Core\Entity\Exception\BundleClassInheritanceException;
use Drupal\Core\Entity\Exception\MissingBundleClassException;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\TypedData\TranslationStatusInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class ContentEntityStorageBase extends EntityStorageBase implements ContentEntityStorageInterface, DynamicallyFieldableEntityStorageInterface, BundleEntityStorageInterface {
protected $bundleKey = FALSE;
protected $entityFieldManager;
protected $entityTypeBundleInfo;
protected $cacheBackend;
protected $latestRevisionIds = [];
public function __construct(EntityTypeInterface $entity_type, EntityFieldManagerInterface $entity_field_manager, CacheBackendInterface $cache, MemoryCacheInterface $memory_cache, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
parent::__construct($entity_type, $memory_cache);
$this->bundleKey = $this->entityType
->getKey('bundle');
$this->entityFieldManager = $entity_field_manager;
$this->cacheBackend = $cache;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
public function create(array $values = []) {
$bundle = $this
->getBundleFromValues($values);
$entity_class = $this
->getEntityClass($bundle);
$entity_class::preCreate($this, $values);
if ($this->uuidKey && $this->uuidService && !isset($values[$this->uuidKey])) {
$values[$this->uuidKey] = $this->uuidService
->generate();
}
$entity = $this
->doCreate($values);
$entity
->enforceIsNew();
$entity
->postCreate($this);
$this
->invokeHook('create', $entity);
return $entity;
}
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($entity_type, $container
->get('entity_field.manager'), $container
->get('cache.entity'), $container
->get('entity.memory_cache'), $container
->get('entity_type.bundle.info'));
}
protected function doCreate(array $values) {
$bundle = $this
->getBundleFromValues($values);
if ($this->bundleKey && !$bundle) {
throw new EntityStorageException('Missing bundle for entity type ' . $this->entityTypeId);
}
$entity_class = $this
->getEntityClass($bundle);
$entity = new $entity_class([], $this->entityTypeId, $bundle);
$this
->initFieldValues($entity, $values);
return $entity;
}
public function getBundleFromClass(string $class_name) : ?string {
$bundle_for_class = NULL;
foreach ($this->entityTypeBundleInfo
->getBundleInfo($this->entityTypeId) as $bundle => $bundle_info) {
if (!empty($bundle_info['class']) && $bundle_info['class'] === $class_name) {
if ($bundle_for_class) {
throw new AmbiguousBundleClassException($class_name);
}
else {
$bundle_for_class = $bundle;
}
}
}
return $bundle_for_class;
}
protected function getBundleFromValues(array $values) : ?string {
$bundle = NULL;
if (!$this->bundleKey || !isset($values[$this->bundleKey])) {
return NULL;
}
$bundle_value = $values[$this->bundleKey];
if (!is_array($bundle_value)) {
$bundle = $bundle_value;
}
elseif (is_numeric(array_keys($bundle_value)[0])) {
$bundle = reset($bundle_value[0]);
}
else {
$bundle = reset($bundle_value);
}
return $bundle;
}
public function getEntityClass(?string $bundle = NULL) : string {
$entity_class = parent::getEntityClass();
$bundle = $bundle ?? $this
->getEntityTypeId();
$bundle_info = $this->entityTypeBundleInfo
->getBundleInfo($this->entityTypeId);
$bundle_class = $bundle_info[$bundle]['class'] ?? NULL;
if ($bundle_class) {
if (!class_exists($bundle_class)) {
throw new MissingBundleClassException($bundle_class);
}
elseif (!is_subclass_of($bundle_class, $entity_class)) {
throw new BundleClassInheritanceException($bundle_class, $entity_class);
}
return $bundle_class;
}
return $entity_class;
}
public function createWithSampleValues($bundle = FALSE, array $values = []) {
$forbidden_keys = [
$this->entityType
->getKey('id'),
];
if ($revision_key = $this->entityType
->getKey('revision')) {
$forbidden_keys[] = $revision_key;
}
if ($bundle_key = $this->entityType
->getKey('bundle')) {
if (!$bundle) {
throw new EntityStorageException("No entity bundle was specified");
}
if (!array_key_exists($bundle, $this->entityTypeBundleInfo
->getBundleInfo($this->entityTypeId))) {
throw new EntityStorageException(sprintf("Missing entity bundle. The \"%s\" bundle does not exist", $bundle));
}
$values[$bundle_key] = $bundle;
$forbidden_keys[] = $bundle_key;
}
$forbidden_keys = array_merge($forbidden_keys, array_keys($values));
$entity = $this
->create($values);
foreach ($entity as $field_name => $value) {
if (!in_array($field_name, $forbidden_keys, TRUE)) {
$entity
->get($field_name)
->generateSampleItems();
}
}
return $entity;
}
protected function initFieldValues(ContentEntityInterface $entity, array $values = [], array $field_names = []) {
foreach ($entity as $name => $field) {
if (!$field_names || isset($field_names[$name])) {
if (isset($values[$name])) {
$entity->{$name} = $values[$name];
}
elseif (!array_key_exists($name, $values)) {
$entity
->get($name)
->applyDefaultValue();
}
}
unset($values[$name]);
}
foreach ($values as $name => $value) {
$entity->{$name} = $value;
}
$this
->invokeHook('field_values_init', $entity);
}
protected function isAnyRevisionTranslated(TranslatableInterface $entity) {
return $entity
->getTranslationLanguages(FALSE) || $this
->isAnyStoredRevisionTranslated($entity);
}
protected function isAnyStoredRevisionTranslated(TranslatableInterface $entity) {
if ($entity
->isNew()) {
return FALSE;
}
if ($entity instanceof TranslationStatusInterface) {
foreach ($entity
->getTranslationLanguages(FALSE) as $langcode => $language) {
if ($entity
->getTranslationStatus($langcode) === TranslationStatusInterface::TRANSLATION_EXISTING) {
return TRUE;
}
}
}
$query = $this
->getQuery()
->condition($this->entityType
->getKey('id'), $entity
->id())
->condition($this->entityType
->getKey('default_langcode'), 0)
->accessCheck(FALSE)
->range(0, 1);
if ($entity
->getEntityType()
->isRevisionable()) {
$query
->allRevisions();
}
$result = $query
->execute();
return !empty($result);
}
public function createTranslation(ContentEntityInterface $entity, $langcode, array $values = []) {
$translation = $entity
->getTranslation($langcode);
$definitions = array_filter($translation
->getFieldDefinitions(), function (FieldDefinitionInterface $definition) {
return $definition
->isTranslatable();
});
$field_names = array_map(function (FieldDefinitionInterface $definition) {
return $definition
->getName();
}, $definitions);
$values[$this->langcodeKey] = $langcode;
$values[$this
->getEntityType()
->getKey('default_langcode')] = FALSE;
$this
->initFieldValues($translation, $values, $field_names);
$this
->invokeHook('translation_create', $translation);
return $translation;
}
public function createRevision(RevisionableInterface $entity, $default = TRUE, $keep_untranslatable_fields = NULL) {
$new_revision = clone $entity;
$original_keep_untranslatable_fields = $keep_untranslatable_fields;
if (!$entity
->isNew() && !$entity
->isDefaultRevision() && $entity
->isTranslatable() && $this
->isAnyRevisionTranslated($entity)) {
$active_langcode = $entity
->language()
->getId();
$skipped_field_names = array_flip($this
->getRevisionTranslationMergeSkippedFieldNames());
if (!isset($keep_untranslatable_fields)) {
$keep_untranslatable_fields = $entity
->isDefaultTranslation() && $entity
->isDefaultTranslationAffectedOnly();
}
$default_revision = $this
->load($entity
->id());
$translation_languages = $default_revision
->getTranslationLanguages();
foreach ($translation_languages as $langcode => $language) {
if ($langcode == $active_langcode) {
continue;
}
$default_revision_translation = $default_revision
->getTranslation($langcode);
$new_revision_translation = $new_revision
->hasTranslation($langcode) ? $new_revision
->getTranslation($langcode) : $new_revision
->addTranslation($langcode);
$sync_items = array_diff_key($keep_untranslatable_fields ? $default_revision_translation
->getTranslatableFields() : $default_revision_translation
->getFields(), $skipped_field_names);
foreach ($sync_items as $field_name => $items) {
$new_revision_translation
->set($field_name, $items
->getValue());
}
$new_revision_translation
->setRevisionTranslationAffected(NULL);
$keep_untranslatable_fields = TRUE;
}
foreach (array_diff_key($new_revision
->getTranslationLanguages(), $translation_languages) as $langcode => $language) {
if ($langcode !== $active_langcode) {
$new_revision
->removeTranslation($langcode);
}
}
$new_revision->original = clone $new_revision;
}
$new_revision
->setNewRevision();
$new_revision
->isDefaultRevision($default);
$new_revision
->setRevisionTranslationAffected(TRUE);
$arguments = [
$new_revision,
$entity,
$original_keep_untranslatable_fields,
];
$this
->moduleHandler()
->invokeAll($this->entityTypeId . '_revision_create', $arguments);
$this
->moduleHandler()
->invokeAll('entity_revision_create', $arguments);
return $new_revision;
}
protected function getRevisionTranslationMergeSkippedFieldNames() {
$entity_type = $this
->getEntityType();
$field_names = [
$entity_type
->getKey('revision'),
$entity_type
->getKey('revision_translation_affected'),
];
$field_names = array_merge($field_names, array_values($entity_type
->getRevisionMetadataKeys()));
return $field_names;
}
public function getLatestRevisionId($entity_id) {
if (!$this->entityType
->isRevisionable()) {
return NULL;
}
if (!isset($this->latestRevisionIds[$entity_id][LanguageInterface::LANGCODE_DEFAULT])) {
$result = $this
->getQuery()
->latestRevision()
->condition($this->entityType
->getKey('id'), $entity_id)
->accessCheck(FALSE)
->execute();
$this->latestRevisionIds[$entity_id][LanguageInterface::LANGCODE_DEFAULT] = key($result);
}
return $this->latestRevisionIds[$entity_id][LanguageInterface::LANGCODE_DEFAULT];
}
public function getLatestTranslationAffectedRevisionId($entity_id, $langcode) {
if (!$this->entityType
->isRevisionable()) {
return NULL;
}
if (!$this->entityType
->isTranslatable()) {
return $this
->getLatestRevisionId($entity_id);
}
if (!isset($this->latestRevisionIds[$entity_id][$langcode])) {
$result = $this
->getQuery()
->allRevisions()
->condition($this->entityType
->getKey('id'), $entity_id)
->condition($this->entityType
->getKey('revision_translation_affected'), 1, '=', $langcode)
->range(0, 1)
->sort($this->entityType
->getKey('revision'), 'DESC')
->accessCheck(FALSE)
->execute();
$this->latestRevisionIds[$entity_id][$langcode] = key($result);
}
return $this->latestRevisionIds[$entity_id][$langcode];
}
public function onFieldStorageDefinitionCreate(FieldStorageDefinitionInterface $storage_definition) {
}
public function onFieldStorageDefinitionUpdate(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
}
public function onFieldStorageDefinitionDelete(FieldStorageDefinitionInterface $storage_definition) {
}
public function onFieldDefinitionCreate(FieldDefinitionInterface $field_definition) {
}
public function onFieldDefinitionUpdate(FieldDefinitionInterface $field_definition, FieldDefinitionInterface $original) {
}
public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) {
}
public function purgeFieldData(FieldDefinitionInterface $field_definition, $batch_size) {
$items_by_entity = $this
->readFieldItemsToPurge($field_definition, $batch_size);
foreach ($items_by_entity as $items) {
$items
->delete();
$this
->purgeFieldItems($items
->getEntity(), $field_definition);
}
return count($items_by_entity);
}
protected abstract function readFieldItemsToPurge(FieldDefinitionInterface $field_definition, $batch_size);
protected abstract function purgeFieldItems(ContentEntityInterface $entity, FieldDefinitionInterface $field_definition);
public function finalizePurge(FieldStorageDefinitionInterface $storage_definition) {
}
protected function preLoad(array &$ids = NULL) {
$entities = [];
$preload_ids = $ids ?: [];
$preload_entities = $this
->moduleHandler()
->invokeAll('entity_preload', [
$preload_ids,
$this->entityTypeId,
]);
foreach ((array) $preload_entities as $entity) {
$entities[$entity
->id()] = $entity;
}
if ($entities) {
if ($ids !== NULL) {
$ids = array_keys(array_diff_key(array_flip($ids), $entities));
}
else {
$result = $this
->getQuery()
->accessCheck(FALSE)
->condition($this->entityType
->getKey('id'), array_keys($entities), 'NOT IN')
->execute();
$ids = array_values($result);
}
}
return $entities;
}
public function loadRevision($revision_id) {
$revisions = $this
->loadMultipleRevisions([
$revision_id,
]);
return $revisions[$revision_id] ?? NULL;
}
public function loadMultipleRevisions(array $revision_ids) {
$revisions = $this
->doLoadMultipleRevisionsFieldItems($revision_ids);
$entity_groups = [];
$entity_group_mapping = [];
foreach ($revisions as $revision) {
$entity_id = $revision
->id();
$entity_group_key = isset($entity_group_mapping[$entity_id]) ? $entity_group_mapping[$entity_id] + 1 : 0;
$entity_group_mapping[$entity_id] = $entity_group_key;
$entity_groups[$entity_group_key][$entity_id] = $revision;
}
foreach ($entity_groups as $entities) {
$this
->invokeStorageLoadHook($entities);
$this
->postLoad($entities);
}
if ($revision_ids) {
$flipped_ids = array_intersect_key(array_flip($revision_ids), $revisions);
$revisions = array_replace($flipped_ids, $revisions);
}
return $revisions;
}
protected abstract function doLoadMultipleRevisionsFieldItems($revision_ids);
protected function doSave($id, EntityInterface $entity) {
if ($entity
->isNew()) {
$entity
->enforceIsNew();
if ($this->entityType
->isRevisionable()) {
$entity
->setNewRevision();
}
$return = SAVED_NEW;
}
else {
$return = $entity
->isDefaultRevision() ? SAVED_UPDATED : FALSE;
}
$this
->populateAffectedRevisionTranslations($entity);
if ($this->entityType
->isRevisionable() && ($entity
->isNewRevision() || $entity
->isDefaultRevision())) {
$revision_default_key = $this->entityType
->getRevisionMetadataKey('revision_default');
$entity
->set($revision_default_key, $entity
->isDefaultRevision());
}
$this
->doSaveFieldItems($entity);
return $return;
}
protected abstract function doSaveFieldItems(ContentEntityInterface $entity, array $names = []);
protected function doPreSave(EntityInterface $entity) {
$entity
->updateOriginalValues();
if ($entity
->getEntityType()
->isRevisionable() && !$entity
->isNew() && empty($entity
->getLoadedRevisionId())) {
$entity
->updateLoadedRevisionId();
}
$id = parent::doPreSave($entity);
if (!$entity
->isNew()) {
if (empty($entity->original) || $entity
->id() != $entity->original
->id()) {
throw new EntityStorageException("Update existing '{$this->entityTypeId}' entity while changing the ID is not supported.");
}
if (!$entity
->isNewRevision() && $entity
->getRevisionId() != $entity
->getLoadedRevisionId()) {
throw new EntityStorageException("Update existing '{$this->entityTypeId}' entity revision while changing the revision ID is not supported.");
}
}
return $id;
}
protected function doPostSave(EntityInterface $entity, $update) {
if ($update && $this->entityType
->isTranslatable()) {
$this
->invokeTranslationHooks($entity);
}
parent::doPostSave($entity, $update);
if ($this->entityType
->isRevisionable()) {
$entity
->updateLoadedRevisionId();
$entity
->setNewRevision(FALSE);
}
}
protected function doDelete($entities) {
foreach ($entities as $entity) {
$this
->invokeFieldMethod('delete', $entity);
}
$this
->doDeleteFieldItems($entities);
}
protected abstract function doDeleteFieldItems($entities);
public function deleteRevision($revision_id) {
if ($revision = $this
->loadRevision($revision_id)) {
if ($revision
->isDefaultRevision()) {
throw new EntityStorageException('Default revision can not be deleted');
}
$this
->invokeFieldMethod('deleteRevision', $revision);
$this
->doDeleteRevisionFieldItems($revision);
$this
->invokeHook('revision_delete', $revision);
}
}
protected abstract function doDeleteRevisionFieldItems(ContentEntityInterface $revision);
protected function invokeTranslationHooks(ContentEntityInterface $entity) {
$translations = $entity
->getTranslationLanguages(FALSE);
$original_translations = $entity->original
->getTranslationLanguages(FALSE);
$all_translations = array_keys($translations + $original_translations);
foreach ($all_translations as $langcode) {
if (isset($translations[$langcode]) && !isset($original_translations[$langcode])) {
$this
->invokeHook('translation_insert', $entity
->getTranslation($langcode));
}
elseif (!isset($translations[$langcode]) && isset($original_translations[$langcode])) {
$this
->invokeHook('translation_delete', $entity->original
->getTranslation($langcode));
}
}
}
protected function invokeStorageLoadHook(array &$entities) {
if (!empty($entities)) {
$this
->moduleHandler()
->invokeAllWith('entity_storage_load', function (callable $hook, string $module) use (&$entities) {
$hook($entities, $this->entityTypeId);
});
$this
->moduleHandler()
->invokeAllWith($this->entityTypeId . '_storage_load', function (callable $hook, string $module) use (&$entities) {
$hook($entities);
});
}
}
protected function invokeHook($hook, EntityInterface $entity) {
switch ($hook) {
case 'presave':
$this
->invokeFieldMethod('preSave', $entity);
break;
case 'insert':
$this
->invokeFieldPostSave($entity, FALSE);
break;
case 'update':
$this
->invokeFieldPostSave($entity, TRUE);
break;
}
parent::invokeHook($hook, $entity);
}
protected function invokeFieldMethod($method, ContentEntityInterface $entity) {
$result = [];
$args = array_slice(func_get_args(), 2);
$langcodes = array_keys($entity
->getTranslationLanguages());
$current_entity_langcode = $entity
->language()
->getId();
if (reset($langcodes) != $current_entity_langcode) {
$langcodes = array_diff($langcodes, [
$current_entity_langcode,
]);
array_unshift($langcodes, $current_entity_langcode);
}
foreach ($langcodes as $langcode) {
$translation = $entity
->getTranslation($langcode);
$fields = $translation
->isDefaultTranslation() ? $translation
->getFields() : $translation
->getTranslatableFields();
foreach ($fields as $name => $items) {
$result[$langcode][$name] = $args ? call_user_func_array([
$items,
$method,
], $args) : $items
->{$method}();
}
}
if ($method == 'postSave' && !empty($entity->original)) {
$original_langcodes = array_keys($entity->original
->getTranslationLanguages());
foreach (array_diff($original_langcodes, $langcodes) as $removed_langcode) {
$translation = $entity->original
->getTranslation($removed_langcode);
if ($translation
->isDefaultTranslation()) {
if (method_exists($translation, 'setDefaultTranslationEnforced')) {
$translation
->setDefaultTranslationEnforced(FALSE);
}
else {
@trigger_error('Not providing a setDefaultTranslationEnforced() method when implementing \\Drupal\\Core\\TypedData\\TranslatableInterface is deprecated in drupal:10.2.0 and is required from drupal:11.0.0. See https://www.drupal.org/node/3376146', E_USER_DEPRECATED);
}
}
$fields = $translation
->getTranslatableFields();
foreach ($fields as $name => $items) {
$items
->delete();
}
}
}
return $result;
}
protected function invokeFieldPostSave(ContentEntityInterface $entity, $update) {
$resave = [];
foreach ($this
->invokeFieldMethod('postSave', $entity, $update) as $translation_results) {
$resave += array_filter($translation_results);
}
if ($resave) {
$this
->doSaveFieldItems($entity, array_keys($resave));
}
}
protected function hasFieldValueChanged(FieldDefinitionInterface $field_definition, ContentEntityInterface $entity, ContentEntityInterface $original) {
$field_name = $field_definition
->getName();
$langcodes = array_keys($entity
->getTranslationLanguages());
if ($langcodes !== array_keys($original
->getTranslationLanguages())) {
return TRUE;
}
foreach ($langcodes as $langcode) {
$items = $entity
->getTranslation($langcode)
->get($field_name)
->filterEmptyItems();
$original_items = $original
->getTranslation($langcode)
->get($field_name)
->filterEmptyItems();
if (!$items
->equals($original_items)) {
return TRUE;
}
}
return FALSE;
}
protected function populateAffectedRevisionTranslations(ContentEntityInterface $entity) {
if ($this->entityType
->isTranslatable() && $this->entityType
->isRevisionable()) {
$languages = $entity
->getTranslationLanguages();
foreach ($languages as $langcode => $language) {
$translation = $entity
->getTranslation($langcode);
$current_affected = $translation
->isRevisionTranslationAffected();
if (!isset($current_affected) || $entity
->isNewRevision() && !$translation
->isRevisionTranslationAffectedEnforced()) {
$new_affected = $translation
->hasTranslationChanges() ? TRUE : NULL;
$translation
->setRevisionTranslationAffected($new_affected);
$translation
->setRevisionTranslationAffectedEnforced(FALSE);
}
}
}
}
protected function cleanIds(array $ids, $entity_key = 'id') {
$definitions = $this->entityFieldManager
->getActiveFieldStorageDefinitions($this->entityTypeId);
$field_name = $this->entityType
->getKey($entity_key);
if ($field_name && $definitions[$field_name]
->getType() == 'integer') {
$ids = array_filter($ids, function ($id) {
return is_numeric($id) && $id == (int) $id;
});
$ids = array_map('intval', $ids);
}
return $ids;
}
protected function getFromPersistentCache(array &$ids = NULL) {
if (!$this->entityType
->isPersistentlyCacheable() || empty($ids)) {
return [];
}
$entities = [];
$cid_map = [];
foreach ($ids as $id) {
$cid_map[$id] = $this
->buildCacheId($id);
}
$cids = array_values($cid_map);
if ($cache = $this->cacheBackend
->getMultiple($cids)) {
foreach ($ids as $index => $id) {
$cid = $cid_map[$id];
if (isset($cache[$cid])) {
$entities[$id] = $cache[$cid]->data;
unset($ids[$index]);
}
}
}
return $entities;
}
protected function setPersistentCache($entities) {
if (!$this->entityType
->isPersistentlyCacheable()) {
return;
}
$cache_tags = [
$this->entityTypeId . '_values',
'entity_field_info',
];
$items = [];
foreach ($entities as $id => $entity) {
$items[$this
->buildCacheId($id)] = [
'data' => $entity,
'tags' => $cache_tags,
];
}
$this->cacheBackend
->setMultiple($items);
}
public function loadUnchanged($id) {
$entities = [];
$ids = [
$id,
];
parent::resetCache($ids);
$preloaded_entities = $this
->preLoad($ids);
if (!empty($preloaded_entities)) {
$entities += $preloaded_entities;
}
$entities += $this
->getFromPersistentCache($ids);
if (!$entities) {
$entities[$id] = $this
->load($id);
}
else {
$this
->postLoad($entities);
$this
->setStaticCache($entities);
}
return $entities[$id];
}
public function resetCache(array $ids = NULL) {
if ($ids) {
parent::resetCache($ids);
if ($this->entityType
->isPersistentlyCacheable()) {
$cids = [];
foreach ($ids as $id) {
unset($this->latestRevisionIds[$id]);
$cids[] = $this
->buildCacheId($id);
}
$this->cacheBackend
->deleteMultiple($cids);
}
}
else {
parent::resetCache();
if ($this->entityType
->isPersistentlyCacheable()) {
Cache::invalidateTags([
$this->entityTypeId . '_values',
]);
}
$this->latestRevisionIds = [];
}
}
}