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