|
1
|
|
|
<?php |
|
2
|
|
|
namespace Wandu\Router\Loader; |
|
3
|
|
|
|
|
4
|
|
|
use Exception; |
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
6
|
|
|
use Throwable; |
|
7
|
|
|
use Wandu\DI\ContainerInterface; |
|
8
|
|
|
use Wandu\DI\Exception\NullReferenceException; |
|
9
|
|
|
use Wandu\Http\Psr\ServerRequest; |
|
10
|
|
|
use Wandu\Router\Contracts\LoaderInterface; |
|
11
|
|
|
use Wandu\Router\Contracts\MiddlewareInterface; |
|
12
|
|
|
use Wandu\Router\Exception\HandlerNotFoundException; |
|
13
|
|
|
|
|
14
|
|
|
class WanduLoader implements LoaderInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var \Wandu\DI\ContainerInterface */ |
|
17
|
|
|
protected $container; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param \Wandu\DI\ContainerInterface $container |
|
21
|
|
|
*/ |
|
22
|
5 |
|
public function __construct(ContainerInterface $container) |
|
23
|
|
|
{ |
|
24
|
5 |
|
$this->container = $container; |
|
25
|
5 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* {@inheritdoc} |
|
29
|
|
|
*/ |
|
30
|
2 |
|
public function middleware($className): MiddlewareInterface |
|
31
|
|
|
{ |
|
32
|
|
|
try { |
|
33
|
2 |
|
return $this->container->create($className); |
|
34
|
1 |
|
} catch (NullReferenceException $e) { |
|
35
|
1 |
|
throw new HandlerNotFoundException($className); |
|
36
|
|
|
} |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* {@inheritdoc} |
|
41
|
|
|
*/ |
|
42
|
3 |
|
public function execute($className, $methodName, ServerRequestInterface $request) |
|
43
|
|
|
{ |
|
44
|
|
|
try { |
|
45
|
3 |
|
$object = $this->container->get($className); |
|
46
|
|
|
} catch (NullReferenceException $e) { |
|
47
|
|
|
throw new HandlerNotFoundException($className, $methodName); |
|
48
|
|
|
} |
|
49
|
3 |
|
if (!method_exists($object, $methodName) && !method_exists($object, '__call')) { |
|
50
|
|
|
throw new HandlerNotFoundException($className, $methodName); |
|
51
|
|
|
} |
|
52
|
3 |
|
return $this->container->with([ |
|
53
|
3 |
|
ServerRequest::class => $request, |
|
54
|
3 |
|
])->call([$object, $methodName]); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|