EntityRevisionParamConverter.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Drupal\Core\ParamConverter;
  3. use Drupal\Core\Entity\EntityInterface;
  4. use Drupal\Core\Entity\EntityRepositoryInterface;
  5. use Drupal\Core\Entity\EntityTypeManagerInterface;
  6. use Drupal\Core\Entity\TranslatableInterface;
  7. use Symfony\Component\Routing\Route;
  8. /**
  9. * Parameter converter for upcasting entity revision IDs to full objects.
  10. *
  11. * This is useful for pages which want to show a specific revision, like
  12. * "/entity_example/{entity_example}/revision/{entity_example_revision}".
  13. *
  14. *
  15. * In order to use it you should specify some additional options in your route:
  16. * @code
  17. * example.route:
  18. * path: /foo/{entity_example_revision}
  19. * options:
  20. * parameters:
  21. * entity_example_revision:
  22. * type: entity_revision:entity_example
  23. * @endcode
  24. */
  25. class EntityRevisionParamConverter implements ParamConverterInterface {
  26. use DynamicEntityTypeParamConverterTrait;
  27. /**
  28. * The entity type manager.
  29. *
  30. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  31. */
  32. protected $entityTypeManager;
  33. /**
  34. * The entity repository.
  35. *
  36. * @var \Drupal\Core\Entity\EntityRepositoryInterface
  37. */
  38. protected $entityRepository;
  39. /**
  40. * Creates a new EntityRevisionParamConverter instance.
  41. *
  42. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
  43. * The entity type manager.
  44. * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
  45. * The entity repository.
  46. */
  47. public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityRepositoryInterface $entity_repository) {
  48. $this->entityTypeManager = $entity_type_manager;
  49. $this->entityRepository = $entity_repository;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function convert($value, $definition, $name, array $defaults) {
  55. $entity_type_id = $this->getEntityTypeFromDefaults($definition, $name, $defaults);
  56. $entity = $this->entityTypeManager->getStorage($entity_type_id)->loadRevision($value);
  57. // If the entity type is translatable, ensure we return the proper
  58. // translation object for the current context.
  59. if ($entity instanceof EntityInterface && $entity instanceof TranslatableInterface) {
  60. $entity = $this->entityRepository->getTranslationFromContext($entity, NULL, ['operation' => 'entity_upcast']);
  61. }
  62. return $entity;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function applies($definition, $name, Route $route) {
  68. return isset($definition['type']) && strpos($definition['type'], 'entity_revision:') !== FALSE;
  69. }
  70. }