PreviewLinkRoutes.php in Preview Link 2.x
File
src/Routing/PreviewLinkRoutes.php
View source
<?php
declare (strict_types=1);
namespace Drupal\preview_link\Routing;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\preview_link\PreviewLinkUtility;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class PreviewLinkRoutes extends RouteSubscriberBase {
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager) {
$this->entityTypeManager = $entityTypeManager;
}
protected function alterRoutes(RouteCollection $collection) : void {
$entityTypes = $this->entityTypeManager
->getDefinitions();
$entityTypes = array_filter($entityTypes, [
PreviewLinkUtility::class,
'isEntityTypeSupported',
]);
foreach ($entityTypes as $entityType) {
$canonicalPath = $entityType
->getLinkTemplate('canonical');
$route = $this
->getRouteForPath($collection, $canonicalPath);
if (!$route) {
continue;
}
$entityParameterName = $entityType
->id();
foreach ($route
->getOptions()['parameters'] ?? [] as $parameterName => $value) {
if (($value['type'] ?? NULL) === 'entity:' . $entityType
->id()) {
$entityParameterName = $parameterName;
}
}
if (strpos($route
->getPath(), sprintf('{%s}', $entityParameterName)) === FALSE) {
throw new \LogicException(sprintf('Unable to determine parameter name representing an upcast of entity type `%s`', $entityType
->id()));
}
$route
->addRequirements([
'_access_preview_link_canonical_rerouter' => $entityParameterName,
]);
}
}
protected function getRouteForPath(RouteCollection $collection, string $path) : ?Route {
foreach ($collection as $route) {
assert($route instanceof Route);
if ($route
->getPath() === $path) {
return $route;
}
}
return NULL;
}
}