1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
/** |
4
|
|
|
* This file is part of the theroadbunch/bouncer package. |
5
|
|
|
* |
6
|
|
|
* (c) Dan McAdams <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace RoadBunch\Bouncer; |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class AbstractBouncer |
17
|
|
|
* |
18
|
|
|
* @author Dan McAdams <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
abstract class AbstractBouncer implements BouncerInterface |
21
|
|
|
{ |
22
|
|
|
/** @var string[] $subjectPool */ |
23
|
|
|
private array $subjectPool = []; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Provide an array of strings or a single string value. |
27
|
|
|
* If a single string is provided, values will be extracted with the delimiter ';' |
28
|
|
|
* |
29
|
|
|
* @param string|string[] $subjects |
30
|
|
|
*/ |
31
|
|
|
public function __construct(array|string $subjects = []) |
32
|
|
|
{ |
33
|
|
|
if (is_string($subjects)) { |
|
|
|
|
34
|
|
|
$subjects = $this->subjectsFromString($subjects); |
35
|
|
|
} |
36
|
|
|
array_walk($subjects, [$this, 'add']); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function has(string $subject): bool |
40
|
|
|
{ |
41
|
|
|
return in_array($subject, $this->subjectPool); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function add(string $subject): void |
45
|
|
|
{ |
46
|
|
|
if (!$this->has($subject)) { |
47
|
|
|
$this->subjectPool[] = $subject; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function remove(string $subject): void |
52
|
|
|
{ |
53
|
|
|
$key = array_search($subject, $this->subjectPool); |
54
|
|
|
|
55
|
|
|
if ($key !== false) { |
56
|
|
|
unset($this->subjectPool[$key]); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function subjectsFromString(string $subjects): array |
61
|
|
|
{ |
62
|
|
|
return array_filter( |
63
|
|
|
explode(';', $subjects), |
64
|
|
|
function ($subject) { |
65
|
|
|
return !empty(trim($subject)); |
66
|
|
|
} |
67
|
|
|
); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|