Commit 1a5d1fc7 authored by alexpott's avatar alexpott

Issue #2225955 by tim.plunkett, Berdir: Improve the DX of writing entity storage classes.

parent 5e4b8a11
......@@ -55,6 +55,11 @@ class ConfigEntityType extends EntityType {
*/
protected $config_prefix;
/**
* {@inheritdoc}
*/
protected $static_cache = FALSE;
/**
* {@inheritdoc}
*/
......
......@@ -24,6 +24,12 @@ public function loadMultiple(array $ids = NULL) {
return array();
}
/**
* {@inheritdoc}
*/
protected function doLoadMultiple(array $ids = NULL) {
}
/**
* {@inheritdoc}
*/
......@@ -57,6 +63,12 @@ public function loadByProperties(array $values = array()) {
public function delete(array $entities) {
}
/**
* {@inheritdoc}
*/
protected function doDelete($entities) {
}
/**
* {@inheritdoc}
*/
......@@ -106,4 +118,16 @@ protected function readFieldItemsToPurge(EntityInterface $entity, FieldInstanceC
protected function purgeFieldItems(EntityInterface $entity, FieldInstanceConfigInterface $instance) {
}
/**
* {@inheritdoc}
*/
protected function doSave($id, EntityInterface $entity) {
}
/**
* {@inheritdoc}
*/
protected function has($id, EntityInterface $entity) {
}
}
......@@ -22,13 +22,6 @@ abstract class ContentEntityStorageBase extends EntityStorageBase implements Fie
*/
protected $bundleKey = FALSE;
/**
* Name of the entity class.
*
* @var string
*/
protected $entityClass;
/**
* Constructs a ContentEntityStorageBase object.
*
......@@ -39,7 +32,6 @@ public function __construct(EntityTypeInterface $entity_type) {
parent::__construct($entity_type);
$this->bundleKey = $this->entityType->getKey('bundle');
$this->entityClass = $this->entityType->getClass();
}
/**
......@@ -54,10 +46,7 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
/**
* {@inheritdoc}
*/
public function create(array $values = array()) {
$entity_class = $this->entityType->getClass();
$entity_class::preCreate($this, $values);
protected function doCreate(array $values) {
// We have to determine the bundle first.
$bundle = FALSE;
if ($this->bundleKey) {
......@@ -66,8 +55,7 @@ public function create(array $values = array()) {
}
$bundle = $values[$this->bundleKey];
}
$entity = new $entity_class(array(), $this->entityTypeId, $bundle);
$entity->enforceIsNew();
$entity = new $this->entityClass(array(), $this->entityTypeId, $bundle);
foreach ($entity as $name => $field) {
if (isset($values[$name])) {
......@@ -83,12 +71,6 @@ public function create(array $values = array()) {
foreach ($values as $name => $value) {
$entity->$name = $value;
}
$entity->postCreate($this);
// Modules might need to add or change the data initially held by the new
// entity object, for instance to fill-in default values.
$this->invokeHook('create', $entity);
return $entity;
}
......
......@@ -9,16 +9,6 @@
use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Language\Language;
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Uuid\Uuid;
use Drupal\field\FieldInfo;
use Drupal\field\FieldConfigUpdateForbiddenException;
use Drupal\field\FieldConfigInterface;
use Drupal\field\FieldInstanceConfigInterface;
use Drupal\field\Entity\FieldConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
......@@ -83,9 +73,6 @@ public function __construct(EntityTypeInterface $entity_type, Connection $databa
$this->database = $database;
$this->uuidService = $uuid_service;
// Check if the entity type supports IDs.
$this->idKey = $this->entityType->getKey('id');
// Check if the entity type supports UUIDs.
$this->uuidKey = $this->entityType->getKey('uuid');
}
......@@ -93,76 +80,14 @@ public function __construct(EntityTypeInterface $entity_type, Connection $databa
/**
* {@inheritdoc}
*/
public function loadMultiple(array $ids = NULL) {
$entities = array();
// Create a new variable which is either a prepared version of the $ids
// array for later comparison with the entity cache, or FALSE if no $ids
// were passed. The $ids array is reduced as items are loaded from cache,
// and we need to know if it's empty for this reason to avoid querying the
// database when all requested entities are loaded from cache.
$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
// Try to load entities from the static cache, if the entity type supports
// static caching.
if ($this->cache && $ids) {
$entities += $this->cacheGet($ids);
// If any entities were loaded, remove them from the ids still to load.
if ($passed_ids) {
$ids = array_keys(array_diff_key($passed_ids, $entities));
}
}
// Load any remaining entities from the database. This is the case if $ids
// is set to NULL (so we load all entities) or if there are any ids left to
// load.
if ($ids === NULL || $ids) {
// Build and execute the query.
$query_result = $this->buildQuery($ids)->execute();
if ($class = $this->entityType->getClass()) {
// We provide the necessary arguments for PDO to create objects of the
// specified entity class.
// @see \Drupal\Core\Entity\EntityInterface::__construct()
$query_result->setFetchMode(\PDO::FETCH_CLASS, $class, array(array(), $this->entityTypeId));
}
$queried_entities = $query_result->fetchAllAssoc($this->idKey);
}
// Pass all entities loaded from the database through $this->postLoad(),
// which attaches fields (if supported by the entity type) and calls the
// entity type specific load callback, for example hook_node_load().
if (!empty($queried_entities)) {
$this->postLoad($queried_entities);
$entities += $queried_entities;
}
if ($this->cache) {
// Add entities to the cache.
if (!empty($queried_entities)) {
$this->cacheSet($queried_entities);
}
}
protected function doLoadMultiple(array $ids = NULL) {
// Build and execute the query.
$records = $this
->buildQuery($ids)
->execute()
->fetchAllAssoc($this->idKey, \PDO::FETCH_ASSOC);
// Ensure that the returned array is ordered the same as the original
// $ids array if this was passed in and remove any invalid ids.
if ($passed_ids) {
// Remove any invalid ids from the array.
$passed_ids = array_intersect_key($passed_ids, $entities);
foreach ($entities as $entity) {
$passed_ids[$entity->id()] = $entity;
}
$entities = $passed_ids;
}
return $entities;
}
/**
* {@inheritdoc}
*/
public function load($id) {
$entities = $this->loadMultiple(array($id));
return isset($entities[$id]) ? $entities[$id] : NULL;
return $this->mapFromStorageRecords($records);
}
/**
......@@ -179,42 +104,16 @@ public function deleteRevision($revision_id) {
throw new \Exception('Database storage does not support revisions.');
}
/**
* {@inheritdoc}
*/
public function loadByProperties(array $values = array()) {
// Build a query to fetch the entity IDs.
$entity_query = \Drupal::entityQuery($this->entityTypeId);
$this->buildPropertyQuery($entity_query, $values);
$result = $entity_query->execute();
return $result ? $this->loadMultiple($result) : array();
}
/**
* Builds an entity query.
*
* @param \Drupal\Core\Entity\Query\QueryInterface $entity_query
* EntityQuery instance.
* @param array $values
* An associative array of properties of the entity, where the keys are the
* property names and the values are the values those properties must have.
*/
protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
foreach ($values as $name => $value) {
$entity_query->condition($name, $value);
}
}
/**
* Builds the query to load the entity.
*
* @param array|null $ids
* An array of entity IDs, or NULL to load all entities.
*
* @return SelectQuery
* @return \Drupal\Core\Database\Query\Select
* A SelectQuery object for loading the entity.
*/
protected function buildQuery($ids, $revision_id = FALSE) {
protected function buildQuery($ids) {
$query = $this->database->select($this->entityType->getBaseTable(), 'base');
$query->addTag($this->entityTypeId . '_load_multiple');
......@@ -230,29 +129,6 @@ protected function buildQuery($ids, $revision_id = FALSE) {
return $query;
}
/**
* {@inheritdoc}
*/
public function create(array $values = array()) {
$entity_class = $this->entityType->getClass();
$entity_class::preCreate($this, $values);
$entity = new $entity_class($values, $this->entityTypeId);
$entity->enforceIsNew();
// Assign a new UUID if there is none yet.
if ($this->uuidKey && !isset($entity->{$this->uuidKey})) {
$entity->{$this->uuidKey} = $this->uuidService->generate();
}
$entity->postCreate($this);
// Modules might need to add or change the data initially held by the new
// entity object, for instance to fill-in default values.
$this->invokeHook('create', $entity);
return $entity;
}
/**
* {@inheritdoc}
*/
......@@ -264,24 +140,8 @@ public function delete(array $entities) {
$transaction = $this->database->startTransaction();
try {
$entity_class = $this->entityType->getClass();
$entity_class::preDelete($this, $entities);
foreach ($entities as $entity) {
$this->invokeHook('predelete', $entity);
}
$ids = array_keys($entities);
$this->database->delete($this->entityType->getBaseTable())
->condition($this->idKey, $ids, 'IN')
->execute();
// Reset the cache as soon as the changes have been applied.
$this->resetCache($ids);
$entity_class::postDelete($this, $entities);
foreach ($entities as $entity) {
$this->invokeHook('delete', $entity);
}
parent::delete($entities);
// Ignore slave server temporarily.
db_ignore_slave();
}
......@@ -292,44 +152,30 @@ public function delete(array $entities) {
}
}
/**
* {@inheritdoc}
*/
protected function doDelete($entities) {
$ids = array_keys($entities);
$this->database->delete($this->entityType->getBaseTable())
->condition($this->idKey, $ids, 'IN')
->execute();
// Reset the cache as soon as the changes have been applied.
$this->resetCache($ids);
}
/**
* {@inheritdoc}
*/
public function save(EntityInterface $entity) {
$transaction = $this->database->startTransaction();
try {
// Load the stored entity, if any.
if (!$entity->isNew() && !isset($entity->original)) {
$id = $entity->id();
if ($entity->getOriginalId() !== NULL) {
$id = $entity->getOriginalId();
}
$entity->original = $this->loadUnchanged($id);
}
$entity->preSave($this);
$this->invokeHook('presave', $entity);
if (!$entity->isNew()) {
$return = drupal_write_record($this->entityType->getBaseTable(), $entity, $this->idKey);
$this->resetCache(array($entity->id()));
$entity->postSave($this, TRUE);
$this->invokeHook('update', $entity);
}
else {
$return = drupal_write_record($this->entityType->getBaseTable(), $entity);
// Reset general caches, but keep caches specific to certain entities.
$this->resetCache(array());
$entity->enforceIsNew(FALSE);
$entity->postSave($this, FALSE);
$this->invokeHook('insert', $entity);
}
$return = parent::save($entity);
// Ignore slave server temporarily.
db_ignore_slave();
unset($entity->original);
return $return;
}
catch (\Exception $e) {
......@@ -339,6 +185,30 @@ public function save(EntityInterface $entity) {
}
}
/**
* {@inheritdoc}
*/
protected function doSave($id, EntityInterface $entity) {
if (!$entity->isNew()) {
$return = drupal_write_record($this->entityType->getBaseTable(), $entity, $this->idKey);
$this->resetCache(array($entity->id()));
}
else {
$return = drupal_write_record($this->entityType->getBaseTable(), $entity);
// Reset general caches, but keep caches specific to certain entities.
$this->resetCache(array());
}
return $return;
}
/**
* {@inheritdoc}
*/
protected function has($id, EntityInterface $entity) {
return !$entity->isNew();
}
/**
* {@inheritdoc}
*/
......
......@@ -74,12 +74,12 @@ protected function buildQuery($ids, $revision_id = FALSE) {
/**
* {@inheritdoc}
*/
protected function postLoad(array &$queried_entities) {
protected function mapFromStorageRecords(array $records) {
// Prepare standard comment fields.
foreach ($queried_entities as &$record) {
foreach ($records as $record) {
$record->name = $record->uid ? $record->registered_name : $record->name;
}
parent::postLoad($queried_entities);
return parent::mapFromStorageRecords($records);
}
/**
......
......@@ -138,12 +138,10 @@ public function loadUpdatedCustomized(array $router_paths) {
);
$query_result = $query->execute();
if ($class = $this->entityType->getClass()) {
// We provide the necessary arguments for PDO to create objects of the
// specified entity class.
// @see \Drupal\Core\Entity\EntityInterface::__construct()
$query_result->setFetchMode(\PDO::FETCH_CLASS, $class, array(array(), $this->entityTypeId));
}
// We provide the necessary arguments for PDO to create objects of the
// specified entity class.
// @see \Drupal\Core\Entity\EntityInterface::__construct()
$query_result->setFetchMode(\PDO::FETCH_CLASS, $this->entityClass, array(array(), $this->entityTypeId));
return $query_result->fetchAllAssoc($this->idKey);
}
......
......@@ -79,23 +79,20 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
/**
* {@inheritdoc}
*/
function postLoad(array &$queried_users) {
foreach ($queried_users as $key => $record) {
$queried_users[$key]->roles = array();
function mapFromStorageRecords(array $records) {
foreach ($records as $record) {
$record->roles = array();
if ($record->uid) {
$queried_users[$record->uid]->roles[] = DRUPAL_AUTHENTICATED_RID;
$record->roles[] = DRUPAL_AUTHENTICATED_RID;
}
else {
$queried_users[$record->uid]->roles[] = DRUPAL_ANONYMOUS_RID;
$record->roles[] = DRUPAL_ANONYMOUS_RID;
}
}
// Add any additional roles from the database.
$this->addRoles($queried_users);
// Call the default postLoad() method. This will add fields and call
// hook_user_load().
parent::postLoad($queried_users);
$this->addRoles($records);
return parent::mapFromStorageRecords($records);
}
/**
......@@ -129,9 +126,11 @@ public function saveRoles(UserInterface $account) {
* {@inheritdoc}
*/
public function addRoles(array $users) {
$result = $this->database->query('SELECT rid, uid FROM {users_roles} WHERE uid IN (:uids)', array(':uids' => array_keys($users)));
foreach ($result as $record) {
$users[$record->uid]->roles[] = $record->rid;
if ($users) {
$result = $this->database->query('SELECT rid, uid FROM {users_roles} WHERE uid IN (:uids)', array(':uids' => array_keys($users)));
foreach ($result as $record) {
$users[$record->uid]->roles[] = $record->rid;
}
}
}
......
......@@ -110,6 +110,8 @@ public static function getInfo() {
/**
* {@inheritdoc}
*
* @covers ::__construct()
*/
protected function setUp() {
parent::setUp();
......@@ -128,6 +130,10 @@ protected function setUp() {
$this->entityType->expects($this->any())
->method('getConfigPrefix')
->will($this->returnValue('the_config_prefix'));
$this->entityType->expects($this->any())
->method('getClass')
->will($this->returnValue(get_class($this->getMockEntity())));
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
......@@ -171,12 +177,9 @@ protected function setUp() {
/**
* @covers ::create()
* @covers ::doCreate()
*/
public function testCreateWithPredefinedUuid() {
$this->entityType->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue(get_class($this->getMockEntity())));
$this->cacheBackend->expects($this->never())
->method('invalidateTags');
......@@ -197,14 +200,11 @@ public function testCreateWithPredefinedUuid() {
/**
* @covers ::create()
* @covers ::doCreate()
*
* @return \Drupal\Core\Entity\EntityInterface
*/
public function testCreate() {
$this->entityType->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue(get_class($this->getMockEntity())));
$this->cacheBackend->expects($this->never())
->method('invalidateTags');
......@@ -227,6 +227,7 @@ public function testCreate() {
/**
* @covers ::save()
* @covers ::doSave()
*
* @param \Drupal\Core\Entity\EntityInterface $entity
*
......@@ -252,7 +253,7 @@ public function testSaveInsert(EntityInterface $entity) {
$this->entityTypeId . 's' => TRUE, // List cache tag.
));
$this->configFactory->expects($this->once())
$this->configFactory->expects($this->exactly(2))
->method('get')
->with('the_config_prefix.foo')
->will($this->returnValue($config_object));
......@@ -285,6 +286,7 @@ public function testSaveInsert(EntityInterface $entity) {
/**
* @covers ::save()
* @covers ::doSave()
*
* @param \Drupal\Core\Entity\EntityInterface $entity
*
......@@ -315,7 +317,7 @@ public function testSaveUpdate(EntityInterface $entity) {
->method('loadMultiple')
->with(array('the_config_prefix.foo'))
->will($this->returnValue(array()));
$this->configFactory->expects($this->once())
$this->configFactory->expects($this->exactly(2))
->method('get')
->with('the_config_prefix.foo')
->will($this->returnValue($config_object));
......@@ -348,6 +350,7 @@ public function testSaveUpdate(EntityInterface $entity) {
/**
* @covers ::save()
* @covers ::doSave()
*
* @depends testSaveInsert
*/
......@@ -416,6 +419,7 @@ public function testSaveInvalid() {
/**
* @covers ::save()
* @covers ::doSave()
*
* @expectedException \Drupal\Core\Entity\EntityStorageException
*/
......@@ -447,6 +451,7 @@ public function testSaveDuplicate() {
/**
* @covers ::save()
* @covers ::doSave()
*
* @expectedException \Drupal\Core\Config\ConfigDuplicateUUIDException
* @expectedExceptionMessage when this UUID is already used for
......@@ -482,6 +487,7 @@ public function testSaveMismatch() {
/**
* @covers ::save()
* @covers ::doSave()
*/
public function testSaveNoMismatch() {
$config_object = $this->getMockBuilder('Drupal\Core\Config\Config')
......@@ -522,6 +528,7 @@ public function testSaveNoMismatch() {
/**
* @covers ::save()
* @covers ::doSave()
*
* @expectedException \Drupal\Core\Config\ConfigDuplicateUUIDException
* @expectedExceptionMessage when this entity already exists with UUID
......@@ -573,9 +580,6 @@ public function testSaveChangedUuid() {
->will($this->returnValue(array('foo')));
$entity = $this->getMockEntity(array('id' => 'foo'));
$this->entityType->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue(get_class($entity)));
$entity->set('uuid', 'baz');
$this->entityStorage->save($entity);
......@@ -584,7 +588,8 @@ public function testSaveChangedUuid() {
/**
* @covers ::load()
* @covers ::postLoad()
* @covers ::buildQuery()
* @covers ::mapFromStorageRecords()
* @covers ::doLoadMultiple()
*/
public function testLoad() {
$config_object = $this->getMockBuilder('Drupal\Core\Config\Config')
......@@ -605,10 +610,6 @@ public function testLoad() {
->method('getImplementations')
->will($this->returnValue(array()));
$this->entityType->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue(get_class($this->getMockEntity())));
$entity = $this->entityStorage->load('foo');
$this->assertInstanceOf('Drupal\Core\Entity\EntityInterface', $entity);
$this->assertSame('foo', $entity->id());
......@@ -617,7 +618,8 @@ public function testLoad() {
/**
* @covers ::loadMultiple()
* @covers ::postLoad()
* @covers ::buildQuery()
* @covers ::mapFromStorageRecords()
* @covers ::doLoadMultiple()
*/
public function testLoadMultipleAll() {
$foo_config_object = $this->getMockBuilder('Drupal\Core\Config\Config')
......@@ -647,10 +649,6 @@ public function testLoadMultipleAll() {
->method('getImplementations')
->will($this->returnValue(array()));
$this->entityType->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue(get_class($this->getMockEntity())));
$entities = $this->entityStorage->loadMultiple();
$expected['foo'] = 'foo';
$expected['bar'] = 'bar';
......@@ -664,7 +662,8 @@ public function testLoadMultipleAll() {
/**
* @covers ::loadMultiple()
* @covers ::postLoad()
* @covers ::buildQuery()