Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Checker/ClaimCheckerManager.php

raw symbols SCIP
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 * This manager handles as many claim checkers as needed.
12 *
13 * @see \Jose\Tests\Component\Checker\ClaimCheckerManagerTest
14 */
15 class ClaimCheckerManager
16 {
17 /**
18 * @var ClaimChecker[]
19 */
20 private array $checkers = [];
21
22 /**
23 * @param ClaimChecker[] $checkers
24 */
25 public function __construct(iterable $checkers)
26 {
27 foreach ($checkers as $checker) {
28 $this->add($checker);
29 }
30 }
31
32 /**
33 * This method returns all checkers handled by this manager.
34 *
35 * @return ClaimChecker[]
36 */
37 public function getCheckers(): array
38 {
39 return $this->checkers;
40 }
41
42 /**
43 * This method checks all the claims passed as argument. All claims are checked against the claim checkers. If one
44 * fails, the InvalidClaimException is thrown.
45 *
46 * This method returns an array with all checked claims. It is up to the implementor to decide use the claims that
47 * have not been checked.
48 *
49 * @param string[] $mandatoryClaims
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 * @param string[] $mandatoryClaims
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 }