Completed
Push — master ( bcd072...f56bcc )
by Changwan
03:29
created

WanduLoader::middleware()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 1
b 1
f 0
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