AbstractHashChecker::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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