Passed
Push — master ( fb750b...6eebbc )
by Shiyu
02:41
created

Handler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * CORS handler
4
 * User: moyo
5
 * Date: 2019-01-08
6
 * Time: 19:08
7
 */
8
9
namespace Carno\Web\Policy\CORS;
10
11
use Carno\Coroutine\Context;
12
use Carno\HTTP\Standard\Response;
13
use Carno\HTTP\Standard\ServerRequest;
14
use Carno\Web\Contracts\Policy;
15
use FastRoute\Dispatcher;
16
17
class Handler implements Policy
18
{
19
    /**
20
     * @var string
21
     */
22
    private $prefix = null;
23
24
    /**
25
     * @var Processor
26
     */
27
    private $rule = null;
28
29
    /**
30
     * CORS constructor.
31
     * @param string $prefix
32
     * @param Processor $rule
33
     */
34
    public function __construct(string $prefix, Processor $rule)
35
    {
36
        $this->prefix = $prefix;
37
        $this->rule = $rule;
38
    }
39
40
    /**
41
     * @param string $uri
42
     * @return bool
43
     */
44
    public function allowed(string $uri) : bool
45
    {
46
        return substr($uri, 0, strlen($this->prefix)) === $this->prefix;
47
    }
48
49
    /**
50
     * @param Context $ctx
51
     * @param ServerRequest $sr
52
     * @param int $route
53
     * @param callable $handler
54
     * @param array $params
55
     * @return Response|null
56
     */
57
    public function request(
58
        Context $ctx,
59
        ServerRequest $sr,
60
        int $route,
61
        callable $handler = null,
62
        array $params = []
63
    ) : ?Response {
64
        if ($route === Dispatcher::FOUND) {
65
            return null;
66
        }
67
68
        if ($sr->getMethod() !== 'OPTIONS') {
69
            return null;
70
        }
71
72
        return $this->response($sr, new Response);
73
    }
74
75
    /**
76
     * @param ServerRequest $sr
77
     * @param Response $respond
78
     * @return Response
79
     */
80
    public function response(ServerRequest $sr, Response $respond) : Response
81
    {
82
        return $this->rule->process($sr, $respond);
83
    }
84
}
85