HashCalculator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 72.72%

Importance

Changes 0
Metric Value
wmc 5
eloc 13
dl 0
loc 51
ccs 8
cts 11
cp 0.7272
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A calculate() 0 8 2
A __construct() 0 6 1
A setPrivateKey() 0 4 1
A setMapper() 0 4 1
1
<?php
2
3
namespace kalanis\Restful\Security;
4
5
6
use kalanis\Restful\Exceptions\InvalidStateException;
7
use kalanis\Restful\Http\IInput;
8
use kalanis\Restful\Mapping\IMapper;
9
use kalanis\Restful\Mapping\MapperContext;
10
use Nette\Http\IRequest;
11
12
13
/**
14
 * Default auth token calculator implementation
15
 * @package kalanis\Restful\Security
16
 */
17 1
class HashCalculator implements IAuthTokenCalculator
18
{
19
20
    /** Fingerprint hash algorithm */
21
    public const HASH = 'sha256';
22
23
    private string $privateKey = '';
24
25
    private IMapper $mapper;
26
27
    public function __construct(
28
        MapperContext $mapperContext,
29
        IRequest      $httpRequest,
30
    )
31
    {
32 1
        $this->mapper = $mapperContext->getMapper($httpRequest->getHeader('content-type'));
33 1
    }
34
35
    /**
36
     * Set hash data calculator mapper
37
     */
38
    public function setMapper(IMapper $mapper): static
39
    {
40
        $this->mapper = $mapper;
41
        return $this;
42
    }
43
44
    /**
45
     * Set hash calculator security private key
46
     * @param string $key
47
     * @return $this
48
     */
49
    public function setPrivateKey(#[\SensitiveParameter] string $key): static
50
    {
51 1
        $this->privateKey = $key;
52 1
        return $this;
53
    }
54
55
    /**
56
     * Calculates hash
57
     *
58
     * @throws InvalidStateException
59
     */
60
    public function calculate(IInput $input): string
61
    {
62 1
        if (empty($this->privateKey)) {
63
            throw new InvalidStateException('Private key is not set');
64
        }
65
66 1
        $dataString = $this->mapper->stringify($input->getData(), false);
67 1
        return hash_hmac(self::HASH, $dataString, $this->privateKey);
68
    }
69
}
70