Completed
Push — 1.x ( 365e71...2c7718 )
by Akihito
9s
created

Invoker   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 6
dl 0
loc 64
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A invoke() 0 12 3
A invokeMethod() 0 16 3
A invokeOptions() 0 7 1
1
<?php
2
/**
3
 * This file is part of the BEAR.Resource package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace BEAR\Resource;
8
9
use BEAR\Resource\Exception\MethodNotAllowedException;
10
use Ray\Di\Di\Named;
11
12
final class Invoker implements InvokerInterface
13
{
14
    /**
15
     * @var NamedParameterInterface
16
     */
17
    private $params;
18
19
    /**
20
     * @var RenderInterface
21
     */
22
    private $optionsRenderer;
23
24
    /**
25
     * @Named("optionsRenderer=options")
26
     */
27 95
    public function __construct(NamedParameterInterface $params, RenderInterface $optionsRenderer)
28
    {
29 95
        $this->params = $params;
30 95
        $this->optionsRenderer = $optionsRenderer;
31 95
    }
32
33
    /**
34
     * {@inheritdoc}
35
     *
36
     * @throws MethodNotAllowedException
37
     */
38 71
    public function invoke(AbstractRequest $request)
39
    {
40 71
        $onMethod = 'on' . ucfirst($request->method);
41 71
        if (method_exists($request->resourceObject, $onMethod) === true) {
42 11
            return $this->invokeMethod($request, $onMethod);
43
        }
44 60
        if ($request->method === Request::OPTIONS) {
45 36
            return $this->invokeOptions($request);
46 36
        }
47
48 60
        throw new MethodNotAllowedException(get_class($request->resourceObject) . "::{($request->method}()", 405);
49 56
    }
50
51 55
    private function invokeMethod(AbstractRequest $request, string $onMethod) : ResourceObject
52
    {
53
        if ($request->resourceObject->uri instanceof AbstractUri) {
54
            $request->resourceObject->uri->query = $request->query;
55
            $request->resourceObject->uri->method = $request->method;
56
        }
57
        $params = $this->params->getParameters([$request->resourceObject, $onMethod], $request->query);
58 55
        $response = call_user_func_array([$request->resourceObject, $onMethod], $params);
59
60 55
        if (! $response instanceof ResourceObject) {
61 30
            $request->resourceObject->body = $response;
62 30
            $response = $request->resourceObject;
63
        }
64
65 55
        return $response;
66
    }
67
68
    private function invokeOptions(AbstractRequest $request) : ResourceObject
69
    {
70
        $ro = $request->resourceObject;
71
        $ro->view = $this->optionsRenderer->render($request->resourceObject);
72
73 11
        return $ro;
74
    }
75
}
76