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
|
5 |
|
*/ |
22
|
|
|
public function __construct(ContainerInterface $container) |
23
|
5 |
|
{ |
24
|
5 |
|
$this->container = $container; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* {@inheritdoc} |
29
|
2 |
|
*/ |
30
|
|
|
public function middleware($className): MiddlewareInterface |
31
|
|
|
{ |
32
|
2 |
|
try { |
33
|
1 |
|
return $this->container->create($className); |
34
|
1 |
|
} catch (NullReferenceException $e) { |
35
|
|
|
throw new HandlerNotFoundException($className); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* {@inheritdoc} |
41
|
|
|
*/ |
42
|
|
|
public function execute($className, $methodName, ServerRequestInterface $request) |
43
|
3 |
|
{ |
44
|
|
|
try { |
45
|
|
|
$object = $this->container->get($className); |
46
|
3 |
|
} catch (NullReferenceException $e) { |
47
|
|
|
throw new HandlerNotFoundException($className, $methodName); |
48
|
|
|
} |
49
|
|
|
if (!method_exists($object, $methodName) && !method_exists($object, '__call')) { |
50
|
|
|
throw new HandlerNotFoundException($className, $methodName); |
51
|
|
|
} |
52
|
3 |
|
return $this->container->with([ |
53
|
|
|
ServerRequest::class => $request, |
54
|
|
|
])->call([$object, $methodName]); |
55
|
3 |
|
} |
56
|
|
|
} |
57
|
|
|
|