Passed
Push — master ( 1d318a...e4f13f )
by Takashi
03:46 queued 01:19
created

AccessRestrictor::categoryIsUnderOneOf()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace Ttskch;
4
5
class AccessRestrictor
6
{
7
    /**
8
     * @var array
9
     */
10
    private $publicCategories;
11
12
    /**
13
     * @var array
14
     */
15
    private $publicTags;
16
17
    /**
18
     * @var array
19
     */
20
    private $privateCategories;
21
22
    /**
23
     * @var array
24
     */
25
    private $privateTags;
26
27
    public function __construct(array $publicCategories = [], array $publicTags = [], array $privateCategories = [], array $privateTags = [])
28
    {
29
        $this->publicCategories = $publicCategories;
30
        $this->publicTags = $publicTags;
31
        $this->privateCategories = $privateCategories;
32
        $this->privateTags = $privateTags;
33
    }
34
35
    /**
36
     * @param string $category
37
     * @param array $tags
38
     * @return bool
39
     */
40
    public function isPublic($category, array $tags)
41
    {
42
        $isPublic = false;
43
44
        if (
45
            empty($this->publicCategories) ||
46
            $this->categoryIsUnderOneOf($category, $this->publicCategories) ||
47
            empty($this->publicTags) ||
48
            $this->atLeastOnetagIsIn($tags, $this->publicTags)
49
        ) {
50
            $isPublic = true;
51
        }
52
53
        if ($this->categoryIsUnderOneOf($category, $this->privateCategories) || $this->atLeastOnetagIsIn($tags, $this->privateTags)) {
54
            $isPublic = false;
55
        }
56
57
        return $isPublic;
58
    }
59
60
    /**
61
     * @param string $needle
62
     * @param array $haystacks
63
     * @return bool
64
     */
65
    public function categoryIsUnderOneOf($needle, array $haystacks)
66
    {
67
        foreach ($haystacks as $haystack) {
68
            if (preg_match(sprintf('#^%s#', $haystack), $needle)) {
69
                return true;
70
            }
71
        }
72
73
        return false;
74
    }
75
76
    /**
77
     * @param array $needles
78
     * @param array $haystacks
79
     * @return bool
80
     */
81
    public function atLeastOneTagIsIn(array $needles, array $haystacks)
82
    {
83
        foreach ($haystacks as $haystack) {
84
            foreach ($needles as $needle) {
85
                if ($needle === $haystack) {
86
                    return true;
87
                }
88
            }
89
        }
90
91
        return false;
92
    }
93
}
94