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

OptionsRenderer::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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