OptionsPreflightHandler::setAllowHeaders()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Kelemen\ApiNette\Handler;
4
5
use Kelemen\ApiNette\Response\ApiResponse;
6
use Kelemen\ApiNette\Response\TextApiResponse;
7
use Nette\Http\Request;
8
use Nette\Http\Response;
9
10
class OptionsPreflightHandler extends BaseHandler
11
{
12
    /** @var array */
13
    private $allowMethods = ['POST', 'DELETE', 'PUT', 'GET', 'OPTIONS'];
14
15
    /** @var array */
16
    private $allowHeaders = ['Authorization', 'X-Requested-With'];
17
18
    /** @var int */
19
    private $controlMaxAge = 0;
20
21
    /** @var array */
22
    private $exposeHeaders = [];
23
24
    /**
25
     * @param array $allowMethods
26
     * @return OptionsPreflightHandler
27
     */
28 2
    public function setAllowMethods(array $allowMethods)
29
    {
30 2
        $this->allowMethods = $allowMethods;
31 2
        return $this;
32
    }
33
34
    /**
35
     * @param array $allowHeaders
36
     * @return OptionsPreflightHandler
37
     */
38 2
    public function setAllowHeaders(array $allowHeaders)
39
    {
40 2
        $this->allowHeaders = $allowHeaders;
41 2
        return $this;
42
    }
43
44
    /**
45
     * @param int $controlMaxAge
46
     * @return OptionsPreflightHandler
47
     */
48 2
    public function setControlMaxAge($controlMaxAge)
49
    {
50 2
        $this->controlMaxAge = (int) $controlMaxAge;
51 2
        return $this;
52
    }
53
54
    /**
55
     * @param array $exposeHeaders
56
     * @return OptionsPreflightHandler
57
     */
58 2
    public function setExposeHeaders(array $exposeHeaders)
59
    {
60 2
        $this->exposeHeaders = $exposeHeaders;
61 2
        return $this;
62
    }
63
64
    /**
65
     * @param Request $request
66
     * @param Response $response
67
     * @param callable $next
68
     * @return ApiResponse
69
     */
70 4
    public function __invoke(Request $request, Response $response, callable $next)
71
    {
72 4
        if ($this->controlMaxAge) {
73 2
            $response->addHeader('Access-Control-Max-Age', $this->controlMaxAge);
74 1
        }
75
76 4
        if (count($this->exposeHeaders)) {
77 2
            $response->addHeader('Access-Control-Expose-Headers', implode(',', $this->exposeHeaders));
78 1
        }
79
80 4
        if (count($this->allowMethods)) {
81 4
            $response->addHeader('Access-Control-Allow-Methods', implode(',', $this->allowMethods));
82 2
        }
83
84 4
        if (count($this->allowHeaders)) {
85 4
            $response->addHeader('Access-Control-Allow-Headers', implode(',', $this->allowHeaders));
86 2
        }
87 4
        return new TextApiResponse(200);
88
    }
89
}
90