devel_wizard-2.x-dev/templates/spell/route_access_checker/access-checker.php.twig
templates/spell/route_access_checker/access-checker.php.twig
<?php
declare(strict_types=1);
namespace Drupal\{{ module }}\Route;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface as RoutingAccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;
/**
* Defines an access checker for {{ object }}.
*
* @code
* # my_module_01.routing.yml
* my_module_01.route_01:
* path: '/my_module_01/foo'
* requirements:
* {{ accessChecker.appliesTo }}: 'foo:bar'
* @endcode
*/
class {{ accessChecker.className }} implements RoutingAccessInterface {
protected string $appliesTo = '{{ accessChecker.appliesTo }}';
public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
[$arg1, $arg2] = explode(':', $route->getRequirement($this->appliesTo) . ':');
try {
$arg1 = $this->resolvePlaceholders($arg1, $route_match);
$arg2 = $this->resolvePlaceholders($arg2, $route_match);
}
catch (\InvalidArgumentException $exception) {
return AccessResult::forbidden($exception->getMessage());
}
return AccessResult::allowedIf($arg1 === 'foo' && $arg2 === 'bar');
}
/**
* @throws \InvalidArgumentException
*/
protected function resolvePlaceholders(string $arg, RouteMatchInterface $routeMatch): string {
if (!str_contains($arg, '{')) {
return $arg;
}
foreach ($routeMatch->getRawParameters()->all() as $name => $value) {
$arg = str_replace('{' . $name . '}', $value, $arg);
}
if (str_contains($arg, '{')) {
throw new \InvalidArgumentException(sprintf(
'Could not resolve all the placeholders in %s: %s access checker argument.',
$this->appliesTo,
$arg,
));
}
return $arg;
}
}
