Completed
Push — master ( 9cf2a9...b53505 )
by Mikhail
01:23
created

Authentication::generateSign()   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 18
    public function __construct(string $key, string $secret, ?string $subaccountId = null)
28
    {
29 18
        $this->key = $key;
30 18
        $this->secret = $secret;
31 18
        $this->subaccountId = $subaccountId;
32 18
    }
33
34
    /**
35
     * @param callable $next
36
     * @return Closure
37
     */
38 16
    public function __invoke(callable $next)
39
    {
40
        return function (RequestInterface $request, array $options = []) use ($next) {
41 16
            $timestamp = round(microtime(true) * 1000);
42 16
            $contentHash = $this->generateContentHash($request->getBody()->__toString());
43
            $pre_sign = $timestamp .
44 16
                $request->getUri()->__toString() .
45 16
                $request->getMethod() .
46 16
                $contentHash .
47 16
                $this->subaccountId;
48 16
            $sign = $this->generateSign($pre_sign);
49 16
            $request = $request->withAddedHeader('Api-Key', $this->key);
50 16
            $request = $request->withAddedHeader('Api-Timestamp', $timestamp);
51 16
            $request = $request->withAddedHeader('Api-Content-Hash', $contentHash);
52 16
            $request = $request->withAddedHeader('Api-Signature', $sign);
53 16
            if (!is_null($this->subaccountId)) {
54
                $request = $request->withAddedHeader('Api-Subaccount-Id', $this->subaccountId);
55
            }
56 16
            return $next($request, $options);
57 16
        };
58
    }
59
60
    /**
61
     * @param string $content
62
     * @return string
63
     */
64 16
    private function generateContentHash(string $content): string
65
    {
66 16
        return hash('sha512', $content);
67
    }
68
69
    /**
70
     * @param string $preSign
71
     * @return string
72
     */
73 16
    private function generateSign(string $preSign): string
74
    {
75 16
        return hash_hmac('sha512', $preSign, $this->secret);
76
    }
77
78
79
}
80