PreviewLinkCanonicalRerouteAccessCheck.php in Preview Link 2.0.x
File
src/Access/PreviewLinkCanonicalRerouteAccessCheck.php
View source
<?php
declare (strict_types=1);
namespace Drupal\preview_link\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\preview_link\Exception\PreviewLinkRerouteException;
use Drupal\preview_link\PreviewLinkHostInterface;
use Symfony\Component\HttpFoundation\Request;
class PreviewLinkCanonicalRerouteAccessCheck implements AccessInterface {
protected $privateTempStoreFactory;
protected $previewLinkHost;
protected $routeMatch;
public function __construct(PrivateTempStoreFactory $privateTempStoreFactory, PreviewLinkHostInterface $previewLinkHost, CurrentRouteMatch $routeMatch) {
$this->privateTempStoreFactory = $privateTempStoreFactory;
$this->previewLinkHost = $previewLinkHost;
$this->routeMatch = $routeMatch;
}
public function access(Request $request = NULL) : AccessResultInterface {
$cacheability = (new CacheableMetadata())
->addCacheContexts([
'session',
'route',
]);
$routeMatch = $this->routeMatch
->getMasterRouteMatch();
$route = $routeMatch
->getRouteObject();
$entityParameterName = $route ? $route
->getRequirement('_access_preview_link_canonical_rerouter') : NULL;
if (!isset($entityParameterName)) {
return AccessResult::allowed()
->addCacheableDependency($cacheability);
}
$cacheability = (new CacheableMetadata())
->addCacheContexts([
'session',
'route',
]);
if (!$request) {
return AccessResult::allowed()
->addCacheableDependency($cacheability);
}
$entity = $routeMatch
->getParameter($entityParameterName);
if (!$entity instanceof EntityInterface) {
return AccessResult::allowed()
->addCacheableDependency($cacheability);
}
$collection = $this->privateTempStoreFactory
->get('preview_link');
$claimedTokens = $collection
->get('keys') ?? [];
if (!$claimedTokens) {
return AccessResult::allowed()
->addCacheableDependency($cacheability);
}
if (!$this->previewLinkHost
->isToken($entity, $claimedTokens)) {
return AccessResult::allowed()
->addCacheableDependency($cacheability);
}
$previewLinks = $this->previewLinkHost
->getPreviewLinks($entity);
foreach ($previewLinks as $previewLink) {
if (in_array($previewLink
->getToken(), $claimedTokens, TRUE)) {
throw new PreviewLinkRerouteException('', 0, NULL, $entity, $previewLink);
}
}
throw new \LogicException('Shouldnt get here unless there are implementation differences between isToken and getPreviewLinks.');
}
}