Passed
Push — master ( 79f846...b59e9f )
by Shiyu
02:12
created

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