-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathClaimCheckerManager.php
85 lines (75 loc) · 2.19 KB
/
ClaimCheckerManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace Jose\Component\Checker;
use function array_key_exists;
use function count;
/**
* This manager handles as many claim checkers as needed.
*/
class ClaimCheckerManager
{
/**
* @var ClaimChecker[]
*/
private array $checkers = [];
/**
* @param ClaimChecker[] $checkers
*/
public function __construct(array $checkers)
{
foreach ($checkers as $checker) {
$this->add($checker);
}
}
/**
* This method returns all checkers handled by this manager.
*
* @return ClaimChecker[]
*/
public function getCheckers(): array
{
return $this->checkers;
}
/**
* This method checks all the claims passed as argument. All claims are checked against the claim checkers. If one
* fails, the InvalidClaimException is thrown.
*
* This method returns an array with all checked claims. It is up to the implementor to decide use the claims that
* have not been checked.
*
* @param string[] $mandatoryClaims
*/
public function check(array $claims, array $mandatoryClaims = []): array
{
$this->checkMandatoryClaims($mandatoryClaims, $claims);
$checkedClaims = [];
foreach ($this->checkers as $claim => $checker) {
if (array_key_exists($claim, $claims)) {
$checker->checkClaim($claims[$claim]);
$checkedClaims[$claim] = $claims[$claim];
}
}
return $checkedClaims;
}
private function add(ClaimChecker $checker): void
{
$claim = $checker->supportedClaim();
$this->checkers[$claim] = $checker;
}
/**
* @param string[] $mandatoryClaims
*/
private function checkMandatoryClaims(array $mandatoryClaims, array $claims): void
{
if (count($mandatoryClaims) === 0) {
return;
}
$diff = array_keys(array_diff_key(array_flip($mandatoryClaims), $claims));
if (count($diff) !== 0) {
throw new MissingMandatoryClaimException(sprintf(
'The following claims are mandatory: %s.',
implode(', ', $diff)
), $diff);
}
}
}