Verifier   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 41
ccs 19
cts 19
cp 1
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A withoutUnsignedHeaders() 0 11 3
A verify() 0 14 2
A __construct() 0 5 1
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