EntityRevisionConverter.php in Workspace 8
File
src/ParamConverter/EntityRevisionConverter.php
View source
<?php
namespace Drupal\workspace\ParamConverter;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\ParamConverter\ParamConverterInterface;
use Drupal\Core\ParamConverter\ParamNotConvertedException;
use Drupal\Core\TypedData\TranslatableInterface;
use Symfony\Component\Routing\Route;
class EntityRevisionConverter implements ParamConverterInterface {
protected $entityTypeManager;
protected $entityRepository;
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityRepositoryInterface $entity_repository) {
$this->entityTypeManager = $entity_type_manager;
$this->entityRepository = $entity_repository;
}
public function convert($value, $definition, $name, array $defaults) {
$entity_type_id = $this
->getEntityTypeFromDefaults($definition, $name, $defaults);
if ($storage = $this->entityTypeManager
->getStorage($entity_type_id)) {
$entity = $storage
->loadRevision($value);
if ($entity instanceof EntityInterface && $entity instanceof TranslatableInterface) {
$entity = $this->entityRepository
->getTranslationFromContext($entity, NULL, [
'operation' => 'entity_upcast',
]);
}
return $entity;
}
}
public function applies($definition, $name, Route $route) {
if (!empty($definition['type']) && strpos($definition['type'], 'entity_revision:') === 0) {
$entity_type_id = substr($definition['type'], strlen('entity:'));
if (strpos($definition['type'], '{') !== FALSE) {
$entity_type_slug = substr($entity_type_id, 1, -1);
return $name != $entity_type_slug && in_array($entity_type_slug, $route
->compile()
->getVariables(), TRUE);
}
return $this->entityTypeManager
->hasDefinition($entity_type_id);
}
return FALSE;
}
protected function getEntityTypeFromDefaults($definition, $name, array $defaults) {
$entity_type_id = substr($definition['type'], strlen('entity_revision:'));
if (strpos($entity_type_id, '{') === 0) {
$entity_type_slug = substr($entity_type_id, 1, -1);
if (!isset($defaults[$entity_type_slug])) {
throw new ParamNotConvertedException(sprintf('The "%s" parameter was not converted because the "%s" parameter is missing', $name, $entity_type_slug));
}
$entity_type_id = $defaults[$entity_type_slug];
}
return $entity_type_id;
}
}