Passed
Push — bouncer-from-strings ( 831a9e...147aba )
by Daniel
11:13
created

AbstractBouncer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 15
dl 0
loc 46
rs 10
c 1
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A remove() 0 6 2
A add() 0 4 2
A has() 0 3 1
A subjectsFromString() 0 6 1
A __construct() 0 6 2
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)) {
0 ignored issues
show
introduced by
The condition is_string($subjects) is always false.
Loading history...
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