Newer
Older
<?php
/**
* @file
* Contains \Drupal\Core\Entity\Entity.
*/
namespace Drupal\Core\Entity;
Alex Pott
committed
use Drupal\Core\Cache\Cache;
Dries Buytaert
committed
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
Angie Byron
committed
use Drupal\Component\Utility\String;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
Angie Byron
committed
use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
use Drupal\Core\Language\Language;
use Drupal\Core\Language\LanguageInterface;
Angie Byron
committed
use Drupal\Core\Link;
use Drupal\Core\Session\AccountInterface;
Angie Byron
committed
use Drupal\Core\Url;
catch
committed
/**
* Defines a base entity class.
*/
Dries Buytaert
committed
abstract class Entity implements EntityInterface {
Angie Byron
committed
use DependencySerializationTrait {
__sleep as traitSleep;
}
/**
* The entity type.
*
* @var string
*/
protected $entityTypeId;
/**
* Boolean indicating whether the entity should be forced to be new.
*
* @var bool
*/
protected $enforceIsNew;
Angie Byron
committed
/**
* A typed data object wrapping this entity.
*
* @var \Drupal\Core\TypedData\ComplexDataInterface
*/
protected $typedData;
/**
Dries Buytaert
committed
* Constructs an Entity object.
*
* @param array $values
* An array of values to set, keyed by property name. If the entity type
* has bundles, the bundle key has to be specified.
* @param string $entity_type
* The type of the entity to create.
*/
public function __construct(array $values, $entity_type) {
$this->entityTypeId = $entity_type;
// Set initial values.
foreach ($values as $key => $value) {
$this->$key = $value;
}
}
Alex Pott
committed
/**
* Returns the entity manager.
*
* @return \Drupal\Core\Entity\EntityManagerInterface
*/
protected function entityManager() {
return \Drupal::entityManager();
}
/**
* Returns the language manager.
*
* @return \Drupal\Core\Language\LanguageManagerInterface
*/
protected function languageManager() {
return \Drupal::languageManager();
}
/**
* Returns the UUID generator.
*
* @return \Drupal\Component\Uuid\UuidInterface
*/
protected function uuidGenerator() {
return \Drupal::service('uuid');
}
/**
* {@inheritdoc}
*/
public function id() {
return isset($this->id) ? $this->id : NULL;
}
/**
* {@inheritdoc}
*/
public function uuid() {
return isset($this->uuid) ? $this->uuid : NULL;
}
/**
* {@inheritdoc}
*/
public function isNew() {
return !empty($this->enforceIsNew) || !$this->id();
}
Angie Byron
committed
/**
* {@inheritdoc}
*/
public function enforceIsNew($value = TRUE) {
$this->enforceIsNew = $value;
Alex Pott
committed
return $this;
}
Angie Byron
committed
/**
* {@inheritdoc}
*/
public function getEntityTypeId() {
return $this->entityTypeId;
}
/**
* {@inheritdoc}
*/
public function bundle() {
return $this->entityTypeId;
}
/**
* {@inheritdoc}
*/
public function label() {
$label = NULL;
Alex Pott
committed
$entity_type = $this->getEntityType();
Alex Pott
committed
if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
$label = call_user_func($label_callback, $this);
}
Alex Pott
committed
elseif (($label_key = $entity_type->getKey('label')) && isset($this->{$label_key})) {
Alex Pott
committed
$label = $this->{$label_key};
}
return $label;
}
/**
Alex Pott
committed
* {@inheritdoc}
*/
Angie Byron
committed
public function urlInfo($rel = 'canonical', array $options = []) {
Alex Pott
committed
if ($this->isNew()) {
throw new EntityMalformedException(sprintf('The "%s" entity type has not been saved, and cannot have a URI.', $this->getEntityTypeId()));
}
Alex Pott
committed
// The links array might contain URI templates set in annotations.
Angie Byron
committed
$link_templates = $this->linkTemplates();
Alex Pott
committed
if (isset($link_templates[$rel])) {
$route_parameters = $this->urlRouteParameters($rel);
$route_name = "entity.{$this->entityTypeId}." . str_replace(array('-', 'drupal:'), array('_', ''), $rel);
$uri = new Url($route_name, $route_parameters);
Alex Pott
committed
}
else {
$bundle = $this->bundle();
// A bundle-specific callback takes precedence over the generic one for
// the entity type.
Alex Pott
committed
$bundles = $this->entityManager()->getBundleInfo($this->getEntityTypeId());
Alex Pott
committed
if (isset($bundles[$bundle]['uri_callback'])) {
$uri_callback = $bundles[$bundle]['uri_callback'];
}
Alex Pott
committed
elseif ($entity_uri_callback = $this->getEntityType()->getUriCallback()) {
$uri_callback = $entity_uri_callback;
}
Alex Pott
committed
// Invoke the callback to get the URI. If there is no callback, use the
// default URI format.
Alex Pott
committed
if (isset($uri_callback) && is_callable($uri_callback)) {
$uri = call_user_func($uri_callback, $this);
Alex Pott
committed
}
else {
Angie Byron
committed
throw new UndefinedLinkTemplateException(String::format('No link template "@rel" found for the "@entity_type" entity type', array(
'@rel' => $rel,
'@entity_type' => $this->getEntityTypeId(),
)));
Alex Pott
committed
}
}
// Pass the entity data to _url() so that alter functions do not need to
// look up this entity again.
Angie Byron
committed
$uri
->setOption('entity_type', $this->getEntityTypeId())
->setOption('entity', $this);
Angie Byron
committed
$uri_options = $uri->getOptions();
$uri_options += $options;
return $uri->setOptions($uri_options);
Alex Pott
committed
}
Alex Pott
committed
/**
* {@inheritdoc}
*/
public function getSystemPath($rel = 'canonical') {
Angie Byron
committed
if ($this->hasLinkTemplate($rel) && $uri = $this->urlInfo($rel)) {
return $uri->getInternalPath();
Alex Pott
committed
}
return '';
}
/**
* {@inheritdoc}
*/
public function hasLinkTemplate($rel) {
$link_templates = $this->linkTemplates();
return isset($link_templates[$rel]);
}
Angie Byron
committed
/**
* Returns an array link templates.
*
* @return array
* An array of link templates containing paths.
Angie Byron
committed
*/
protected function linkTemplates() {
return $this->getEntityType()->getLinkTemplates();
Angie Byron
committed
}
Angie Byron
committed
/**
* {@inheritdoc}
*/
public function link($text = NULL, $rel = 'canonical', array $options = []) {
if (is_null($text)) {
$text = $this->label();
}
$url = $this->urlInfo($rel);
$options += $url->getOptions();
$url->setOptions($options);
return (new Link($text, $url))->toString();
}
Alex Pott
committed
/**
* {@inheritdoc}
*/
public function url($rel = 'canonical', $options = array()) {
// While self::urlInfo() will throw an exception if the entity is new,
// the expected result for a URL is always a string.
Angie Byron
committed
if ($this->isNew() || !$this->hasLinkTemplate($rel)) {
Alex Pott
committed
return '';
}
Angie Byron
committed
$uri = $this->urlInfo($rel);
$options += $uri->getOptions();
$uri->setOptions($options);
return $uri->toString();
Alex Pott
committed
}
Alex Pott
committed
/**
* Returns an array of placeholders for this entity.
*
* Individual entity classes may override this method to add additional
* placeholders if desired. If so, they should be sure to replicate the
* property caching logic.
*
Alex Pott
committed
* @param string $rel
* The link relationship type, for example: canonical or edit-form.
*
Alex Pott
committed
* @return array
* An array of URI placeholders.
*/
Alex Pott
committed
protected function urlRouteParameters($rel) {
// The entity ID is needed as a route parameter.
$uri_route_parameters[$this->getEntityTypeId()] = $this->id();
return $uri_route_parameters;
}
Alex Pott
committed
/**
* {@inheritdoc}
*
* Returns a list of URI relationships supported by this entity.
*
* @return array
* An array of link relationships supported by this entity.
*/
public function uriRelationships() {
Angie Byron
committed
return array_keys($this->linkTemplates());
Alex Pott
committed
}
Dries Buytaert
committed
/**
* {@inheritdoc}
Dries Buytaert
committed
*/
catch
committed
public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
if ($operation == 'create') {
Alex Pott
committed
return $this->entityManager()
->getAccessControlHandler($this->entityTypeId)
catch
committed
->createAccess($this->bundle(), $account, [], $return_as_object);
}
catch
committed
return $this->entityManager()
->getAccessControlHandler($this->entityTypeId)
catch
committed
->access($this, $operation, LanguageInterface::LANGCODE_DEFAULT, $account, $return_as_object);
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
public function language() {
$langcode = $this->{$this->getEntityType()->getKey('langcode')};
$language = $this->languageManager()->getLanguage($langcode);
Angie Byron
committed
if (!$language) {
// Make sure we return a proper language object.
$langcode = $this->langcode ?: LanguageInterface::LANGCODE_NOT_SPECIFIED;
$language = new Language(array('id' => $langcode));
Angie Byron
committed
}
return $language;
}
/**
* {@inheritdoc}
*/
public function save() {
catch
committed
return $this->entityManager()->getStorage($this->entityTypeId)->save($this);
}
/**
* {@inheritdoc}
*/
public function delete() {
if (!$this->isNew()) {
catch
committed
$this->entityManager()->getStorage($this->entityTypeId)->delete(array($this->id() => $this));
}
}
/**
* {@inheritdoc}
*/
public function createDuplicate() {
$duplicate = clone $this;
Alex Pott
committed
$entity_type = $this->getEntityType();
// Reset the entity ID and indicate that this is a new entity.
Alex Pott
committed
$duplicate->{$entity_type->getKey('id')} = NULL;
$duplicate->enforceIsNew();
// Check if the entity type supports UUIDs and generate a new one if so.
Alex Pott
committed
if ($entity_type->hasKey('uuid')) {
Alex Pott
committed
$duplicate->{$entity_type->getKey('uuid')} = $this->uuidGenerator()->generate();
}
return $duplicate;
}
/**
* {@inheritdoc}
*/
public function getEntityType() {
Alex Pott
committed
return $this->entityManager()->getDefinition($this->getEntityTypeId());
}
/**
* {@inheritdoc}
*/
catch
committed
public function preSave(EntityStorageInterface $storage) {
// Check if this is an entity bundle.
if ($this->getEntityType()->getBundleOf()) {
// Throw an exception if the bundle ID is longer than 32 characters.
if (Unicode::strlen($this->id()) > EntityTypeInterface::BUNDLE_MAX_LENGTH) {
throw new ConfigEntityIdLengthException(String::format(
'Attempt to create a bundle with an ID longer than @max characters: @id.', array(
'@max' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
'@id' => $this->id(),
)
));
}
}
}
/**
* {@inheritdoc}
*/
catch
committed
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
Alex Pott
committed
$this->invalidateTagsOnSave($update);
}
/**
* {@inheritdoc}
*/
catch
committed
public static function preCreate(EntityStorageInterface $storage, array &$values) {
}
/**
* {@inheritdoc}
*/
catch
committed
public function postCreate(EntityStorageInterface $storage) {
}
/**
* {@inheritdoc}
*/
catch
committed
public static function preDelete(EntityStorageInterface $storage, array $entities) {
}
/**
* {@inheritdoc}
*/
catch
committed
public static function postDelete(EntityStorageInterface $storage, array $entities) {
static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
}
/**
* {@inheritdoc}
*/
catch
committed
public static function postLoad(EntityStorageInterface $storage, array &$entities) {
}
/**
* {@inheritdoc}
*/
public function referencedEntities() {
return array();
}
Alex Pott
committed
/**
* {@inheritdoc}
*/
public function getCacheTags() {
Alex Pott
committed
// @todo Add bundle-specific listing cache tag? https://drupal.org/node/2145751
return [$this->entityTypeId . ':' . $this->id()];
Alex Pott
committed
}
/**
* {@inheritdoc}
Angie Byron
committed
*
* @return static
* The entity object or NULL if there is no entity with the given ID.
*/
public static function load($id) {
Alex Pott
committed
$entity_manager = \Drupal::entityManager();
return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->load($id);
}
/**
* {@inheritdoc}
Angie Byron
committed
*
* @return static[]
* An array of entity objects indexed by their IDs.
*/
public static function loadMultiple(array $ids = NULL) {
Alex Pott
committed
$entity_manager = \Drupal::entityManager();
return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->loadMultiple($ids);
Angie Byron
committed
/**
* {@inheritdoc}
Angie Byron
committed
*
* @return static
* The entity object.
Angie Byron
committed
*/
public static function create(array $values = array()) {
Alex Pott
committed
$entity_manager = \Drupal::entityManager();
return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->create($values);
Angie Byron
committed
}
Alex Pott
committed
/**
* Invalidates an entity's cache tags upon save.
*
* @param bool $update
* TRUE if the entity has been updated, or FALSE if it has been inserted.
*/
protected function invalidateTagsOnSave($update) {
// An entity was created or updated: invalidate its list cache tags. (An
// updated entity may start to appear in a listing because it now meets that
// listing's filtering requirements. A newly created entity may start to
// appear in listings because it did not exist before.)
$tags = $this->getEntityType()->getListCacheTags();
Alex Pott
committed
if ($update) {
// An existing entity was updated, also invalidate its unique cache tag.
$tags = Cache::mergeTags($tags, $this->getCacheTags());
Alex Pott
committed
}
Cache::invalidateTags($tags);
}
/**
* Invalidates an entity's cache tags upon delete.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
Alex Pott
committed
* @param \Drupal\Core\Entity\EntityInterface[] $entities
* An array of entities.
*/
protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_type, array $entities) {
$tags = $entity_type->getListCacheTags();
Alex Pott
committed
foreach ($entities as $entity) {
// An entity was deleted: invalidate its own cache tag, but also its list
// cache tags. (A deleted entity may cause changes in a paged list on
// other pages than the one it's on. The one it's on is handled by its own
// cache tag, but subsequent list pages would not be invalidated, hence we
// must invalidate its list cache tags as well.)
$tags = Cache::mergeTags($tags, $entity->getCacheTags());
Alex Pott
committed
}
Cache::invalidateTags($tags);
}
Angie Byron
committed
/**
* {@inheritdoc}
*/
public function getOriginalId() {
// By default, entities do not support renames and do not have original IDs.
return NULL;
}
/**
* {@inheritdoc}
*/
public function setOriginalId($id) {
// By default, entities do not support renames and do not have original IDs.
Alex Pott
committed
// If the specified ID is anything except NULL, this should mark this entity
// as no longer new.
if ($id !== NULL) {
$this->enforceIsNew(FALSE);
}
Angie Byron
committed
return $this;
}
/**
* {@inheritdoc}
*/
public function toArray() {
return array();
}
Angie Byron
committed
/**
* {@inheritdoc}
*/
public function getTypedData() {
if (!isset($this->typedData)) {
$class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
$this->typedData = $class::createFromEntity($this);
}
return $this->typedData;
}
/**
* {@inheritdoc}
*/
public function __sleep() {
$this->typedData = NULL;
return $this->traitSleep();
}
Alex Pott
committed
/**
* {@inheritdoc}
*/
public function getConfigDependencyKey() {
return $this->getEntityType()->getConfigDependencyKey();
}
/**
* {@inheritdoc}
*/
public function getConfigDependencyName() {
return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
}