clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,62 @@
<?php
namespace Drupal\entity_reference_revisions\Commands;
use Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger;
use Drush\Commands\DrushCommands;
use Drush\Drush;
use Drush\Utils\StringUtils;
/**
* A Drush commandfile.
*/
class EntityReferenceRevisionsCommands extends DrushCommands {
/**
* The purger service.
*
* @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger
*/
protected $purger;
/**
* Constructs a ERRCommands object.
*
* @param \Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger $purger
*/
public function __construct(EntityReferenceRevisionsOrphanPurger $purger) {
$this->purger = $purger;
}
/**
* Orphan composite revision deletion.
*
* @param $types
* A comma delimited list of entity types to check for orphans. Omit to
* choose from a list.
* @usage drush err:purge paragraph
* Purge orphaned paragraphs.
*
* @command err:purge
* @aliases errp
*/
public function purge($types) {
$this->purger->setBatch(StringUtils::csvToArray($types));
drush_backend_batch_process();
}
/**
* @hook interact err:purge
*/
public function interact($input, $output) {
if (empty($input->getArgument('types'))) {
$choices = [];
foreach ($this->purger->getCompositeEntityTypes() as $entity_type) {
$choices[(string) $entity_type->id()] = (string) $entity_type->getLabel();
}
$selected = $this->io()->choice(dt("Choose the entity type to clear"), $choices);
$input->setArgument('types', $selected);
}
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\entity_reference_revisions;
/**
* Allows an entity to define whether it needs to be saved.
*/
interface EntityNeedsSaveInterface {
/**
* Checks whether the entity needs to be saved.
*
* @return bool
* TRUE if the entity needs to be saved.
*/
public function needsSave();
/**
* Sets the "needs save" flag on an entity.
*
* @param bool $needs_save
* TRUE if the entity needs to be saved.
*
* @return void
*/
public function setNeedsSave(bool $needs_save);
}
@@ -0,0 +1,39 @@
<?php
namespace Drupal\entity_reference_revisions;
use Drupal\Core\Entity\EntityStorageInterface;
/**
* Trait for EntityNeedsSaveInterface.
*/
trait EntityNeedsSaveTrait {
/**
* Whether the entity needs to be saved or not.
*
* @var bool
*/
protected $needsSave = FALSE;
/**
* {@inheritdoc}
*/
public function needsSave() {
return $this->needsSave;
}
/**
* {@inheritdoc}
*/
public function setNeedsSave($needs_save) {
$this->needsSave = $needs_save;
}
/**
* {@inheritdoc}
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
$this->setNeedsSave(FALSE);
}
}
@@ -0,0 +1,131 @@
<?php
namespace Drupal\entity_reference_revisions;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemListTranslationChangesInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
/**
* Defines a item list class for entity reference fields.
*/
class EntityReferenceRevisionsFieldItemList extends EntityReferenceFieldItemList implements EntityReferenceFieldItemListInterface {
/**
* {@inheritdoc}
*/
public function referencedEntities() {
$target_entities = [];
foreach ($this->list as $delta => $item) {
if ($item->entity) {
$target_entities[$delta] = $item->entity;
}
}
return $target_entities;
}
/**
* {@inheritdoc}
*/
public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
$default_value = parent::processDefaultValue($default_value, $entity, $definition);
if ($default_value) {
// Convert UUIDs to numeric IDs.
$uuids = array();
foreach ($default_value as $delta => $properties) {
if (isset($properties['target_uuid'])) {
$uuids[$delta] = $properties['target_uuid'];
}
}
if ($uuids) {
$target_type = $definition->getSetting('target_type');
$entity_ids = \Drupal::entityQuery($target_type)
->condition('uuid', $uuids, 'IN')
->accessCheck(TRUE)
->execute();
$entities = \Drupal::entityTypeManager()
->getStorage($target_type)
->loadMultiple($entity_ids);
$entity_uuids = array();
foreach ($entities as $id => $entity) {
$entity_uuids[$entity->uuid()] = $id;
}
foreach ($uuids as $delta => $uuid) {
if (isset($entity_uuids[$uuid])) {
$default_value[$delta]['target_id'] = $entity_uuids[$uuid];
unset($default_value[$delta]['target_uuid']);
}
else {
unset($default_value[$delta]);
}
}
}
// Ensure we return consecutive deltas, in case we removed unknown UUIDs.
$default_value = array_values($default_value);
}
return $default_value;
}
/**
* {@inheritdoc}
*/
public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {
$default_value = parent::defaultValuesFormSubmit($element, $form, $form_state);
// Convert numeric IDs to UUIDs to ensure config deployability.
$ids = array();
foreach ($default_value as $delta => $properties) {
$ids[] = $properties['target_revision_id'];
}
$entities = array();
foreach($ids as $id) {
$entities[$id] = \Drupal::entityTypeManager()
->getStorage($this->getSetting('target_type'))
->loadRevision($id);
}
foreach ($default_value as $delta => $properties) {
if (!empty($entities[$properties['target_revision_id']])) {
$default_value[$delta] = array(
'target_uuid' => $entities[$properties['target_revision_id']]->uuid(),
'target_revision_id' => $properties['target_revision_id'],
);
}
}
return $default_value;
}
/**
* {@inheritdoc}
*/
public function hasAffectingChanges(FieldItemListInterface $original_items, $langcode) {
// If there are fewer items, then it is a change.
if (count($this) < count($original_items)) {
return TRUE;
}
foreach ($this as $delta => $item) {
// If this is a different entity, then it is an affecting change.
if (!$original_items->offsetExists($delta) || $item->target_id != $original_items[$delta]->target_id) {
return TRUE;
}
// If it is the same entity, only consider it as having affecting changes
// if the target entity itself has changes.
if ($item->entity && $item->entity->hasTranslation($langcode) && $item->entity->getTranslation($langcode)->hasTranslationChanges()) {
return TRUE;
}
}
return FALSE;
}
}
@@ -0,0 +1,404 @@
<?php
namespace Drupal\entity_reference_revisions;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Manages orphan composite revision deletion.
*/
class EntityReferenceRevisionsOrphanPurger {
use StringTranslationTrait;
/**
* Parent is valid.
*/
const PARENT_VALID = 0;
/**
* Parent is invalid and usage can not be verified.
*/
const PARENT_INVALID_SKIP = 1;
/**
* Parent is invalid and paragraph is safe to delete.
*/
const PARENT_INVALID_DELETE = 2;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* The database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* List of already checked parents.
*
* @var bool[][]
*/
protected $validParents = [];
/**
* Constructs a EntityReferenceRevisionsOrphanManager object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Database\Connection $database
* The database service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, DateFormatterInterface $date_formatter, TimeInterface $time, Connection $database, MessengerInterface $messenger) {
$this->entityTypeManager = $entity_type_manager;
$this->entityFieldManager = $entity_field_manager;
$this->dateFormatter = $date_formatter;
$this->time = $time;
$this->database = $database;
$this->messenger = $messenger;
}
/**
* Deletes unused revision or an entity if there are no revisions remaining.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $composite_revision
* The composite revision.
*
* @return bool
* TRUE if an entity revision was deleted. Otherwise, FALSE.
*/
public function deleteUnusedRevision(ContentEntityInterface $composite_revision) {
// If this is the default revision of the composite entity, check if there
// are other revisions. If there are not, delete the composite entity.
$composite_storage = $this->entityTypeManager->getStorage($composite_revision->getEntityTypeId());
if ($composite_revision->isDefaultRevision()) {
$count = $composite_storage
->getQuery()
->accessCheck(FALSE)
->allRevisions()
->condition($composite_storage->getEntityType()->getKey('id'), $composite_revision->id())
->count()
->execute();
if ($count <= 1) {
$composite_revision->delete();
return TRUE;
}
}
else {
// Delete the revision if this is not the default one.
$composite_storage->deleteRevision($composite_revision->getRevisionId());
return TRUE;
}
return FALSE;
}
/**
* Batch operation for checking orphans for a given entity type.
*
* @param string $entity_type_id
* The entity type id, for example 'paragraph'.
* @param Iterable|array $context
* The context array.
*/
public function deleteOrphansBatchOperation($entity_type_id, &$context) {
$composite_type = $this->entityTypeManager->getDefinition($entity_type_id);
$composite_revision_key = $composite_type->getKey('revision');
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $composite_storage */
$composite_storage = $this->entityTypeManager->getStorage($entity_type_id);
$batch_size = Settings::get('entity_update_batch_size', 50);
if (empty($context['sandbox']['total'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_revision_id'] = -1;
$context['sandbox']['total'] = (int) $composite_storage->getQuery()
->allRevisions()
->accessCheck(FALSE)
->count()
->execute();
}
if (!isset($context['results'][$entity_type_id])) {
$context['results'][$entity_type_id]['entity_count'] = 0;
$context['results'][$entity_type_id]['revision_count'] = 0;
$context['results'][$entity_type_id]['start'] = $this->time->getRequestTime();
}
// Get the next batch of revision ids from the selected entity type.
// @todo Replace with an entity query on all revisions with a revision ID
// condition after https://www.drupal.org/project/drupal/issues/2766135.
$revision_table = $composite_type->getRevisionTable();
$entity_revision_ids = $this->database->select($revision_table, 'r')
->fields('r', [$composite_revision_key])
->range(0, $batch_size)
->orderBy($composite_revision_key)
->condition($composite_revision_key, $context['sandbox']['current_revision_id'], '>')
->execute()
->fetchCol();
/** @var \Drupal\Core\Entity\ContentEntityInterface $composite_revision */
foreach ($composite_storage->loadMultipleRevisions($entity_revision_ids) as $composite_revision) {
$context['sandbox']['progress']++;
$context['sandbox']['current_revision_id'] = $composite_revision->getRevisionId();
if ($this->isUsed($composite_revision)) {
continue;
}
if ($this->deleteUnusedRevision($composite_revision)) {
$context['results'][$entity_type_id]['revision_count']++;
if ($composite_revision->isDefaultRevision()) {
$context['results'][$entity_type_id]['entity_count']++;
}
}
}
// This entity type is completed if no new revision ids were found or the
// total is reached.
if ($entity_revision_ids && $context['sandbox']['progress'] < $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['total'];
}
else {
$context['finished'] = 1;
$context['results'][$entity_type_id]['end'] = $this->time->getRequestTime();
}
$interval = $this->dateFormatter->formatInterval($this->time->getRequestTime() - $context['results'][$entity_type_id]['start']);
$context['message'] = t('Checked @entity_type revisions for orphans: @current of @total in @interval (@deletions deleted)', [
'@entity_type' => $composite_type->getLabel(),
'@current' => $context['sandbox']['progress'],
'@total' => $context['sandbox']['total'],
'@interval' => $interval,
'@deletions' => $context['results'][$entity_type_id]['revision_count'],
]);
}
/**
* Batch dispatch submission finished callback.
*/
public static function batchSubmitFinished($success, $results, $operations) {
return \Drupal::service('entity_reference_revisions.orphan_purger')->doBatchSubmitFinished($success, $results, $operations);
}
/**
* Sets a batch for executing deletion of the orphaned composite entities.
*
* @param array $composite_entity_type_ids
* An array of composite entity type IDs to remove orphaned items for.
*/
public function setBatch(array $composite_entity_type_ids) {
if (empty($composite_entity_type_ids)) {
return;
}
$operations = [];
foreach ($composite_entity_type_ids as $entity_type_id) {
$operations[] = ['_entity_reference_revisions_orphan_purger_batch_dispatcher',
[
'entity_reference_revisions.orphan_purger:deleteOrphansBatchOperation',
$entity_type_id,
],
];
}
$batch = [
'operations' => $operations,
'finished' => [EntityReferenceRevisionsOrphanPurger::class, 'batchSubmitFinished'],
'title' => $this->t('Removing orphaned entities.'),
'progress_message' => $this->t('Processed @current of @total entity types.'),
'error_message' => $this->t('This batch encountered an error.'),
];
batch_set($batch);
}
/**
* Finished callback for the batch process.
*
* @param bool $success
* Whether the batch completed successfully.
* @param array $results
* The results array.
* @param array $operations
* The operations array.
*/
public function doBatchSubmitFinished($success, $results, $operations) {
if ($success) {
foreach ($results as $entity_type_id => $result) {
if ($this->entityTypeManager->hasDefinition($entity_type_id)) {
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
$interval = $this->dateFormatter->formatInterval($result['end'] - $result['start']);
$this->messenger->addMessage($this->t('@label: Deleted @revision_count revisions (@entity_count entities) in @interval.', [
'@label' => $entity_type->getLabel(),
'@revision_count' => $result['revision_count'],
'@entity_count' => $result['entity_count'],
'@interval' => $interval,
]));
}
}
}
else {
// $operations contains the operations that remained unprocessed.
$error_operation = reset($operations);
$this->messenger->addError($this->t('An error occurred while processing @operation with arguments : @args', [
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0], TRUE),
]));
}
}
/**
* Checks if the composite entity is used.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $composite_revision
* The composite revision.
*
* @return bool
* Whether the composite entity is used, FALSE if it is safe to delete.
*/
public function isUsed(ContentEntityInterface $composite_revision) {
$composite_type = $this->entityTypeManager->getDefinition($composite_revision->getEntityTypeId());
$parent_type_field = $composite_type->get('entity_revision_parent_type_field');
$parent_type = $composite_revision->get($parent_type_field)->value;
$parent_field_name_field = $composite_type->get('entity_revision_parent_field_name_field');
$parent_field_name = $composite_revision->get($parent_field_name_field)->value;
$status = $this->isValidParent($parent_type, $parent_field_name);
if ($status !== static::PARENT_VALID) {
return $status == static::PARENT_INVALID_SKIP ? TRUE : FALSE;
}
// Check if the revision is used in any revision of the parent, if that
// entity type supports revisions.
$query = $this->entityTypeManager->getStorage($parent_type)
->getQuery()
->condition("$parent_field_name.target_revision_id", $composite_revision->getRevisionId())
->range(0, 1)
->accessCheck(FALSE);
if ($this->entityTypeManager->getDefinition($parent_type)->isRevisionable()) {
$query = $query->allRevisions();
}
$revisions = $query->execute();
// If there are parent revisions where this revision is used, skip it.
return !empty($revisions);
}
/**
* Checks if the parent type/field is a valid combination that can be queried.
*
* @param string $parent_type
* Parent entity type ID.
* @param string $parent_field_name
* Parent field name.
*
* @return int
* static::PARENT_VALID, static::PARENT_INVALID_SKIP or
* static::PARENT_INVALID_DELETE.
*/
protected function isValidParent($parent_type, $parent_field_name) {
// There is not certainty that this revision is not used because we do not
// know what to query for if the parent fields are empty.
if ($parent_type == NULL) {
return static::PARENT_INVALID_SKIP;
}
if (isset($this->validParents[$parent_type][$parent_field_name])) {
return $this->validParents[$parent_type][$parent_field_name];
}
$status = static::PARENT_VALID;
// If the parent type does not exist anymore, the composite is not used.
if (!$this->entityTypeManager->hasDefinition($parent_type)) {
$status = static::PARENT_INVALID_DELETE;
}
else {
$parent_field_definitions = $this->entityFieldManager->getFieldStorageDefinitions($parent_type);
if (!isset($parent_field_definitions[$parent_field_name])) {
$status = static::PARENT_INVALID_DELETE;
}
// In case the parent field has no target revision ID key we can not be
// sure that this revision is not used anymore.
elseif (empty($parent_field_definitions[$parent_field_name]->getSchema()['columns']['target_revision_id'])) {
$status = static::PARENT_INVALID_SKIP;
}
}
$this->validParents[$parent_type][$parent_field_name] = $status;
return $status;
}
/**
* Returns a list of composite entity types.
*
* @return \Drupal\Core\Entity\EntityTypeInterface[]
* An array of composite entity types.
*/
public function getCompositeEntityTypes() {
$composite_entity_types = [];
$entity_types = $this->entityTypeManager->getDefinitions();
foreach ($entity_types as $entity_type) {
$has_parent_type_field = $entity_type->get('entity_revision_parent_type_field');
$has_parent_id_field = $entity_type->get('entity_revision_parent_id_field');
$has_parent_field_name_field = $entity_type->get('entity_revision_parent_field_name_field');
if ($has_parent_type_field && $has_parent_id_field && $has_parent_field_name_field) {
$composite_entity_types[] = $entity_type;
}
}
return $composite_entity_types;
}
}
@@ -0,0 +1,40 @@
<?php
namespace Drupal\entity_reference_revisions;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\entity_reference_revisions\Normalizer\EntityReferenceRevisionItemNormalizer;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
/**
* Service Provider for Entity Reference Revisions.
*/
class EntityReferenceRevisionsServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container) {
$modules = $container->getParameter('container.modules');
if (isset($modules['hal'])) {
// Hal module is enabled, add our new normalizer for entity reference
// revision items. For Drupal 10, the normalizer has been moved to the
// hal contrib module.
if (version_compare(\Drupal::VERSION, '10', '<')) {
$service_definition = new Definition(EntityReferenceRevisionItemNormalizer::class, array(
new Reference('hal.link_manager'),
new Reference('serializer.entity_resolver'),
));
// The priority must be higher than that of
// serializer.normalizer.entity_reference_item.hal in
// hal.services.yml.
$service_definition->setPublic(TRUE);
$service_definition->addTag('normalizer', array('priority' => 20));
$container->setDefinition('serializer.normalizer.entity_reference_revision_item', $service_definition);
}
}
}
}
@@ -0,0 +1,110 @@
<?php
namespace Drupal\entity_reference_revisions\Form;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class OrphanedCompositeEntitiesDeleteForm.
*
* @package Drupal\entity_reference_revisions\Form
*/
class OrphanedCompositeEntitiesDeleteForm extends FormBase {
/**
* The Entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* The entity reference revisions orphan purger service.
*
* @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger
*/
protected $purger;
/**
* OrphanedCompositeEntitiesDeleteForm constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The EntityTypeManager service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
* @param \Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger $purger
* The entity reference revisions orphan purger.
*/
public function __construct(EntityTypeManagerInterface $entity_manager, MessengerInterface $messenger, EntityReferenceRevisionsOrphanPurger $purger) {
$this->entityTypeManager = $entity_manager;
$this->messenger = $messenger;
$this->purger = $purger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('messenger'),
$container->get('entity_reference_revisions.orphan_purger')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'orphaned_composite_entities_delete_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$this->messenger->addWarning($this->t('The submission of the current form can cause the deletion of entities that are still used, backup all data first.'), 'warning');
$form['description'] = [
'#markup' => $this->t('Delete orphaned composite entities revisions that are no longer referenced. If there are no revisions left, the entity will be deleted as long as it is not used.'),
];
$options = [];
foreach ($this->purger->getCompositeEntityTypes() as $entity_type) {
$options[$entity_type->id()] = $entity_type->getLabel();
}
$form['composite_entity_types'] = [
'#type' => 'checkboxes',
'#required' => TRUE,
'#title' => $this->t('Select the entity types to check for orphans'),
'#options' => $options,
'#default_value' => array_keys($options),
];
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this->t('Delete orphaned composite revisions'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->purger->setBatch(array_filter($form_state->getValue('composite_entity_types')));
}
}
@@ -0,0 +1,43 @@
<?php
namespace Drupal\entity_reference_revisions\Normalizer;
use Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem;
use Drupal\hal\Normalizer\EntityReferenceItemNormalizer;
/**
* Defines a class for normalizing EntityReferenceRevisionItems.
*/
class EntityReferenceRevisionItemNormalizer extends EntityReferenceItemNormalizer {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = EntityReferenceRevisionsItem::class;
/**
* {@inheritdoc}
*/
protected function constructValue($data, $context) {
$value = parent::constructValue($data, $context);
if ($value) {
$value['target_revision_id'] = $data['target_revision_id'];
}
return $value;
}
/**
* {@inheritdoc}
*/
public function normalize($field_item, $format = NULL, array $context = array()) {
$data = parent::normalize($field_item, $format, $context);
$field_name = $field_item->getParent()->getName();
$entity = $field_item->getEntity();
$field_uri = $this->linkManager->getRelationUri($entity->getEntityTypeId(), $entity->bundle(), $field_name, $context);
$data['_embedded'][$field_uri][0]['target_revision_id'] = $field_item->target_revision_id;
return $data;
}
}
@@ -0,0 +1,130 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\DataType;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Plugin\DataType\EntityReference;
use Drupal\Core\Entity\RevisionableInterface;
/**
* Defines an 'entity_reference_revisions' data type.
*
* This serves as 'entity' property of entity reference field items and gets
* its value set from the parent, i.e. LanguageItem.
*
* The plain value of this reference is the entity object, i.e. an instance of
* \Drupal\Core\Entity\EntityInterface. For setting the value the entity object
* or the entity ID may be passed.
*
* Note that the definition of the referenced entity's type is required, whereas
* defining referencable entity bundle(s) is optional. A reference defining the
* type and bundle of the referenced entity can be created as following:
* @code
* $definition = \Drupal\Core\Entity\EntityDefinition::create($entity_type)
* ->addConstraint('Bundle', $bundle);
* \Drupal\Core\TypedData\DataReferenceDefinition::create('entity_revision')
* ->setTargetDefinition($definition);
* @endcode
*
* @DataType(
* id = "entity_revision_reference",
* label = @Translation("Entity reference revisions"),
* definition_class = "\Drupal\Core\TypedData\DataReferenceDefinition"
* )
*/
class EntityReferenceRevisions extends EntityReference {
/**
* The entity revision ID.
*
* @var integer|string
*/
protected $revision_id;
/**
* The entity ID.
*
* @var integer|string
*/
protected $id;
/**
* Returns the definition of the referenced entity.
*
* @return \Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface
* The reference target's definition.
*/
public function getTargetDefinition() {
return $this->definition->getTargetDefinition();
}
/**
* Checks whether the target entity has not been saved yet.
*
* @return bool
* TRUE if the entity is new, FALSE otherwise.
*/
public function isTargetNew() {
// If only an ID is given, the reference cannot be a new entity.
return !isset($this->id) && isset($this->target) && $this->target->getValue()->isNew();
}
/**
* {@inheritdoc}
*/
public function getTarget() {
if (!isset($this->target) && isset($this->id)) {
$storage = \Drupal::entityTypeManager()->getStorage($this->getTargetDefinition()->getEntityTypeId());
// By default always load the default revision, so caches get used.
$entity = $storage->load($this->id);
assert(is_null($entity) || $entity instanceof RevisionableInterface);
if ($entity !== NULL && $this->revision_id !== NULL && $entity->getRevisionId() != $this->revision_id) {
// A non-default revision is a referenced, so load this one.
$entity = $storage->loadRevision($this->revision_id);
}
$this->target = isset($entity) ? $entity->getTypedData() : NULL;
}
return $this->target;
}
/**
* {@inheritdoc}
*/
public function getTargetIdentifier() {
if (isset($this->id)) {
return $this->id;
}
elseif ($entity = $this->getValue()) {
return $entity->id();
}
}
/**
* {@inheritdoc}
*/
public function setValue($value, $notify = TRUE) {
unset($this->target);
unset($this->id);
unset($this->revision_id);
// Both the entity ID and the entity object may be passed as value. The
// reference may also be unset by passing NULL as value.
if (!isset($value)) {
$this->target = NULL;
}
elseif (is_object($value) && $value instanceof EntityInterface) {
$this->target = $value->getTypedData();
}
elseif (!is_scalar($value['target_id']) || !is_scalar($value['target_revision_id']) || $this->getTargetDefinition()->getEntityTypeId() === NULL) {
throw new \InvalidArgumentException('Value is not a valid entity.');
}
else {
$this->id = $value['target_id'];
$this->revision_id = $value['target_revision_id'];
}
// Notify the parent of any changes.
if ($notify && isset($this->parent)) {
$this->parent->onChange($this->name);
}
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\DataType;
use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\Core\Entity\Plugin\DataType\EntityAdapter;
/**
* Defines the "entity" data type.
*
* Instances of this class wrap entity objects and allow to deal with entities
* based upon the Typed Data API.
*
* In addition to the "entity" data type, this exposes derived
* "entity:$entity_type" and "entity:$entity_type:$bundle" data types.
*
* @DataType(
* id = "entity_revision",
* label = @Translation("Entity Revision"),
* description = @Translation("All kind of entities with revision information, e.g. nodes, comments or users."),
* deriver = "\Drupal\Core\Entity\Plugin\DataType\Deriver\EntityDeriver",
* definition_class = "\Drupal\entity_reference_revisions\TypedData\EntityRevisionDataDefinition"
* )
*/
class EntityRevisionsAdapter extends EntityAdapter implements \IteratorAggregate, ComplexDataInterface {
}
@@ -0,0 +1,30 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\Derivative;
use Drupal\entity_reference_revisions\Plugin\migrate\destination\EntityReferenceRevisions;
use Drupal\migrate\Plugin\Derivative\MigrateEntityRevision;
/**
* Class MigrateEntityReferenceRevisions
*/
class MigrateEntityReferenceRevisions extends MigrateEntityRevision {
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($basePluginDefinition) {
foreach ($this->entityDefinitions as $entityType => $entityInfo) {
if ($entityInfo->getKey('revision')) {
$this->derivatives[$entityType] = [
'id' => "entity_reference_revisions:$entityType",
'class' => EntityReferenceRevisions::class,
'requirements_met' => 1,
'provider' => $entityInfo->getProvider(),
];
}
}
return $this->derivatives;
}
}
@@ -0,0 +1,164 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'entity reference rendered entity' formatter.
*
* @FieldFormatter(
* id = "entity_reference_revisions_entity_view",
* label = @Translation("Rendered entity"),
* description = @Translation("Display the referenced entities rendered by entity_view()."),
* field_types = {
* "entity_reference_revisions"
* }
* )
*/
class EntityReferenceRevisionsEntityFormatter extends EntityReferenceRevisionsFormatterBase implements ContainerFactoryPluginInterface {
/**
* The logger factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
/**
* The entity display repository.
*
* @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
*/
protected $entityDisplayRepository;
/**
* Constructs a StringFormatter instance.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the formatter is associated.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Any third party settings settings.
* @param LoggerChannelFactoryInterface $logger_factory
* The logger factory.
* @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
* The entity display repository.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, LoggerChannelFactoryInterface $logger_factory, EntityDisplayRepositoryInterface $entity_display_repository) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->loggerFactory = $logger_factory;
$this->entityDisplayRepository = $entity_display_repository;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('logger.factory'),
$container->get('entity_display.repository')
);
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
'view_mode' => 'default',
'link' => FALSE,
) + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements['view_mode'] = array(
'#type' => 'select',
'#options' => $this->entityDisplayRepository->getViewModeOptions($this->getFieldSetting('target_type')),
'#title' => $this->t('View mode'),
'#default_value' => $this->getSetting('view_mode'),
'#required' => TRUE,
);
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$view_modes = $this->entityDisplayRepository->getViewModeOptions($this->getFieldSetting('target_type'));
$view_mode = $this->getSetting('view_mode');
$summary[] = $this->t('Rendered as @mode', array('@mode' => isset($view_modes[$view_mode]) ? $view_modes[$view_mode] : $view_mode));
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$view_mode = $this->getSetting('view_mode');
$elements = array();
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
// Protect ourselves from recursive rendering.
static $depth = 0;
$depth++;
if ($depth > 20) {
$this->loggerFactory->get('entity')->error('Recursive rendering detected when rendering entity @entity_type @entity_id. Aborting rendering.', array('@entity_type' => $entity->getEntityTypeId(), '@entity_id' => $entity->id()));
return $elements;
}
$view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
$elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()->getId());
// Add a resource attribute to set the mapping property's value to the
// entity's url. Since we don't know what the markup of the entity will
// be, we shouldn't rely on it for structured data such as RDFa.
if (!empty($items[$delta]->_attributes) && !$entity->isNew() && $entity->hasLinkTemplate('canonical')) {
$items[$delta]->_attributes += array('resource' => $entity->toUrl()->toString());
}
$depth = 0;
}
return $elements;
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
// This formatter is only available for entity types that have a view
// builder.
$target_type = $field_definition->getFieldStorageDefinition()->getSetting('target_type');
return \Drupal::entityTypeManager()->getDefinition($target_type)->hasViewBuilderClass();
}
}
@@ -0,0 +1,30 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
/**
* Parent plugin for entity reference formatters.
*/
abstract class EntityReferenceRevisionsFormatterBase extends EntityReferenceFormatterBase {
/**
* {@inheritdoc}
*/
public function prepareView(array $entities_items) {
// Entity revision loading currently has no static/persistent cache and no
// multiload. As entity reference checks _loaded, while we don't want to
// indicate a loaded entity, when there is none, as it could cause errors,
// we actually load the entity and set the flag.
foreach ($entities_items as $items) {
foreach ($items as $item) {
if ($item->entity) {
$item->_loaded = TRUE;
}
}
}
}
}
@@ -0,0 +1,111 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'entity reference revisions label' formatter.
*
* @FieldFormatter(
* id = "entity_reference_revisions_label",
* label = @Translation("Label"),
* description = @Translation("Display the label of the referenced entity revisions."),
* field_types = {
* "entity_reference_revisions"
* }
* )
*/
class EntityReferenceRevisionsLabelFormatter extends EntityReferenceRevisionsFormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'link' => TRUE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements['link'] = [
'#title' => $this->t('Link label to the referenced entity'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('link'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$summary[] = $this->getSetting('link') ? $this->t('Link to the referenced entity') : $this->t('No link');
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$output_as_link = $this->getSetting('link');
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
$label = $entity->label();
// If the link is to be displayed and the entity has a uri, display a
// link.
if ($output_as_link && !$entity->isNew()) {
try {
$uri = $entity->toUrl('revision');
}
catch (UndefinedLinkTemplateException $e) {
// This exception is thrown by \Drupal\Core\Entity\Entity::toUrl()
// and it means that the entity type doesn't have a link template nor
// a valid "uri_callback", so don't bother trying to output a link for
// the rest of the referenced entities.
$output_as_link = FALSE;
}
}
if ($output_as_link && isset($uri) && !$entity->isNew()) {
$elements[$delta] = [
'#type' => 'link',
'#title' => $label,
'#url' => $uri,
'#options' => $uri->getOptions(),
];
if (!empty($items[$delta]->_attributes)) {
$elements[$delta]['#options'] += ['attributes' => []];
$elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes;
// Unset field item attributes since they have been included in the
// formatter output and shouldn't be rendered in the field template.
unset($items[$delta]->_attributes);
}
}
else {
$elements[$delta] = ['#plain_text' => $label];
}
$elements[$delta]['#cache']['tags'] = $entity->getCacheTags();
}
return $elements;
}
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity) {
return $entity->access('view label', NULL, TRUE);
}
}
@@ -0,0 +1,537 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\Field\FieldType;
use Drupal\Component\Utility\Random;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Entity\TranslatableRevisionableInterface;
use Drupal\Core\Entity\TypedData\EntityDataDefinition;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\Field\PreconfiguredFieldUiOptionsInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataReferenceDefinition;
use Drupal\Core\TypedData\DataReferenceTargetDefinition;
use Drupal\Core\TypedData\OptionsProviderInterface;
use Drupal\entity_reference_revisions\EntityNeedsSaveInterface;
/**
* Defines the 'entity_reference_revisions' entity field type.
*
* Supported settings (below the definition's 'settings' key) are:
* - target_type: The entity type to reference. Required.
* - target_bundle: (optional): If set, restricts the entity bundles which may
* may be referenced. May be set to an single bundle, or to an array of
* allowed bundles.
*
* @FieldType(
* id = "entity_reference_revisions",
* label = @Translation("Entity reference revisions"),
* description = @Translation("An entity field containing an entity reference to a specific revision."),
* category = "reference",
* no_ui = FALSE,
* class = "\Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem",
* list_class = "\Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList",
* default_formatter = "entity_reference_revisions_entity_view",
* default_widget = "entity_reference_revisions_autocomplete"
* )
*/
class EntityReferenceRevisionsItem extends EntityReferenceItem implements OptionsProviderInterface, PreconfiguredFieldUiOptionsInterface {
/**
* {@inheritdoc}
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$entity_types = \Drupal::entityTypeManager()->getDefinitions();
$options = array();
foreach ($entity_types as $entity_type) {
if ($entity_type->isRevisionable()) {
$options[$entity_type->id()] = $entity_type->getLabel();
}
}
$element['target_type'] = array(
'#type' => 'select',
'#title' => $this->t('Type of item to reference'),
'#options' => $options,
'#default_value' => $this->getSetting('target_type'),
'#required' => TRUE,
'#disabled' => $has_data,
'#size' => 1,
);
return $element;
}
/**
* {@inheritdoc}
*/
public static function getPreconfiguredOptions() {
$options = array();
// Add all the commonly referenced entity types as distinct pre-configured
// options.
$entity_types = \Drupal::entityTypeManager()->getDefinitions();
$common_references = array_filter($entity_types, function (EntityTypeInterface $entity_type) {
return $entity_type->get('common_reference_revisions_target') && $entity_type->isRevisionable();
});
/** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */
foreach ($common_references as $entity_type) {
$options[$entity_type->id()] = [
'label' => t('@entity_type (revisions)', ['@entity_type' => $entity_type->getLabel()]),
'field_storage_config' => [
'settings' => [
'target_type' => $entity_type->id(),
]
]
];
// Change the label on Drupal 10.1+.
if (version_compare(\Drupal::VERSION, '10.1.999', '<')) {
$options[$entity_type->id()]['label'] = $entity_type->getLabel();
}
$default_reference_settings = $entity_type->get('default_reference_revision_settings');
if (is_array($default_reference_settings)) {
$options[$entity_type->id()] = array_merge($options[$entity_type->id()], $default_reference_settings);
}
}
return $options;
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$settings = $field_definition->getSettings();
$target_type_info = \Drupal::entityTypeManager()->getDefinition($settings['target_type']);
$properties = parent::propertyDefinitions($field_definition);
if ($target_type_info->getKey('revision')) {
$target_revision_id_definition = DataReferenceTargetDefinition::create('integer')
->setLabel(t('@label revision ID', array('@label' => $target_type_info->getLabel())))
->setSetting('unsigned', TRUE);
$target_revision_id_definition->setRequired(TRUE);
$properties['target_revision_id'] = $target_revision_id_definition;
}
$properties['entity'] = DataReferenceDefinition::create('entity_revision')
->setLabel($target_type_info->getLabel())
->setDescription(t('The referenced entity revision'))
// The entity object is computed out of the entity ID.
->setComputed(TRUE)
->setReadOnly(FALSE)
->setTargetDefinition(EntityDataDefinition::create($settings['target_type']));
return $properties;
}
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$target_type = $field_definition->getSetting('target_type');
$target_type_info = \Drupal::entityTypeManager()->getDefinition($target_type);
$schema = parent::schema($field_definition);
if ($target_type_info->getKey('revision')) {
$schema['columns']['target_revision_id'] = array(
'description' => 'The revision ID of the target entity.',
'type' => 'int',
'unsigned' => TRUE,
);
$schema['indexes']['target_revision_id'] = array('target_revision_id');
}
return $schema;
}
/**
* {@inheritdoc}
*/
public function setValue($values, $notify = TRUE) {
if (isset($values) && !is_array($values)) {
// If either a scalar or an object was passed as the value for the item,
// assign it to the 'entity' property since that works for both cases.
$this->set('entity', $values, $notify);
}
else {
// Load the latest revision by default, if no revision has been passed-in
// but we have a target ID.
if (is_array($values) && !empty($values['target_id']) && !array_key_exists('target_revision_id', $values)) {
$target_type_id = $this->getSetting('target_type');
$storage = \Drupal::entityTypeManager()->getStorage($target_type_id);
$entity = $storage->load($values['target_id']);
assert($entity instanceof RevisionableInterface);
$values['target_revision_id'] = $entity->getRevisionId();
}
parent::setValue($values, FALSE);
// Support setting the field item with only one property, but make sure
// values stay in sync if only property is passed.
// NULL is a valid value, so we use array_key_exists().
if (is_array($values) && array_key_exists('target_id', $values) && !isset($values['entity'])) {
$this->onChange('target_id', FALSE);
}
elseif (is_array($values) && array_key_exists('target_revision_id', $values) && !isset($values['entity'])) {
$this->onChange('target_revision_id', FALSE);
}
elseif (is_array($values) && !array_key_exists('target_id', $values) && !array_key_exists('target_revision_id', $values) && isset($values['entity'])) {
$this->onChange('entity', FALSE);
}
elseif (is_array($values) && array_key_exists('target_id', $values) && isset($values['entity'])) {
// If both properties are passed, verify the passed values match. The
// only exception we allow is when we have a new entity: in this case
// its actual id and target_id will be different, due to the new entity
// marker.
$entity_id = $this->get('entity')->getTargetIdentifier();
// If the entity has been saved and we're trying to set both the
// target_id and the entity values with a non-null target ID, then the
// value for target_id should match the ID of the entity value.
if (!$this->entity->isNew() && $values['target_id'] !== NULL && ($entity_id != $values['target_id'])) {
throw new \InvalidArgumentException('The target id and entity passed to the entity reference item do not match.');
}
}
// Notify the parent if necessary.
if ($notify && $this->getParent()) {
$this->getParent()->onChange($this->getName());
}
}
}
/**
* {@inheritdoc}
*/
public function getValue() {
$values = parent::getValue();
if ($this->entity instanceof EntityNeedsSaveInterface && $this->entity->needsSave()) {
$values['entity'] = $this->entity;
}
return $values;
}
/**
* {@inheritdoc}
*/
public function onChange($property_name, $notify = TRUE) {
// Make sure that the target ID and the target property stay in sync.
if ($property_name == 'entity') {
$property = $this->get('entity');
$target_id = $property->isTargetNew() ? NULL : $property->getTargetIdentifier();
$this->writePropertyValue('target_id', $target_id);
$this->writePropertyValue('target_revision_id', $property->getValue()->getRevisionId());
}
elseif ($property_name == 'target_id' && $this->target_id != NULL && $this->target_revision_id) {
$this->writePropertyValue('entity', array(
'target_id' => $this->target_id,
'target_revision_id' => $this->target_revision_id,
));
}
elseif ($property_name == 'target_revision_id' && $this->target_revision_id && $this->target_id) {
$this->writePropertyValue('entity', array(
'target_id' => $this->target_id,
'target_revision_id' => $this->target_revision_id,
));
}
if ($notify && isset($this->parent)) {
$this->parent->onChange($this->name);
}
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
// Avoid loading the entity by first checking the 'target_id'.
if ($this->target_id !== NULL && $this->target_revision_id !== NULL) {
return FALSE;
}
if ($this->entity && $this->entity instanceof EntityInterface) {
return FALSE;
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function preSave() {
$has_new = $this->hasNewEntity();
// If it is a new entity, parent will save it.
parent::preSave();
$is_affected = TRUE;
if (!$has_new) {
// Create a new revision if it is a composite entity in a host with a new
// revision.
$host = $this->getEntity();
$needs_save = $this->entity instanceof EntityNeedsSaveInterface && $this->entity->needsSave();
// The item is considered to be affected if the field is either
// untranslatable or there are translation changes. This ensures that for
// translatable fields, a new revision of the referenced entity is only
// created for the affected translations and that the revision ID does not
// change on the unaffected translations. In turn, the host entity is not
// marked as affected for these translations.
$is_affected = !$this->getFieldDefinition()->isTranslatable() || ($host instanceof TranslatableRevisionableInterface && $host->hasTranslationChanges());
if ($is_affected && !$host->isNew() && $this->entity && $this->entity->getEntityType()->get('entity_revision_parent_id_field')) {
if ($host->isNewRevision()) {
$this->entity->setNewRevision();
$needs_save = TRUE;
}
// Additionally ensure that the default revision state is kept in sync.
if ($this->entity && $host->isDefaultRevision() != $this->entity->isDefaultRevision()) {
$this->entity->isDefaultRevision($host->isDefaultRevision());
$needs_save = TRUE;
}
}
if ($needs_save) {
// Because ContentEntityBase::hasTranslationChanges() does not check for
// EntityReferenceRevisionsFieldItemList::hasAffectingChanges() on field
// items that are not translatable, hidden on translation forms and not
// in the default translation, this has to be handled here by setting
// setRevisionTranslationAffected on host translations that holds a
// reference that has been changed.
if ($is_affected && $host instanceof TranslatableRevisionableInterface) {
$languages = $host->getTranslationLanguages();
foreach ($languages as $langcode => $language) {
$translation = $host->getTranslation($langcode);
if ($this->entity->hasTranslation($langcode) && $this->entity->getTranslation($langcode)->hasTranslationChanges() && $this->target_revision_id != $this->entity->getRevisionId()) {
$translation->setRevisionTranslationAffected(TRUE);
$translation->setRevisionTranslationAffectedEnforced(TRUE);
}
}
}
$this->entity->save();
}
}
if ($this->entity && $is_affected) {
$this->target_revision_id = $this->entity->getRevisionId();
}
}
/**
* {@inheritdoc}
*/
public function postSave($update) {
parent::postSave($update);
$needs_save = FALSE;
// If any of entity, parent type or parent id is missing then return.
if (!$this->entity || !$this->entity->getEntityType()->get('entity_revision_parent_type_field') || !$this->entity->getEntityType()->get('entity_revision_parent_id_field')) {
return;
}
$entity = $this->entity;
$parent_entity = $this->getEntity();
// If the entity has a parent field name get the key.
if ($entity->getEntityType()->get('entity_revision_parent_field_name_field')) {
$parent_field_name = $entity->getEntityType()->get('entity_revision_parent_field_name_field');
// If parent field name has changed then set it.
if ($entity->get($parent_field_name)->value != $this->getFieldDefinition()->getName()) {
$entity->set($parent_field_name, $this->getFieldDefinition()->getName());
$needs_save = TRUE;
}
}
// Keep in sync the translation languages between the parent and the child.
// For non translatable fields we have to do this in ::preSave but for
// translatable fields we have all the information we need in ::delete.
if (isset($parent_entity->original) && !$this->getFieldDefinition()->isTranslatable()) {
$langcodes = array_keys($parent_entity->getTranslationLanguages());
$original_langcodes = array_keys($parent_entity->original->getTranslationLanguages());
if ($removed_langcodes = array_diff($original_langcodes, $langcodes)) {
foreach ($removed_langcodes as $removed_langcode) {
if ($entity->hasTranslation($removed_langcode) && $entity->getUntranslated()->language()->getId() != $removed_langcode) {
$entity->removeTranslation($removed_langcode);
}
}
$needs_save = TRUE;
}
}
$parent_type = $entity->getEntityType()->get('entity_revision_parent_type_field');
$parent_id = $entity->getEntityType()->get('entity_revision_parent_id_field');
// If the parent type has changed then set it.
if ($entity->get($parent_type)->value != $parent_entity->getEntityTypeId()) {
$entity->set($parent_type, $parent_entity->getEntityTypeId());
$needs_save = TRUE;
}
// If the parent id has changed then set it.
if ($entity->get($parent_id)->value != $parent_entity->id()) {
$entity->set($parent_id, $parent_entity->id());
$needs_save = TRUE;
}
if ($needs_save) {
// Check if any of the keys has changed, save it, do not create a new
// revision.
$entity->setNewRevision(FALSE);
$entity->save();
}
}
/**
* {@inheritdoc}
*/
public function deleteRevision() {
$child = $this->entity;
// Return early, and do not delete the child revision, when the child
// revision is either:
// 1: Missing.
// 2: A default revision.
if (!$child || $child->isDefaultRevision()) {
return;
}
$host = $this->getEntity();
$field_name = $this->getFieldDefinition()->getName() . '.target_revision_id';
$all_revisions = \Drupal::entityQuery($host->getEntityTypeId())
->condition($field_name, $child->getRevisionId())
->allRevisions()
->accessCheck(FALSE)
->execute();
if (count($all_revisions) > 1) {
// Do not delete if there is more than one usage of this revision.
return;
}
\Drupal::entityTypeManager()->getStorage($child->getEntityTypeId())->deleteRevision($child->getRevisionId());
}
/**
* {@inheritdoc}
*/
public function delete() {
parent::delete();
if ($this->entity && $this->entity->getEntityType()->get('entity_revision_parent_type_field') && $this->entity->getEntityType()->get('entity_revision_parent_id_field')) {
// Only delete composite entities if the host field is not translatable.
if (!$this->getFieldDefinition()->isTranslatable()) {
\Drupal::queue('entity_reference_revisions_orphan_purger')->createItem([
'entity_id' => $this->entity->id(),
'entity_type_id' => $this->entity->getEntityTypeId(),
]);
}
}
}
/**
* {@inheritdoc}
*/
public static function onDependencyRemoval(FieldDefinitionInterface $field_definition, array $dependencies) {
$changed = FALSE;
$entity_type_manager = \Drupal::entityTypeManager();
$target_entity_type = $entity_type_manager->getDefinition($field_definition->getFieldStorageDefinition()
->getSetting('target_type'));
$handler_settings = $field_definition->getSetting('handler_settings');
// Update the 'target_bundles' handler setting if a bundle config dependency
// has been removed.
if (!empty($handler_settings['target_bundles'])) {
if ($bundle_entity_type_id = $target_entity_type->getBundleEntityType()) {
if ($storage = $entity_type_manager->getStorage($bundle_entity_type_id)) {
foreach ($storage->loadMultiple($handler_settings['target_bundles']) as $bundle) {
if (isset($dependencies[$bundle->getConfigDependencyKey()][$bundle->getConfigDependencyName()])) {
unset($handler_settings['target_bundles'][$bundle->id()]);
$changed = TRUE;
}
}
}
}
}
if ($changed) {
$field_definition->setSetting('handler_settings', $handler_settings);
}
return $changed;
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
$entity_manager = \Drupal::entityTypeManager();
// ERR field values are never cross referenced so we need to generate new
// target entities. First, find the target entity type.
$target_type_id = $field_definition->getFieldStorageDefinition()->getSetting('target_type');
$target_type = $entity_manager->getDefinition($target_type_id);
$handler_settings = $field_definition->getSetting('handler_settings');
// Determine referenceable bundles.
$bundle_manager = \Drupal::service('entity_type.bundle.info');
if (isset($handler_settings['target_bundles']) && is_array($handler_settings['target_bundles'])) {
if (empty($handler_settings['negate'])) {
$bundles = $handler_settings['target_bundles'];
}
else {
$bundles = array_filter($bundle_manager->getBundleInfo($target_type_id), function ($bundle) use ($handler_settings) {
return !in_array($bundle, $handler_settings['target_bundles'], TRUE);
});
}
}
else {
$bundles = $bundle_manager->getBundleInfo($target_type_id);
}
$bundle = array_rand($bundles);
$label = NULL;
if ($label_key = $target_type->getKey('label')) {
$random = new Random();
// @TODO set the length somehow less arbitrary.
$label = $random->word(mt_rand(1, 10));
}
// Create entity stub.
$entity = $selection_manager->getSelectionHandler($field_definition)->createNewEntity($target_type_id, $bundle, $label, 0);
// Populate entity values and save.
$instances = $entity_manager
->getStorage('field_config')
->loadByProperties([
'entity_type' => $target_type_id,
'bundle' => $bundle,
]);
foreach ($instances as $instance) {
$field_storage = $instance->getFieldStorageDefinition();
$max = $cardinality = $field_storage->getCardinality();
if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
// Just an arbitrary number for 'unlimited'
$max = rand(1, 5);
}
$field_name = $field_storage->getName();
$entity->{$field_name}->generateSampleItems($max);
}
$entity->save();
return [
'target_id' => $entity->id(),
'target_revision_id' => $entity->getRevisionId(),
];
}
}
@@ -0,0 +1,43 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\Field\FieldWidget;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'entity_reference_autocomplete' widget.
*
* @FieldWidget(
* id = "entity_reference_revisions_autocomplete",
* label = @Translation("Autocomplete"),
* description = @Translation("An autocomplete text field."),
* field_types = {
* "entity_reference_revisions"
* }
* )
*/
class EntityReferenceRevisionsAutocompleteWidget extends EntityReferenceAutocompleteWidget {
/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
$entity_type = $this->fieldDefinition->getFieldStorageDefinition()->getSetting('target_type');
foreach ($values as $key => $value) {
if($value['target_id']) {
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($value['target_id']);
// Add the current revision ID.
$values[$key]['target_revision_id'] = $entity->getRevisionId();
}
// The entity_autocomplete form element returns an array when an entity
// was "autocreated", so we need to move it up a level.
if (is_array($value['target_id'])) {
unset($values[$key]['target_id']);
$values[$key] += $value['target_id'];
}
}
return $values;
}
}
@@ -0,0 +1,113 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\QueueWorker;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Removes composite revisions that are no longer used.
*
* @QueueWorker(
* id = "entity_reference_revisions_orphan_purger",
* title = @Translation("Entity Reference Revisions Orphan Purger"),
* cron = {"time" = 60}
* )
*/
class OrphanPurger extends QueueWorkerBase implements ContainerFactoryPluginInterface {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The purger.
*
* @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger
*/
protected $purger;
/**
* The database.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Constructs a new OrphanPurger instance.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\entity_reference_revisions\EntityReferenceRevisionsOrphanPurger $purger
* The purger service.
* @param \Drupal\Core\Database\Connection $database
* The database service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityReferenceRevisionsOrphanPurger $purger, Connection $database) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->purger = $purger;
$this->database = $database;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('entity_reference_revisions.orphan_purger'),
$container->get('database')
);
}
/**
* {@inheritdoc}
*/
public function processItem($data) {
$entity_type_id = $data['entity_type_id'];
if (!$this->entityTypeManager->hasDefinition($entity_type_id)) {
return;
}
// Check the usage of data item and remove if not used.
$composite_storage = $this->entityTypeManager->getStorage($entity_type_id);
$composite_type = $this->entityTypeManager->getDefinition($entity_type_id);
$composite_revision_key = $composite_type->getKey('revision');
// Load all revisions of the composite type.
// @todo Replace with an entity query on all revisions with a revision ID
// condition after https://www.drupal.org/project/drupal/issues/2766135.
$entity_revision_ids = $this->database->select($composite_type->getRevisionTable(), 'r')
->fields('r', [$composite_revision_key])
->condition($composite_type->getKey('id'), $data['entity_id'])
->orderBy($composite_revision_key)
->execute()
->fetchCol();
/** @var \Drupal\Core\Entity\ContentEntityInterface $composite_revision */
foreach ($composite_storage->loadMultipleRevisions($entity_revision_ids) as $composite_revision) {
if (!$this->purger->isUsed($composite_revision)) {
$this->purger->deleteUnusedRevision($composite_revision);
}
}
}
}
@@ -0,0 +1,59 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\diff\Field;
use Drupal\diff\FieldDiffBuilderBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\diff\FieldReferenceInterface;
/**
* This plugins offers the possibility to compare ERR fields.
*
* @FieldDiffBuilder(
* id = "entity_reference_revisions_field_diff_builder",
* label = @Translation("Field Diff for Paragraphs"),
* field_types = {
* "entity_reference_revisions"
* },
* )
*/
class EntityReferenceRevisionsFieldDiffBuilder extends FieldDiffBuilderBase implements FieldReferenceInterface {
/**
* {@inheritdoc}
*/
public function build(FieldItemListInterface $field_items): mixed {
$result_text = array();
$item_counter = 0;
/** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $field_item */
foreach ($field_items as $field_key => $field_item) {
if (!$field_item->isEmpty() && $field_item->entity) {
$parsed_text = $this->entityParser->parseEntity($field_item->entity);
if (is_array($parsed_text)) {
foreach ($parsed_text as $field_id => $field) {
foreach ($field as $id => $text) {
$result_text[$item_counter + $id] = $text;
}
$item_counter = $item_counter + $id + 1;
}
}
}
}
return $result_text;
}
/**
* {@inheritdoc}
*/
public function getEntitiesToDiff(FieldItemListInterface $field_items): array {
/** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $field_item */
$entities = [];
foreach ($field_items as $field_key => $field_item) {
if (!$field_item->isEmpty() && $field_item->entity) {
$entities[$field_key] = $field_item->entity;
}
}
return $entities;
}
}
@@ -0,0 +1,211 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\migrate\destination;
use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\destination\EntityRevision;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Row;
/**
* Provides entity_reference_revisions destination plugin.
*
* Available configuration keys:
* - new_revisions: (optional) Flag to indicate if a new revision should be
* created instead of updating a previous default record. Only applicable when
* providing an entity id without a revision_id.
* - force_revision: (optional) Flag to ignore other checks and always create a
* revision.
*
* @MigrateDestination(
* id = "entity_reference_revisions",
* deriver = "Drupal\entity_reference_revisions\Plugin\Derivative\MigrateEntityReferenceRevisions"
* )
*/
class EntityReferenceRevisions extends EntityRevision implements ConfigurableInterface {
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return $this->configuration;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'new_revisions' => FALSE,
];
}
/**
* {@inheritdoc}
*/
protected static function getEntityTypeId($pluginId) {
// Remove "entity_reference_revisions:".
// Ideally, we would call getDerivativeId(), but since this is static
// that is not possible so we follow the same pattern as core.
return substr($pluginId, 27);
}
/**
* {@inheritdoc}
*/
protected function save(ContentEntityInterface $entity, array $oldDestinationIdValues = []) {
$entity->save();
return [
$this->getKey('id') => $entity->id(),
$this->getKey('revision') => $entity->getRevisionId(),
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
if ($revision_key = $this->getKey('revision')) {
$id_key = $this->getKey('id');
$ids[$id_key]['type'] = 'integer';
// TODO: Improve after https://www.drupal.org/node/2783715 is finished.
$ids[$revision_key]['type'] = 'integer';
if ($this->isTranslationDestination()) {
if ($revision_key = $this->getKey('langcode')) {
$ids[$revision_key]['type'] = 'string';
}
else {
throw new MigrateException('This entity type does not support translation.');
}
}
return $ids;
}
throw new MigrateException('This entity type does not support revisions.');
}
/**
* {@inheritdoc}
*/
protected function getEntity(Row $row, array $oldDestinationIdValues) {
$entity_id = $oldDestinationIdValues ?
array_shift($oldDestinationIdValues) :
$this->getEntityId($row);
$configuration = $this->getConfiguration();
if (isset($configuration['force_revision']) && $configuration['force_revision'] == TRUE) {
$revision_id = NULL;
}
else {
$revision_id = $oldDestinationIdValues ?
array_pop($oldDestinationIdValues) :
$row->getDestinationProperty($this->getKey('revision'));
}
// If a specific revision_id is supplied and exists, assert the entity_id
// matches (if supplied), and update the revision.
/** @var \Drupal\Core\Entity\RevisionableInterface|\Drupal\Core\Entity\EntityInterface $entity */
if (!empty($revision_id) && ($entity = $this->storage->loadRevision($revision_id))) {
if (!empty($entity_id) && ($entity->id() != $entity_id)) {
throw new MigrateException("The revision_id exists for this entity type, but does not belong to the given entity id");
}
$entity = $this->updateEntity($entity, $row) ?: $entity;
}
// If there is no revision_id supplied, but there is an entity_id
// supplied that exists, update it.
elseif (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) {
// If so configured, create a new revision while updating.
if (!empty($this->configuration['new_revisions'])) {
$entity->setNewRevision(TRUE);
}
$entity = $this->updateEntity($entity, $row) ?: $entity;
}
// Otherwise, create a new (possibly stub) entity.
else {
// Attempt to ensure we always have a bundle.
if ($bundle = $this->getBundle($row)) {
$row->setDestinationProperty($this->getKey('bundle'), $bundle);
}
// Stubs might need some required fields filled in.
if ($row->isStub()) {
$this->processStubRow($row);
}
$entity = $this->storage->create($row->getDestination())
->enforceIsNew(TRUE);
$entity->setNewRevision(TRUE);
}
$this->rollbackAction = MigrateIdMapInterface::ROLLBACK_DELETE;
return $entity;
}
/**
* {@inheritdoc}
*/
public function rollback(array $destination_identifiers) {
if ($this->isTranslationDestination()) {
$this->rollbackTranslation($destination_identifiers);
}
else {
$this->rollbackNonTranslation($destination_identifiers);
}
}
/**
* Rollback translation destinations.
*
* @param array $destination_identifiers
* The IDs of the destination object to delete.
*/
protected function rollbackTranslation(array $destination_identifiers) {
$entity = $this->storage->loadRevision(array_pop($destination_identifiers));
if ($entity && $entity instanceof TranslatableInterface) {
if ($key = $this->getKey('langcode')) {
if (isset($destination_identifiers[$key])) {
$langcode = $destination_identifiers[$key];
if ($entity->hasTranslation($langcode)) {
// Make sure we don't remove the default translation.
$translation = $entity->getTranslation($langcode);
if (!$translation->isDefaultTranslation()) {
$entity->removeTranslation($langcode);
$entity->save();
}
}
}
}
}
}
/**
* Rollback non-translation destinations.
*
* @param array $destination_identifiers
* The IDs of the destination object to delete.
*/
protected function rollbackNonTranslation(array $destination_identifiers) {
$revision_id = array_pop($destination_identifiers);
$entity = $this->storage->loadRevision($revision_id);
if ($entity) {
if ($entity->isDefaultRevision()) {
$entity->delete();
}
else {
$this->storage->deleteRevision($revision_id);
}
}
}
}
@@ -0,0 +1,177 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\views\display;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
/**
* The plugin that handles an EntityReferenceRevisions display.
*
* "entity_reference_revisions_display" is a custom property, used with
* \Drupal\views\Views::getApplicableViews() to retrieve all views with a
* 'Entity Reference Revisions' display.
*
* @ingroup views_display_plugins
*
* @ViewsDisplay(
* id = "entity_reference_revisions",
* title = @Translation("Entity Reference Revisions"),
* admin = @Translation("Entity Reference Revisions Source"),
* help = @Translation("Selects referenceable entities for an entity reference revisions field."),
* theme = "views_view",
* register_theme = FALSE,
* uses_menu_links = FALSE,
* entity_reference_revisions_display = TRUE
* )
*/
class EntityReferenceRevisions extends DisplayPluginBase {
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$useAJAX.
*/
protected $usesAJAX = FALSE;
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesPager.
*/
protected $usesPager = FALSE;
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesAttachments.
*/
protected $usesAttachments = FALSE;
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::defineOptions().
*/
protected function defineOptions() {
$options = parent::defineOptions();
// Force the style plugin to 'entity_reference_style' and the row plugin to
// 'fields'.
$options['style']['contains']['type'] = array('default' => 'entity_reference_revisions');
$options['defaults']['default']['style'] = FALSE;
$options['row']['contains']['type'] = array('default' => 'entity_reference_revisions');
$options['defaults']['default']['row'] = FALSE;
// Make sure the query is not cached.
$options['defaults']['default']['cache'] = FALSE;
// Set the display title to an empty string (not used in this display type).
$options['title']['default'] = '';
$options['defaults']['default']['title'] = FALSE;
return $options;
}
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::optionsSummary().
*
* Disable 'cache' and 'title' so it won't be changed.
*/
public function optionsSummary(&$categories, &$options) {
parent::optionsSummary($categories, $options);
unset($options['query']);
unset($options['title']);
}
/**
* {@inheritdoc}
*/
public function getType() {
return 'entity_reference_revisions';
}
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::execute().
*/
public function execute() {
return $this->view->render($this->display['id']);
}
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::render().
*/
public function render() {
if (!empty($this->view->result) && $this->view->style_plugin->evenEmpty()) {
return $this->view->style_plugin->render($this->view->result);
}
return '';
}
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::usesExposed().
*/
public function usesExposed() {
return FALSE;
}
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::query().
*/
public function query() {
if (!empty($this->view->live_preview)) {
return;
}
// Make sure the id field is included in the results.
$id_field = $this->view->storage->get('base_field');
$this->id_field_alias = $this->view->query->addField($this->view->storage->get('base_table'), $id_field);
$options = $this->getOption('entity_reference_revisions_options');
// Restrict the autocomplete options based on what's been typed already.
$db = \Drupal::database();
if (isset($options['match'])) {
$style_options = $this->getOption('style');
$value = $db->escapeLike($options['match']) . '%';
if ($options['match_operator'] != 'STARTS_WITH') {
$value = '%' . $value;
}
// Multiple search fields are OR'd together.
$conditions = $db->condition('OR');
// Build the condition using the selected search fields.
foreach ($style_options['options']['search_fields'] as $field_alias) {
if (!empty($field_alias)) {
// Get the table and field names for the checked field.
$field = $this->view->query->fields[$this->view->field[$field_alias]->field_alias];
// Add an OR condition for the field.
$conditions->condition($field['table'] . '.' . $field['field'], $value, 'LIKE');
}
}
$this->view->query->addWhere(0, $conditions);
}
// Add an IN condition for validation.
if (!empty($options['ids'])) {
$this->view->query->addWhere(0, $id_field, $options['ids']);
}
$this->view->setItemsPerPage($options['limit']);
}
/**
* Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::validate().
*/
public function validate() {
$errors = parent::validate();
// Verify that search fields are set up.
$style = $this->getOption('style');
if (!isset($style['options']['search_fields'])) {
$errors[] = $this->t('Display "@display" needs a selected search fields to work properly. See the settings for the Entity Reference Revisions list format.', array('@display' => $this->display['display_title']));
}
else {
// Verify that the search fields used actually exist.
$fields = array_keys($this->handlers['field']);
foreach ($style['options']['search_fields'] as $field_alias => $enabled) {
if ($enabled && !in_array($field_alias, $fields)) {
$errors[] = $this->t('Display "@display" uses field %field as search field, but the field is no longer present. See the settings for the Entity Reference Revisions list format.', array('@display' => $this->display['display_title'], '%field' => $field_alias));
}
}
}
return $errors;
}
}
@@ -0,0 +1,57 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\views\row;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\row\Fields;
/**
* EntityReferenceRevisions row plugin.
*
* @ingroup views_row_plugins
*
* @ViewsRow(
* id = "entity_reference_revisions",
* title = @Translation("Entity Reference inline fields"),
* help = @Translation("Displays the fields with an optional template."),
* theme = "views_view_fields",
* register_theme = FALSE,
* display_types = {"entity_reference"}
* )
*/
class EntityReferenceRevisions extends Fields {
/**
* Overrides \Drupal\views\Plugin\views\row\Fields::defineOptions().
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['separator'] = array('default' => '-');
return $options;
}
/**
* Overrides \Drupal\views\Plugin\views\row\Fields::buildOptionsForm().
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
// Expand the description of the 'Inline field' checkboxes.
$form['inline']['#description'] .= '<br />' . $this->t("<strong>Note:</strong> In 'Entity Reference' displays, all fields will be displayed inline unless an explicit selection of inline fields is made here." );
}
/**
* {@inheritdoc}
*/
public function preRender($row) {
// Force all fields to be inline by default.
if (empty($this->options['inline'])) {
$fields = $this->view->getHandlers('field', $this->displayHandler->display['id']);
$names = array_keys($fields);
$this->options['inline'] = array_combine($names, $names);
}
return parent::preRender($row);
}
}
@@ -0,0 +1,103 @@
<?php
namespace Drupal\entity_reference_revisions\Plugin\views\style;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\style\StylePluginBase;
/**
* EntityReferenceRevisions style plugin.
*
* @ingroup views_style_plugins
*
* @ViewsStyle(
* id = "entity_reference_revisions",
* title = @Translation("Entity Reference Revisions list"),
* help = @Translation("Returns results as a PHP array of labels and rendered rows."),
* theme = "views_view_unformatted",
* register_theme = FALSE,
* display_types = {"entity_reference_revisions"}
* )
*/
class EntityReferenceRevisions extends StylePluginBase {
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase::usesRowPlugin.
*/
protected $usesRowPlugin = TRUE;
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase::usesFields.
*/
protected $usesFields = TRUE;
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase::usesGrouping.
*/
protected $usesGrouping = FALSE;
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::defineOptions().
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['search_fields'] = array('default' => NULL);
return $options;
}
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::buildOptionsForm().
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$options = $this->displayHandler->getFieldLabels(TRUE);
$form['search_fields'] = array(
'#type' => 'checkboxes',
'#title' => $this->t('Search fields'),
'#options' => $options,
'#required' => TRUE,
'#default_value' => $this->options['search_fields'],
'#description' => $this->t('Select the field(s) that will be searched when using the autocomplete widget.'),
'#weight' => -3,
);
}
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::render().
*/
public function render() {
if (!empty($this->view->live_preview)) {
return parent::render();
}
// Group the rows according to the grouping field, if specified.
$sets = $this->renderGrouping($this->view->result, $this->options['grouping']);
// Grab the alias of the 'id' field added by
// entity_reference_plugin_display.
$id_field_alias = $this->view->storage->get('base_field');
// @todo We don't display grouping info for now. Could be useful for select
// widget, though.
$results = array();
foreach ($sets as $records) {
foreach ($records as $values) {
// Sanitize HTML, remove line breaks and extra whitespace.
$output = $this->view->rowPlugin->render($values);
$output = \Drupal::service('renderer')->render($output);
$results[$values->{$id_field_alias}] = Xss::filterAdmin(preg_replace('/\s\s+/', ' ', str_replace("\n", '', $output)));
}
}
return $results;
}
/**
* {@inheritdoc}
*/
public function evenEmpty() {
return TRUE;
}
}
@@ -0,0 +1,50 @@
<?php
namespace Drupal\entity_reference_revisions\TypedData;
use Drupal\Core\Entity\TypedData\EntityDataDefinition;
use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface;
/**
* A typed data definition class for describing entities.
*/
class EntityRevisionDataDefinition extends EntityDataDefinition implements EntityDataDefinitionInterface {
/**
* {@inheritdoc}
*/
public static function createFromDataType($data_type) {
$parts = explode(':', $data_type);
if ($parts[0] != 'entity_revision') {
throw new \InvalidArgumentException('Data type must be in the form of "entity_revision:ENTITY_TYPE:BUNDLE."');
}
$definition = static::create();
// Set the passed entity type and bundle.
if (isset($parts[1])) {
$definition->setEntityTypeId($parts[1]);
}
if (isset($parts[2])) {
$definition->setBundles(array($parts[2]));
}
return $definition;
}
/**
* {@inheritdoc}
*/
public function getDataType() {
$type = 'entity_revision';
if ($entity_type = $this->getEntityTypeId()) {
$type .= ':' . $entity_type;
// Append the bundle only if we know it for sure and it is not the default
// bundle.
if (($bundles = $this->getBundles()) && count($bundles) == 1) {
$bundle = reset($bundles);
if ($bundle != $entity_type) {
$type .= ':' . $bundle;
}
}
}
return $type;
}
}