Completed
Push — master ( 40bf07...dbb18c )
by Mikhail
01:23
created

Authentication::generateContentHash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace R3bers\BittrexApi\Middleware;
6
7
use Closure;
8
use Psr\Http\Message\RequestInterface;
9
10
class Authentication
11
{
12
    /** @var string */
13
    private $key;
14
15
    /** @var string */
16
    private $secret;
17
18
    /** @var string */
19
    private $subaccountId;
20
21
    /**
22
     * Authentication constructor.
23
     * @param string $key
24
     * @param string $secret
25
     * @param string $subaccountId
26
     */
27 20
    public function __construct(string $key, string $secret, ?string $subaccountId = null)
28
    {
29 20
        $this->key = $key;
30 20
        $this->secret = $secret;
31 20
        $this->subaccountId = $subaccountId;
32 20
    }
33
34
    /**
35
     * @param callable $next
36
     * @return Closure
37
     */
38 18
    public function __invoke(callable $next)
39
    {
40 18
        return function (RequestInterface $request, array $options = []) use ($next) {
41 18
            $timestamp = round(microtime(true) * 1000);
42 18
            $contentHash = $this->generateContentHash($request->getBody()->__toString());
43
            $pre_sign = $timestamp .
44 18
                $request->getUri()->__toString() .
45 18
                $request->getMethod() .
46 18
                $contentHash .
47 18
                $this->subaccountId;
48 18
            $sign = $this->generateSign($pre_sign);
49
            $newHeaders = [
50 18
                'Api-Key' => $this->key,
51 18
                'Api-Timestamp' => $timestamp,
52 18
                'Api-Content-Hash' => $contentHash,
53 18
                'Api-Signature' => $sign
54
            ];
55 18
            foreach ($newHeaders as $key => $value) $request = $request->withAddedHeader($key, $value);
56 18
            if (!is_null($this->subaccountId)) $request = $request->withAddedHeader('Api-Subaccount-Id', $this->subaccountId);
57
58 18
            return $next($request, $options);
59 18
        };
60
    }
61
62
    /**
63
     * @param string $content
64
     * @return string
65
     */
66 18
    private function generateContentHash(string $content): string
67
    {
68 18
        return hash('sha512', $content);
69
    }
70
71
    /**
72
     * @param string $preSign
73
     * @return string
74
     */
75 18
    private function generateSign(string $preSign): string
76
    {
77 18
        return hash_hmac('sha512', $preSign, $this->secret);
78
    }
79
80
}