Passed
Push — master ( 50332b...6b3eac )
by Dāvis
03:20
created

ValidatorChain::validate()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 5
nop 2
dl 0
loc 19
rs 8.2222
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Openidconnect\Specification;
4
5
use Lcobucci\JWT\Token;
6
7
class ValidatorChain
8
{
9
    /**
10
     * @var array
11
     */
12
    protected $validators = [];
13
14
    /**
15
     * @var array
16
     */
17
    protected $messages = [];
18
19
    /**
20
     * @param SpecificationInterface[] $validators
21
     *
22
     * @return $this
23
     */
24
    public function setValidators(array $validators)
25
    {
26
        $this->validators = [];
27
28
        foreach ($validators as $validator) {
29
            $this->addValidator($validator);
30
        }
31
32
        return $this;
33
    }
34
35
    /**
36
     * @param string                 $claim
37
     * @param SpecificationInterface $validator
38
     *
39
     * @return $this
40
     */
41
    public function addValidator(SpecificationInterface $validator)
42
    {
43
        $this->validators[$validator->getName()] = $validator;
44
45
        return $this;
46
    }
47
48
    /**
49
     * @param array $data
50
     * @param Token $token
51
     *
52
     * @return bool
53
     */
54
    public function validate(array $data, Token $token)
55
    {
56
        $valid = true;
57
        foreach ($this->validators as $claim => $validator) {
58
            if ($validator->isRequired() && false === $token->hasClaim($claim)) {
59
                $valid = false;
60
                $this->messages[$claim] = sprintf("Missing required value for claim %s", $claim);
61
                continue;
62
            } elseif (empty($data[$claim]) || false === $token->hasClaim($claim)) {
63
                continue;
64
            }
65
66
            if (!$validator->isSatisfiedBy($data[$claim], $token->getClaim($claim))) {
67
                $valid = false;
68
                $this->messages[$claim] = $validator->getMessage();
69
            }
70
        }
71
72
        return $valid;
73
    }
74
75
    /**
76
     * @param $name
77
     *
78
     * @return bool
79
     */
80
    public function hasValidator($name)
81
    {
82
        return array_key_exists($name, $this->validators);
83
    }
84
85
    /**
86
     * @param $name
87
     *
88
     * @return mixed
89
     */
90
    public function getValidator($name)
91
    {
92
        return $this->validators[$name];
93
    }
94
95
    /**
96
     * @return array
97
     */
98
    public function getMessages()
99
    {
100
        return $this->messages;
101
    }
102
}
103