forked from symfony-cmf/routing-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouteDefaultsTwigValidator.php
More file actions
59 lines (49 loc) · 1.98 KB
/
RouteDefaultsTwigValidator.php
File metadata and controls
59 lines (49 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
/*
* This file is part of the Symfony CMF package.
*
* (c) Symfony CMF
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Cmf\Bundle\RoutingBundle\Validator\Constraints;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Twig\Loader\LoaderInterface;
/**
* @author Maximilian Berghoff <Maximilian.Berghoff@gmx.de>
*/
class RouteDefaultsTwigValidator extends ConstraintValidator
{
private ControllerResolverInterface $controllerResolver;
private ?LoaderInterface $twig;
public function __construct(ControllerResolverInterface $controllerResolver, ?LoaderInterface $twig)
{
$this->controllerResolver = $controllerResolver;
$this->twig = $twig;
}
public function validate(mixed $defaults, Constraint $constraint): void
{
if (!$constraint instanceof RouteDefaults) {
throw new \InvalidArgumentException(sprintf('Expected %s, got %s', RouteDefaults::class, get_class($constraint)));
}
if (\array_key_exists('_controller', $defaults) && null !== $defaults['_controller']) {
$controller = $defaults['_controller'];
$request = new Request([], [], ['_controller' => $controller]);
try {
$this->controllerResolver->getController($request);
} catch (\LogicException $e) {
$this->context->addViolation($e->getMessage());
}
}
if (null !== $this->twig && \array_key_exists('_template', $defaults) && null !== $defaults['_template']) {
$template = $defaults['_template'];
if (false === $this->twig->exists($template)) {
$this->context->addViolation($constraint->message, ['%name%' => $template]);
}
}
}
}