Completed
Push — 1.x ( 81bd95...a6cf87 )
by Akihito
16s queued 14s
created

Invoker::methodNoExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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