BaseValidator::validate()   A
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 9
nop 1
dl 0
loc 18
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MiladRahimi\Jwt\Validator;
6
7
use MiladRahimi\Jwt\Exceptions\ValidationException;
8
9
/**
10
 * The BaseValidator is an implementation of the Validator interface,
11
 * utilizing predefined rules to validate claims. It is strongly recommended
12
 * to use or extend this implementation rather than creating your own
13
 * Validator interface implementation.
14
 */
15
class BaseValidator implements Validator
16
{
17
    /**
18
     * @var array<string,array>
19
     */
20
    protected array $rules = [];
21
22
    /**
23
     * Add a new required rule
24
     */
25
    public function addRequiredRule(string $claimName, Rule $rule)
26
    {
27
        $this->rules[$claimName][] = [$rule, true];
28
    }
29
30
    /**
31
     * Add a new required rule
32
     */
33
    public function addOptionalRule(string $claimName, Rule $rule)
34
    {
35
        $this->rules[$claimName][] = [$rule, false];
36
    }
37
38
    /**
39
     * @inheritdoc
40
     */
41
    public function validate(array $claims)
42
    {
43
        foreach ($this->rules as $claimName => $rules) {
44
            $exists = isset($claims[$claimName]);
45
            $value = $exists ? $claims[$claimName] : null;
46
47
            foreach ($rules as $ruleAndState) {
48
                /**
49
                 * @var Rule $rule
50
                 * @var bool $required
51
                 */
52
                [$rule, $required] = $ruleAndState;
53
54
                if ($exists) {
55
                    $rule->validate($claimName, $value);
56
                } elseif ($required) {
57
                    $message = "The `$claimName` is required.";
58
                    throw  new ValidationException($message);
59
                }
60
            }
61
        }
62
    }
63
}
64