| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Jose\Component\Checker; |
| 6 |
|
| 7 |
use function array_key_exists; |
| 8 |
use function count; |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
class ClaimCheckerManager |
| 16 |
{ |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
private array $checkers = []; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public function __construct(iterable $checkers) |
| 26 |
{ |
| 27 |
foreach ($checkers as $checker) { |
| 28 |
$this->add($checker); |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
public function getCheckers(): array |
| 38 |
{ |
| 39 |
return $this->checkers; |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
public function check(array $claims, array $mandatoryClaims = []): array |
| 52 |
{ |
| 53 |
$this->checkMandatoryClaims($mandatoryClaims, $claims); |
| 54 |
$checkedClaims = []; |
| 55 |
foreach ($this->checkers as $claim => $checker) { |
| 56 |
if (array_key_exists($claim, $claims)) { |
| 57 |
$checker->checkClaim($claims[$claim]); |
| 58 |
$checkedClaims[$claim] = $claims[$claim]; |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
return $checkedClaims; |
| 63 |
} |
| 64 |
|
| 65 |
private function add(ClaimChecker $checker): void |
| 66 |
{ |
| 67 |
$claim = $checker->supportedClaim(); |
| 68 |
$this->checkers[$claim] = $checker; |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
private function checkMandatoryClaims(array $mandatoryClaims, array $claims): void |
| 75 |
{ |
| 76 |
if (count($mandatoryClaims) === 0) { |
| 77 |
return; |
| 78 |
} |
| 79 |
$diff = array_keys(array_diff_key(array_flip($mandatoryClaims), $claims)); |
| 80 |
if (count($diff) !== 0) { |
| 81 |
throw new MissingMandatoryClaimException(sprintf( |
| 82 |
'The following claims are mandatory: %s.', |
| 83 |
implode(', ', $diff) |
| 84 |
), $diff); |
| 85 |
} |
| 86 |
} |
| 87 |
} |