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