ClaimCheckerManager   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 60
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A check() 0 13 4
A __construct() 0 7 2
A add() 0 11 2
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\Converter\JsonConverterInterface;
17
use Jose\Component\Core\JWTInterface;
18
19
/**
20
 * Class ClaimCheckerManager.
21
 */
22
final class ClaimCheckerManager
23
{
24
    /**
25
     * @var JsonConverterInterface
26
     */
27
    private $jsonConverter;
28
29
    /**
30
     * @var ClaimCheckerInterface[]
31
     */
32
    private $checkers = [];
33
34
    /**
35
     * ClaimCheckerManager constructor.
36
     *
37
     * @param JsonConverterInterface  $jsonConverter
38
     * @param ClaimCheckerInterface[] $checkers
39
     */
40
    public function __construct(JsonConverterInterface $jsonConverter, array $checkers)
41
    {
42
        $this->jsonConverter = $jsonConverter;
43
        foreach ($checkers as $checker) {
44
            $this->add($checker);
45
        }
46
    }
47
48
    /**
49
     * @param ClaimCheckerInterface $checker
50
     *
51
     * @return ClaimCheckerManager
52
     */
53
    private function add(ClaimCheckerInterface $checker): ClaimCheckerManager
54
    {
55
        $claim = $checker->supportedClaim();
56
        if (array_key_exists($claim, $this->checkers)) {
57
            throw new \InvalidArgumentException(sprintf('The claim checker "%s" is already supported.', $claim));
58
        }
59
60
        $this->checkers[$claim] = $checker;
61
62
        return $this;
63
    }
64
65
    /**
66
     * @param JWTInterface $jwt
67
     */
68
    public function check(JWTInterface $jwt)
69
    {
70
        $claims = $this->jsonConverter->decode($jwt->getPayload());
71
        if (!is_array($claims)) {
72
            throw new \InvalidArgumentException('The payload is does not contain claims.');
73
        }
74
75
        foreach ($this->checkers as $claim => $checker) {
76
            if (array_key_exists($claim, $claims)) {
77
                $checker->checkClaim($claims[$claim]);
78
            }
79
        }
80
    }
81
}
82