Verifier::verify()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace UMA\Psr7Hmac;
6
7
use Psr\Http\Message\RequestInterface;
8
use UMA\Psr7Hmac\Internal\HashCalculator;
9
use UMA\Psr7Hmac\Internal\HeaderNameNormalizer;
10
use UMA\Psr7Hmac\Internal\HeaderValidator;
11
use UMA\Psr7Hmac\Internal\RequestSerializer;
12
13
final class Verifier
14
{
15
    /**
16
     * @var HeaderValidator
17
     */
18
    private $validator;
19
20 86
    public function __construct()
21
    {
22 86
        $this->validator = (new HeaderValidator())
23 86
            ->addRule(Specification::AUTH_HEADER, Specification::AUTH_REGEXP)
24 86
            ->addRule(Specification::SIGN_HEADER, Specification::SIGN_REGEXP);
25 86
    }
26
27 84
    public function verify(RequestInterface $request, string $secret): bool
28
    {
29 84
        if (false === $matches = $this->validator->conforms($request)) {
0 ignored issues
show
introduced by
The condition false === $matches = $th...tor->conforms($request) is always false.
Loading history...
30 81
            return false;
31
        }
32
33 57
        $clientSideSignature = $matches[Specification::AUTH_HEADER][1];
34
35 57
        $serverSideSignature = HashCalculator::hmac(
36 57
            RequestSerializer::serialize($this->withoutUnsignedHeaders($request)),
37 57
            $secret
38
        );
39
40 57
        return \hash_equals($serverSideSignature, $clientSideSignature);
41
    }
42
43 57
    private function withoutUnsignedHeaders(RequestInterface $request): RequestInterface
44
    {
45 57
        $signedHeaders = \array_filter(\explode(',', $request->getHeaderLine(Specification::SIGN_HEADER)));
46
47 57
        foreach (\array_keys($request->getHeaders()) as $headerName) {
48 57
            if (!\in_array(HeaderNameNormalizer::normalize($headerName), $signedHeaders, true)) {
49 57
                $request = $request->withoutHeader($headerName);
50
            }
51
        }
52
53 57
        return $request;
54
    }
55
}
56