|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Spiral\Interceptors\Handler; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Container\ContainerExceptionInterface; |
|
8
|
|
|
use Psr\Container\ContainerInterface; |
|
9
|
|
|
use Spiral\Core\ResolverInterface; |
|
10
|
|
|
use Spiral\Interceptors\Context\CallContextInterface; |
|
11
|
|
|
use Spiral\Interceptors\Exception\TargetCallException; |
|
12
|
|
|
use Spiral\Interceptors\HandlerInterface; |
|
13
|
|
|
use Spiral\Interceptors\Internal\ActionResolver; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Handler resolves missing arguments from the container. |
|
17
|
|
|
* It requires the Target to explicitly point to a method or function. |
|
18
|
|
|
*/ |
|
19
|
|
|
final class AutowireHandler implements HandlerInterface |
|
20
|
|
|
{ |
|
21
|
6 |
|
public function __construct( |
|
22
|
|
|
/** @internal */ |
|
23
|
|
|
protected ContainerInterface $container, |
|
24
|
|
|
) { |
|
25
|
6 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @psalm-assert class-string $controller |
|
29
|
|
|
* @psalm-assert non-empty-string $action |
|
30
|
|
|
* @throws \Throwable |
|
31
|
|
|
*/ |
|
32
|
6 |
|
public function handle(CallContextInterface $context): mixed |
|
33
|
|
|
{ |
|
34
|
|
|
// Resolve controller method |
|
35
|
6 |
|
$method = $context->getTarget()->getReflection() ?? throw new TargetCallException( |
|
36
|
6 |
|
"Reflection not provided for target `{$context->getTarget()}`.", |
|
37
|
6 |
|
TargetCallException::NOT_FOUND, |
|
38
|
6 |
|
); |
|
39
|
4 |
|
$path = $context->getTarget()->getPath(); |
|
40
|
|
|
|
|
41
|
4 |
|
if ($method instanceof \ReflectionFunction) { |
|
42
|
2 |
|
return $method->invokeArgs( |
|
43
|
2 |
|
$this->resolveArguments($method, $context) |
|
44
|
2 |
|
); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
if (!$method instanceof \ReflectionMethod) { |
|
48
|
|
|
throw new TargetCallException("Action not found for target `{$context->getTarget()}`."); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
2 |
|
$controller = $context->getTarget()->getObject() ?? $this->container->get(\reset($path)); |
|
52
|
|
|
|
|
53
|
|
|
// Validate method and controller |
|
54
|
2 |
|
ActionResolver::validateControllerMethod($method, $controller); |
|
55
|
|
|
|
|
56
|
|
|
// Run action |
|
57
|
2 |
|
return $method->invokeArgs($controller, $this->resolveArguments($method, $context)); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @throws ContainerExceptionInterface |
|
62
|
|
|
*/ |
|
63
|
4 |
|
protected function resolveArguments(\ReflectionFunctionAbstract $method, CallContextInterface $context): array |
|
64
|
|
|
{ |
|
65
|
4 |
|
$resolver = $this->container->get(ResolverInterface::class); |
|
66
|
4 |
|
\assert($resolver instanceof ResolverInterface); |
|
67
|
|
|
|
|
68
|
4 |
|
return $resolver->resolveArguments($method, $context->getArguments()); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|