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

Inspector::join()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Policy inspector (global)
4
 * User: moyo
5
 * Date: 2019-01-08
6
 * Time: 19:31
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
16
class Inspector implements Policy
17
{
18
    /**
19
     * @var Policy[]
20
     */
21
    private $policies = [];
22
23
    /**
24
     * @param Policy ...$policies
25
     */
26
    public function join(Policy ...$policies) : void
27
    {
28
        $this->policies = array_merge($this->policies, $policies);
29
    }
30
31
    /**
32
     * @param string $uri
33
     * @return bool
34
     */
35
    public function allowed(string $uri) : bool
36
    {
37
        return true;
38
    }
39
40
    /**
41
     * @param Context $ctx
42
     * @param ServerRequest $sr
43
     * @param int $route
44
     * @param callable $handler
45
     * @param array $params
46
     * @return Response|null
47
     */
48
    public function request(
49
        Context $ctx,
50
        ServerRequest $sr,
51
        int $route,
52
        callable $handler = null,
53
        array $params = []
54
    ) : ?Response {
55
        foreach ($this->policies as $policy) {
56
            if ($policy->allowed($sr->getUri()->getPath())) {
57
                if ($result = $policy->request(...func_get_args())) {
58
                    return $result;
59
                }
60
            }
61
        }
62
        return null;
63
    }
64
65
    /**
66
     * @param ServerRequest $sr
67
     * @param Response $respond
68
     * @return Response
69
     */
70
    public function response(ServerRequest $sr, Response $respond) : Response
71
    {
72
        foreach ($this->policies as $policy) {
73
            if ($policy->allowed($sr->getUri()->getPath())) {
74
                $respond = $policy->response($sr, $respond);
75
            }
76
        }
77
        return $respond;
78
    }
79
}
80