|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace kalanis\kw_groups\Processor; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
use kalanis\kw_groups\GroupsException; |
|
7
|
|
|
use kalanis\kw_groups\Interfaces\IProcessor; |
|
8
|
|
|
use kalanis\kw_groups\Interfaces\ISource; |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Class Basic |
|
13
|
|
|
* @package kalanis\kw_groups\Processor |
|
14
|
|
|
* Basic processing of groups |
|
15
|
|
|
*/ |
|
16
|
|
|
class Basic implements IProcessor |
|
17
|
|
|
{ |
|
18
|
|
|
protected ISource $source; |
|
19
|
|
|
/** @var array<string, array<int, string>> */ |
|
20
|
|
|
protected array $cachedTree = []; |
|
21
|
|
|
/** @var array<string, bool> */ |
|
22
|
|
|
protected array $cachedThrough = []; |
|
23
|
|
|
|
|
24
|
7 |
|
public function __construct(ISource $source) |
|
25
|
|
|
{ |
|
26
|
7 |
|
$this->source = $source; |
|
27
|
7 |
|
} |
|
28
|
|
|
|
|
29
|
7 |
|
public function canAccess(string $myGroup, string $wantedGroup): bool |
|
30
|
|
|
{ |
|
31
|
7 |
|
$this->cachedThrough = []; |
|
32
|
7 |
|
return $this->represents($wantedGroup, $myGroup); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param string $currentGroup is current one and is stable through all the time during questioning |
|
37
|
|
|
* @param string $wantedGroup is to compare and changing as is changed processed branch |
|
38
|
|
|
* @throws GroupsException |
|
39
|
|
|
* @return bool |
|
40
|
|
|
*/ |
|
41
|
7 |
|
protected function represents(string $currentGroup, string $wantedGroup): bool |
|
42
|
|
|
{ |
|
43
|
7 |
|
if ($currentGroup == $wantedGroup) { |
|
44
|
|
|
// it's me! |
|
45
|
3 |
|
return true; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
6 |
|
$groups = $this->cachedTree(); |
|
49
|
6 |
|
if (!isset($groups[$wantedGroup])) { |
|
50
|
|
|
// that group id does not exists in tree |
|
51
|
1 |
|
return false; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
5 |
|
foreach ($groups[$wantedGroup] as $group) { |
|
55
|
|
|
// against cyclic dependence - manually added groups |
|
56
|
4 |
|
if (isset($this->cachedThrough[$group])) { |
|
57
|
1 |
|
return false; |
|
58
|
|
|
} |
|
59
|
4 |
|
$this->cachedThrough[$group] = true; |
|
60
|
|
|
|
|
61
|
|
|
// somewhere in sub-groups |
|
62
|
4 |
|
if ($this->represents($currentGroup, $group)) { |
|
63
|
2 |
|
return true; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
5 |
|
return false; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @throws GroupsException |
|
71
|
|
|
* @return array<string, array<int, string>> |
|
72
|
|
|
*/ |
|
73
|
6 |
|
protected function cachedTree(): array |
|
74
|
|
|
{ |
|
75
|
6 |
|
if (empty($this->cachedTree)) { |
|
76
|
6 |
|
$this->cachedTree = $this->source->get(); |
|
77
|
|
|
} |
|
78
|
6 |
|
return $this->cachedTree; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
7 |
|
public function dropCache(): self |
|
82
|
|
|
{ |
|
83
|
7 |
|
$this->cachedTree = []; |
|
84
|
7 |
|
return $this; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|