Failed Conditions
Push — v7 ( c80b33...0b1ec1 )
by Florent
04:39
created

ClaimCheckerManager::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\Checker;
15
16
use Jose\Component\Core\JWTInterface;
17
18
/**
19
 * Class ClaimCheckerManager.
20
 */
21
final class ClaimCheckerManager
22
{
23
    /**
24
     * @var ClaimCheckerInterface[]
25
     */
26
    private $checkers = [];
27
28
    /**
29
     * ClaimCheckerManager constructor.
30
     *
31
     * @param ClaimCheckerInterface[] $checkers
32
     */
33
    private function __construct(array $checkers)
34
    {
35
        foreach ($checkers as $checker) {
36
            $this->add($checker);
37
        }
38
    }
39
40
    /**
41
     * @param ClaimCheckerInterface[] $checkers
42
     *
43
     * @return ClaimCheckerManager
44
     */
45
    public static function create(array $checkers): ClaimCheckerManager
46
    {
47
        return new self($checkers);
48
    }
49
50
    /**
51
     * @param ClaimCheckerInterface $checker
52
     */
53
    private function add(ClaimCheckerInterface $checker)
54
    {
55
        $this->checkers[$checker->supportedClaim()] = $checker;
56
    }
57
58
    /**
59
     * @param JWTInterface $jwt
60
     */
61
    public function check(JWTInterface $jwt)
62
    {
63
        $claims = json_decode($jwt->getPayload(), true);
64
        if (!is_array($claims)) {
65
            throw new \InvalidArgumentException('The payload is does not contain claims.');
66
        }
67
68
        foreach ($this->checkers as $claim => $checker) {
69
            if (array_key_exists($claim, $claims)) {
70
                $checker->checkClaim($claims[$claim]);
71
            }
72
        }
73
    }
74
}
75