Passed
Push — master ( 927e42...56a221 )
by Blixit
02:05
created

Matcher::addAllowedField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Blixit\EventSourcing\Store\Matcher;
6
7
use function array_merge;
8
use function implode;
9
use function in_array;
10
use function sprintf;
11
12
class Matcher implements MatcherInterface
13
{
14
    /** @var FilterObject[] $fields */
15
    protected $fields = [];
16
17
    /** @var string[] $allowedFields */
18
    protected $allowedFields = [];
19
20
    /**
21
     * @param FilterObject[] $fields
22
     * @param string[]       $allowedFields
23
     */
24
    public function __construct(array $fields, array $allowedFields = [])
25
    {
26
        $this->allowedFields = array_merge($allowedFields, $this->allowedFields);
27
        foreach ($fields as $field) {
28
            $this->addSearchField($field);
29
        }
30
    }
31
32
    /**
33
     * @return FilterObject[]
34
     */
35
    public function getFields() : array
36
    {
37
        return $this->fields;
38
    }
39
40
    public function addAllowedField(string $field) : void
41
    {
42
        if (in_array($field, $this->allowedFields)) {
43
            return;
44
        }
45
        $this->allowedFields[] = $field;
46
    }
47
48
    /**
49
     * @throws MatcherException
50
     */
51
    public function addSearchField(FilterObject $filterObject) : void
52
    {
53
        if (! in_array($filterObject->getField(), $this->allowedFields)) {
54
            throw new MatcherException(
55
                sprintf(
56
                    'Field "%s" is not allowed. Allowed: %s',
57
                    $filterObject->getField(),
58
                    implode(', ', $this->allowedFields)
59
                )
60
            );
61
        }
62
        $this->fields[$filterObject->getField()] = $filterObject;
63
    }
64
}
65