Completed
Pull Request — 1.x (#173)
by Akihito
04:21 queued 02:55
created

Invoker::noMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 5
cts 5
cp 1
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use BEAR\Resource\Exception\MethodNotAllowedException;
8
use function is_callable;
9
use Ray\Di\Di\Named;
10
11
final class Invoker implements InvokerInterface
12
{
13
    /**
14
     * @var NamedParameterInterface
15
     */
16
    private $params;
17
18
    /**
19
     * @var RenderInterface
20
     */
21
    private $optionsRenderer;
22
23
    /**
24
     * @Named("optionsRenderer=options")
25 100
     */
26
    public function __construct(NamedParameterInterface $params, RenderInterface $optionsRenderer)
27 100
    {
28 100
        $this->params = $params;
29 100
        $this->optionsRenderer = $optionsRenderer;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34 79
     */
35
    public function invoke(AbstractRequest $request) : ResourceObject
36 79
    {
37 79
        $callable = [$request->resourceObject, 'on' . ucfirst($request->method)];
38 11
        if (! is_callable($callable)) {
39
            return $this->noMethod($request);
40 68
        }
41 64
        $params = $this->params->getParameters($callable, $request->query);
42 61
        $response = call_user_func_array($callable, $params);
43 35
        if (! $response instanceof ResourceObject) {
44 35
            $request->resourceObject->body = $response;
45
            $response = $request->resourceObject;
46
        }
47 61
48
        return $response;
49
    }
50 11
51
    private function noMethod(AbstractRequest $request) : ResourceObject
52 11
    {
53 8
        if ($request->method === Request::OPTIONS) {
54 8
            $ro = $request->resourceObject;
55
            $ro->view = $this->optionsRenderer->render($request->resourceObject);
56 7
57
            return $ro;
58
        }
59 3
60
        throw new MethodNotAllowedException(get_class($request->resourceObject) . "::{({$request->method}}()", 405);
61
    }
62
}
63