View source
<?php
namespace Drupal\Core\Entity;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\RefinableCacheableDependencyTrait;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
use Drupal\Core\Language\Language;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Link;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
abstract class EntityBase implements EntityInterface {
use RefinableCacheableDependencyTrait;
use DependencySerializationTrait {
__sleep as traitSleep;
}
protected $entityTypeId;
protected $enforceIsNew;
protected $typedData;
public function __construct(array $values, $entity_type) {
$this->entityTypeId = $entity_type;
foreach ($values as $key => $value) {
$this->{$key} = $value;
}
}
protected function entityTypeManager() {
return \Drupal::entityTypeManager();
}
protected function entityTypeBundleInfo() {
return \Drupal::service('entity_type.bundle.info');
}
protected function languageManager() {
return \Drupal::languageManager();
}
protected function uuidGenerator() {
return \Drupal::service('uuid');
}
public function id() {
return isset($this->id) ? $this->id : NULL;
}
public function uuid() {
return isset($this->uuid) ? $this->uuid : NULL;
}
public function isNew() {
return !empty($this->enforceIsNew) || !$this
->id();
}
public function enforceIsNew($value = TRUE) {
$this->enforceIsNew = $value;
return $this;
}
public function getEntityTypeId() {
return $this->entityTypeId;
}
public function bundle() {
return $this->entityTypeId;
}
public function label() {
if (($label_key = $this
->getEntityType()
->getKey('label')) && isset($this->{$label_key})) {
return $this->{$label_key};
}
}
public function toUrl($rel = 'canonical', array $options = []) {
if ($this
->id() === NULL) {
throw new EntityMalformedException(sprintf('The "%s" entity cannot have a URI as it does not have an ID', $this
->getEntityTypeId()));
}
$link_templates = $this
->linkTemplates();
if ($rel === 'revision' && $this instanceof RevisionableInterface && $this
->isDefaultRevision()) {
$rel = 'canonical';
}
if (isset($link_templates[$rel])) {
$route_parameters = $this
->urlRouteParameters($rel);
$route_name = "entity.{$this->entityTypeId}." . str_replace([
'-',
'drupal:',
], [
'_',
'',
], $rel);
$uri = new Url($route_name, $route_parameters);
}
else {
$bundle = $this
->bundle();
$bundles = $this
->entityTypeBundleInfo()
->getBundleInfo($this
->getEntityTypeId());
if (isset($bundles[$bundle]['uri_callback'])) {
$uri_callback = $bundles[$bundle]['uri_callback'];
}
elseif ($entity_uri_callback = $this
->getEntityType()
->getUriCallback()) {
$uri_callback = $entity_uri_callback;
}
if (isset($uri_callback) && is_callable($uri_callback)) {
$uri = call_user_func($uri_callback, $this);
}
else {
throw new UndefinedLinkTemplateException("No link template '{$rel}' found for the '{$this->getEntityTypeId()}' entity type");
}
}
$uri
->setOption('entity_type', $this
->getEntityTypeId())
->setOption('entity', $this);
if (!in_array($rel, [
'collection',
'add-page',
'add-form',
], TRUE)) {
$options += [
'language' => $this
->language(),
];
}
$uri_options = $uri
->getOptions();
$uri_options += $options;
return $uri
->setOptions($uri_options);
}
public function hasLinkTemplate($rel) {
$link_templates = $this
->linkTemplates();
return isset($link_templates[$rel]);
}
protected function linkTemplates() {
return $this
->getEntityType()
->getLinkTemplates();
}
public function toLink($text = NULL, $rel = 'canonical', array $options = []) {
if (!isset($text)) {
$text = $this
->label();
}
$url = $this
->toUrl($rel);
$options += $url
->getOptions();
$url
->setOptions($options);
return new Link($text, $url);
}
protected function urlRouteParameters($rel) {
$uri_route_parameters = [];
if (!in_array($rel, [
'collection',
'add-page',
'add-form',
], TRUE)) {
$uri_route_parameters[$this
->getEntityTypeId()] = $this
->id();
}
if ($rel === 'add-form' && $this
->getEntityType()
->hasKey('bundle')) {
$parameter_name = $this
->getEntityType()
->getBundleEntityType() ?: $this
->getEntityType()
->getKey('bundle');
$uri_route_parameters[$parameter_name] = $this
->bundle();
}
if ($this instanceof RevisionableInterface && strpos($rel, 'revision') === 0) {
$uri_route_parameters[$this
->getEntityTypeId() . '_revision'] = $this
->getRevisionId();
}
return $uri_route_parameters;
}
public function uriRelationships() {
return array_filter(array_keys($this
->linkTemplates()), function ($link_relation_type) {
try {
$this
->toUrl($link_relation_type)
->toString(TRUE)
->getGeneratedUrl();
} catch (RouteNotFoundException $e) {
return FALSE;
} catch (MissingMandatoryParametersException $e) {
return FALSE;
}
return TRUE;
});
}
public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
if ($operation == 'create') {
return $this
->entityTypeManager()
->getAccessControlHandler($this->entityTypeId)
->createAccess($this
->bundle(), $account, [], $return_as_object);
}
return $this
->entityTypeManager()
->getAccessControlHandler($this->entityTypeId)
->access($this, $operation, $account, $return_as_object);
}
public function language() {
if ($key = $this
->getEntityType()
->getKey('langcode')) {
$langcode = $this->{$key};
$language = $this
->languageManager()
->getLanguage($langcode);
if ($language) {
return $language;
}
}
$langcode = !empty($this->langcode) ? $this->langcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
$language = new Language([
'id' => $langcode,
]);
return $language;
}
public function save() {
$storage = $this
->entityTypeManager()
->getStorage($this->entityTypeId);
return $storage
->save($this);
}
public function delete() {
if (!$this
->isNew()) {
$this
->entityTypeManager()
->getStorage($this->entityTypeId)
->delete([
$this
->id() => $this,
]);
}
}
public function createDuplicate() {
$duplicate = clone $this;
$entity_type = $this
->getEntityType();
$duplicate->{$entity_type
->getKey('id')} = NULL;
$duplicate
->enforceIsNew();
if ($entity_type
->hasKey('uuid')) {
$duplicate->{$entity_type
->getKey('uuid')} = $this
->uuidGenerator()
->generate();
}
return $duplicate;
}
public function getEntityType() {
return $this
->entityTypeManager()
->getDefinition($this
->getEntityTypeId());
}
public function preSave(EntityStorageInterface $storage) {
if ($this
->getEntityType()
->getBundleOf()) {
if (mb_strlen($this
->id()) > EntityTypeInterface::BUNDLE_MAX_LENGTH) {
throw new ConfigEntityIdLengthException("Attempt to create a bundle with an ID longer than " . EntityTypeInterface::BUNDLE_MAX_LENGTH . " characters: {$this->id}().");
}
}
}
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
$this
->invalidateTagsOnSave($update);
}
public static function preCreate(EntityStorageInterface $storage, array &$values) {
}
public function postCreate(EntityStorageInterface $storage) {
}
public static function preDelete(EntityStorageInterface $storage, array $entities) {
}
public static function postDelete(EntityStorageInterface $storage, array $entities) {
static::invalidateTagsOnDelete($storage
->getEntityType(), $entities);
}
public static function postLoad(EntityStorageInterface $storage, array &$entities) {
}
public function referencedEntities() {
return [];
}
public function getCacheContexts() {
return $this->cacheContexts;
}
protected function getListCacheTagsToInvalidate() {
$tags = $this
->getEntityType()
->getListCacheTags();
if ($this
->getEntityType()
->hasKey('bundle')) {
$tags[] = $this
->getEntityTypeId() . '_list:' . $this
->bundle();
}
return $tags;
}
public function getCacheTagsToInvalidate() {
if ($this
->isNew()) {
return [];
}
return [
$this->entityTypeId . ':' . $this
->id(),
];
}
public function getCacheTags() {
if ($this->cacheTags) {
return Cache::mergeTags($this
->getCacheTagsToInvalidate(), $this->cacheTags);
}
return $this
->getCacheTagsToInvalidate();
}
public function getCacheMaxAge() {
return $this->cacheMaxAge;
}
public static function load($id) {
$entity_type_repository = \Drupal::service('entity_type.repository');
$entity_type_manager = \Drupal::entityTypeManager();
$storage = $entity_type_manager
->getStorage($entity_type_repository
->getEntityTypeFromClass(static::class));
return $storage
->load($id);
}
public static function loadMultiple(array $ids = NULL) {
$entity_type_repository = \Drupal::service('entity_type.repository');
$entity_type_manager = \Drupal::entityTypeManager();
$storage = $entity_type_manager
->getStorage($entity_type_repository
->getEntityTypeFromClass(static::class));
return $storage
->loadMultiple($ids);
}
public static function create(array $values = []) {
$entity_type_repository = \Drupal::service('entity_type.repository');
$entity_type_manager = \Drupal::entityTypeManager();
$storage = $entity_type_manager
->getStorage($entity_type_repository
->getEntityTypeFromClass(static::class));
return $storage
->create($values);
}
protected function invalidateTagsOnSave($update) {
$tags = $this
->getListCacheTagsToInvalidate();
if ($this
->hasLinkTemplate('canonical')) {
$tags = Cache::mergeTags($tags, [
'4xx-response',
]);
}
if ($update) {
$tags = Cache::mergeTags($tags, $this
->getCacheTagsToInvalidate());
}
Cache::invalidateTags($tags);
}
protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_type, array $entities) {
$tags = $entity_type
->getListCacheTags();
foreach ($entities as $entity) {
$tags = Cache::mergeTags($tags, $entity
->getCacheTagsToInvalidate());
$tags = Cache::mergeTags($tags, $entity
->getListCacheTagsToInvalidate());
}
Cache::invalidateTags($tags);
}
public function getOriginalId() {
return NULL;
}
public function setOriginalId($id) {
if ($id !== NULL) {
$this
->enforceIsNew(FALSE);
}
return $this;
}
public function toArray() {
return [];
}
public function getTypedData() {
if (!isset($this->typedData)) {
$class = \Drupal::typedDataManager()
->getDefinition('entity')['class'];
$this->typedData = $class::createFromEntity($this);
}
return $this->typedData;
}
public function __sleep() {
$this->typedData = NULL;
return $this
->traitSleep();
}
public function getConfigDependencyKey() {
return $this
->getEntityType()
->getConfigDependencyKey();
}
public function getConfigDependencyName() {
return $this
->getEntityTypeId() . ':' . $this
->bundle() . ':' . $this
->uuid();
}
public function getConfigTarget() {
return $this
->uuid();
}
}