RouteSubscriber.php in View Modes Display 8.2
File
src/Routing/RouteSubscriber.php
View source
<?php
namespace Drupal\view_modes_display\Routing;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class RouteSubscriber extends RouteSubscriberBase {
protected $entityTypeManager;
protected $entityDisplayRepository;
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepositoryInterface $entityDisplayRepository) {
$this->entityTypeManager = $entity_type_manager;
$this->entityDisplayRepository = $entityDisplayRepository;
}
protected function alterRoutes(RouteCollection $collection) {
foreach ($this->entityTypeManager
->getDefinitions() as $entity_type_id => $entity_type) {
if ($viewModes = $this->entityDisplayRepository
->getViewModes($entity_type_id)) {
if ($route = $this
->getPreviewList($entity_type)) {
$collection
->add("entity.{$entity_type_id}.vmd_preview_list", $route);
}
if ($route = $this
->getPreviewRenderRoute($entity_type)) {
$collection
->add("entity.{$entity_type_id}.vmd_preview_render", $route);
}
}
}
}
protected function getPreviewList(EntityTypeInterface $entity_type) {
if ($link_template = $entity_type
->getLinkTemplate('vmd-preview-list')) {
$entity_type_id = $entity_type
->id();
$route = new Route($link_template);
$route
->addDefaults([
'_controller' => '\\Drupal\\view_modes_display\\Controller\\PreviewController::previewList',
'_title' => 'Available View Mode Previews',
'entity_type' => $entity_type_id,
'view_mode' => 'all',
])
->addRequirements([
'_permission' => 'preview view modes',
])
->setOption('_admin_route', TRUE)
->setOption('parameters', [
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
],
]);
return $route;
}
}
protected function getPreviewRenderRoute(EntityTypeInterface $entity_type) {
if ($link_template = $entity_type
->getLinkTemplate('vmd-preview-list')) {
$entity_type_id = $entity_type
->id();
$route = new Route($link_template);
$route
->addDefaults([
'_controller' => '\\Drupal\\view_modes_display\\Controller\\PreviewController::previewEntity',
'_title' => 'View Mode Preview',
'entity_type' => $entity_type_id,
])
->addRequirements([
'_permission' => 'preview view modes',
])
->setOption('parameters', [
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
],
]);
return $route;
}
}
public static function getSubscribedEvents() {
$events = parent::getSubscribedEvents();
$events[RoutingEvents::ALTER] = array(
'onAlterRoutes',
-100,
);
return $events;
}
}