Completed
Push — 1.x ( 7efb78...079849 )
by Akihito
04:35 queued 02:43
created

OptionsRenderer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 1
cbo 2
dl 0
loc 72
rs 10
ccs 22
cts 22
cp 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A render() 0 10 1
A getAllows() 0 11 3
A __construct() 0 5 1
A getEntityBody() 0 9 2
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 Doctrine\Common\Annotations\Reader;
10
11
/**
12
 * RFC2616 OPTIONS method renderer
13
 *
14
 * Set resource request information to `headers` and `view` in ResourceObject.
15
 *
16
 * @link https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
17
 * @see /docs/options/README.md
18
 */
19
final class OptionsRenderer implements RenderInterface
20
{
21
    /**
22
     * @var Reader
23
     */
24
    private $reader;
25
26
    /**
27
     * @var OptionsMethods
28
     */
29
    private $optionsMethod;
30
31
    /**
32
     * @param Reader $reader
33
     */
34 84
    public function __construct(Reader $reader)
35
    {
36 84
        $this->reader = $reader;
37 84
        $this->optionsMethod = new OptionsMethods($reader);
38 84
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 4
    public function render(ResourceObject $ro)
44
    {
45 4
        $ro->headers['Content-Type'] = 'application/json';
46 4
        $allows = $this->getAllows((new \ReflectionClass($ro))->getMethods());
47 4
        $ro->headers['allow'] = implode(', ', $allows);
48 4
        $body = $this->getEntityBody($ro, $allows);
49 4
        $ro->view = json_encode($body, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
50
51 4
        return $ro;
52
    }
53
54
    /**
55
     * Return allowed methods
56
     *
57
     * @param \ReflectionMethod[] $methods
58
     *
59
     * @return array
60
     */
61 4
    private function getAllows(array $methods)
62
    {
63 4
        $allows = [];
64 4
        foreach ($methods as $method) {
65 4
            if (in_array($method->name, ['onGet', 'onPost', 'onPut', 'onPatch', 'onDelete', 'onHead'], true)) {
66 4
                $allows[] = strtoupper(substr($method->name, 2));
67
            }
68
        }
69
70 4
        return $allows;
71
    }
72
73
    /**
74
     * Return OPTIONS entity body
75
     *
76
     * @param ResourceObject $ro
77
     * @param array          $allows
78
     *
79
     * @return array
80
     */
81 4
    private function getEntityBody(ResourceObject $ro, $allows)
82
    {
83 4
        $mehtodList = [];
84 4
        foreach ($allows as $method) {
85 4
            $mehtodList[$method] = $this->optionsMethod->__invoke($ro, $method);
86
        }
87
88 4
        return $mehtodList;
89
    }
90
}
91