Passed
Push — master ( 898cc7...450add )
by Thomas Mauro
03:07
created

AbstractHashChecker::checkClaim()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 6
cp 0
crap 6
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\OpenIdClient\ClaimChecker;
6
7
use Jose\Component\Checker\ClaimChecker;
8
use Jose\Component\Checker\InvalidClaimException;
9
use function TMV\OpenIdClient\base64url_encode;
10
11
abstract class AbstractHashChecker implements ClaimChecker
12
{
13
    /** @var string */
14
    private $valueToCheck;
15
16
    /** @var string */
17
    private $alg;
18
19
    /**
20
     * SHashChecker constructor.
21
     *
22
     * @param string $valueToCheck
23
     * @param string $alg
24
     */
25
    public function __construct(string $valueToCheck, string $alg)
26
    {
27
        $this->valueToCheck = $valueToCheck;
28
        $this->alg = $alg;
29
    }
30
31
    private function getShaSize(string $alg): string
32
    {
33
        $size = \substr($alg, -3);
34
35
        switch ($size) {
36
            case '512':
37
                return 'sha512';
38
            case '384':
39
                return 'sha384';
40
            default:
41
                return 'sha256';
42
        }
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function checkClaim($value): void
49
    {
50
        $hash = \hash($this->getShaSize($this->alg), $this->valueToCheck, true);
51
        $generated = base64url_encode(\substr($hash, 0, \strlen($hash) / 2));
52
53
        if ($value !== $generated) {
54
            throw new InvalidClaimException(\sprintf($this->supportedClaim() . ' mismatch, expected %s, got: %s', $generated, $value), $this->supportedClaim(), $value);
55
        }
56
    }
57
}
58