| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
/*
|
|
|
4 |
* This file is part of the Symfony package.
|
|
|
5 |
*
|
|
|
6 |
* (c) Fabien Potencier <fabien@symfony.com>
|
|
|
7 |
*
|
|
|
8 |
* For the full copyright and license information, please view the LICENSE
|
|
|
9 |
* file that was distributed with this source code.
|
|
|
10 |
*/
|
|
|
11 |
|
|
|
12 |
namespace Symfony\Component\HttpKernel\Controller;
|
|
|
13 |
|
|
|
14 |
use Psr\Container\ContainerInterface;
|
|
|
15 |
use Psr\Log\LoggerInterface;
|
|
|
16 |
use Symfony\Component\DependencyInjection\Container;
|
|
|
17 |
|
|
|
18 |
/**
|
|
|
19 |
* A controller resolver searching for a controller in a psr-11 container when using the "service::method" notation.
|
|
|
20 |
*
|
|
|
21 |
* @author Fabien Potencier <fabien@symfony.com>
|
|
|
22 |
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
|
|
|
23 |
*/
|
|
|
24 |
class ContainerControllerResolver extends ControllerResolver
|
|
|
25 |
{
|
|
|
26 |
protected $container;
|
|
|
27 |
|
|
|
28 |
public function __construct(ContainerInterface $container, LoggerInterface $logger = null)
|
|
|
29 |
{
|
|
|
30 |
$this->container = $container;
|
|
|
31 |
|
|
|
32 |
parent::__construct($logger);
|
|
|
33 |
}
|
|
|
34 |
|
|
|
35 |
protected function instantiateController(string $class): object
|
|
|
36 |
{
|
|
|
37 |
$class = ltrim($class, '\\');
|
|
|
38 |
|
|
|
39 |
if ($this->container->has($class)) {
|
|
|
40 |
return $this->container->get($class);
|
|
|
41 |
}
|
|
|
42 |
|
|
|
43 |
try {
|
|
|
44 |
return parent::instantiateController($class);
|
|
|
45 |
} catch (\Error $e) {
|
|
|
46 |
}
|
|
|
47 |
|
|
|
48 |
$this->throwExceptionIfControllerWasRemoved($class, $e);
|
|
|
49 |
|
|
|
50 |
if ($e instanceof \ArgumentCountError) {
|
|
|
51 |
throw new \InvalidArgumentException(sprintf('Controller "%s" has required constructor arguments and does not exist in the container. Did you forget to define the controller as a service?', $class), 0, $e);
|
|
|
52 |
}
|
|
|
53 |
|
|
|
54 |
throw new \InvalidArgumentException(sprintf('Controller "%s" does neither exist as service nor as class.', $class), 0, $e);
|
|
|
55 |
}
|
|
|
56 |
|
|
|
57 |
private function throwExceptionIfControllerWasRemoved(string $controller, \Throwable $previous)
|
|
|
58 |
{
|
|
|
59 |
if ($this->container instanceof Container && isset($this->container->getRemovedIds()[$controller])) {
|
|
|
60 |
throw new \InvalidArgumentException(sprintf('Controller "%s" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?', $controller), 0, $previous);
|
|
|
61 |
}
|
|
|
62 |
}
|
|
|
63 |
}
|