Completed
Push — 1.0.x-dev ( 34a83d...bde745 )
by Felix
18s queued 11s
created

HmacGenerator::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
1
<?php declare(strict_types=1);
2
3
namespace Starlit\Request\Authenticator\Hmac;
4
5
use Starlit\Request\Authenticator\Hmac\Adapter\RequestAdapterInterface;
6
use Starlit\Request\Authenticator\Hmac\Transformer\HmacDataTransformerInterface;
7
use Starlit\Request\Authenticator\Hmac\Transformer\RequestHmacDataTransformer;
8
9
class HmacGenerator
10
{
11
    // see https://secure.php.net/manual/en/function.hash-hmac-algos.php
12
    private const DEFAULT_HASHING_ALGORITHM = 'sha256';
13
14
    /**
15
     * @var string
16
     */
17
    private $secretKey;
18
19
    /**
20
     * Transforms a request into a data string used by the hash_mac function. The default transfomer builds the
21
     * data string in the format "%method% %uri%\n%content%". Inject your own transformer if you want to support
22
     * a different data string.
23
     *
24
     * @var HmacDataTransformerInterface
25
     */
26
    private $hmacDataTransformer;
27
28 3
    public function __construct(string $key, HmacDataTransformerInterface $hmacDataTransformer = null)
29
    {
30 3
        if (empty($key)) {
31 1
            throw new \InvalidArgumentException('The secret key can not be empty.');
32
        }
33
34 3
        $this->secretKey = $key;
35
36 3
        if ($hmacDataTransformer === null) {
37 3
            $hmacDataTransformer = new RequestHmacDataTransformer();
38
        }
39
40 3
        $this->hmacDataTransformer = $hmacDataTransformer;
41 3
    }
42
43 3
    public function generateHmac(string $data, string $hashingAlgorithm = self::DEFAULT_HASHING_ALGORITHM): string
44
    {
45 3
        if (empty($data)) {
46 1
            throw new \InvalidArgumentException('Data can not be empty.');
47
        }
48
49 2
        if (!($hmac = @\hash_hmac($hashingAlgorithm, $data, $this->secretKey))) {
50 1
            throw new \LogicException("The hashing algorithm [$hashingAlgorithm] is not supported.");
51
        }
52
53 1
        return $hmac;
54
    }
55
56 2
    public function generateHmacForRequest(RequestAdapterInterface $request): string
57
    {
58 2
        $data = $this->hmacDataTransformer->getDataForRequest($request);
59
60 2
        return $this->generateHmac($data);
61
    }
62
}
63