Completed
Pull Request — 1.0.x-dev (#4)
by Patrick
02:06
created

HmacGenerator::generateHmac()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 10
cp 0
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 12
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
    public function __construct(string $key, HmacDataTransformerInterface $hmacDataTransformer = null)
29
    {
30
        if (empty($key)) {
31
            throw new \InvalidArgumentException('The secret key can not be empty.');
32
        }
33
34
        $this->secretKey = $key;
35
36
        if ($hmacDataTransformer === null) {
37
            $hmacDataTransformer = new RequestHmacDataTransformer();
38
        }
39
40
        $this->hmacDataTransformer = $hmacDataTransformer;
41
    }
42
43
    public function generateHmac(string $data, string $hashingAlgorithm = self::DEFAULT_HASHING_ALGORITHM): string
44
    {
45
        if (empty($data)) {
46
            throw new \InvalidArgumentException('Data can not be empty.');
47
        }
48
49
        if (!($hmac = @\hash_hmac($hashingAlgorithm, $data, $this->secretKey))) {
50
            throw new \LogicException("The hashing algorithm [$hashingAlgorithm] is not supported.");
51
        }
52
53
        return $hmac;
54
    }
55
56
    public function generateHmacForRequest(RequestAdapterInterface $request): string
57
    {
58
        $data = $this->hmacDataTransformer->getDataForRequest($request);
59
60
        return $this->generateHmac($data);
61
    }
62
}
63