DiffPluginBase.php in Diff 8
File
src/Plugin/views/field/DiffPluginBase.php
View source
<?php
namespace Drupal\diff\Plugin\views\field;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DiffPluginBase extends FieldPluginBase {
use UncacheableFieldHandlerTrait;
protected $entityTypeManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
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'));
}
public function query() {
$this
->ensureMyTable();
}
public function getValue(ResultRow $row, $field = NULL) {
return '<!--form-item-' . $this->options['id'] . '--' . $row->index . '-->';
}
public function viewsForm(array &$form, FormStateInterface $form_state) {
if (!empty($this->view->result)) {
$form[$this->options['id']]['#tree'] = TRUE;
foreach ($this->view->result as $row_index => $row) {
$entity = $row->_entity;
$form[$this->options['id']][$row_index] = [
'#type' => 'radio',
'#parents' => [
$this->options['id'],
],
'#title' => $this
->t('Compare this item'),
'#title_display' => 'invisible',
'#return_value' => $this
->calculateEntityDiffFormKey($entity),
];
}
}
}
protected function calculateEntityDiffFormKey(EntityInterface $entity) {
$key_parts = [
$entity
->language()
->getId(),
$entity
->id(),
];
if ($entity instanceof RevisionableInterface) {
$key_parts[] = $entity
->getRevisionId();
}
$key = Json::encode($key_parts);
return base64_encode($key);
}
protected function loadEntityFromDiffFormKey($diff_form_key) {
$key = base64_decode($diff_form_key);
$key_parts = Json::decode($key);
$revision_id = NULL;
if (count($key_parts) === 3) {
$revision_id = array_pop($key_parts);
}
$id = array_pop($key_parts);
$langcode = array_pop($key_parts);
$storage = $this->entityTypeManager
->getStorage($this
->getEntityType());
$entity = $revision_id ? $storage
->loadRevision($revision_id) : $storage
->load($id);
if (empty($entity)) {
throw new \UnexpectedValueException('Entity not found: ' . $diff_form_key);
}
if ($entity instanceof TranslatableInterface) {
$entity = $entity
->getTranslation($langcode);
}
return $entity;
}
}