Completed
Push — master ( 19902b...129fa7 )
by Anton
03:10
created

Sha256::__construct()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 13
nc 6
nop 2
1
<?php
2
3
namespace Covery\Client\Credentials;
4
5
use Covery\Client\CredentialsInterface;
6
use Psr\Http\Message\RequestInterface;
7
8
class Sha256 implements CredentialsInterface
9
{
10
    /**
11
     * @var string
12
     */
13
    private $token;
14
    /**
15
     * @var string
16
     */
17
    private $secret;
18
19
    /**
20
     * Sha256 credentials constructor
21
     *
22
     * @param string $token
23
     * @param string $secret
24
     * @throws \Exception
25
     */
26
    public function __construct($token, $secret)
27
    {
28
        if (!is_string($token)) {
29
            throw new \InvalidArgumentException('Token must be string');
30
        } elseif (strlen($token) !== 32) {
31
            throw new \InvalidArgumentException('Token must be exact 32 characters long');
32
        }
33
        if (!is_string($secret)) {
34
            throw new \InvalidArgumentException('Secret must be string');
35
        } elseif (strlen($secret) !== 32) {
36
            throw new \InvalidArgumentException('Secret must be exact 32 characters long');
37
        }
38
        if (!function_exists('hash')) {
39
            throw new \Exception('Unable to build Sha256 credentials - function "hash" not exists');
40
        }
41
42
        $this->token = $token;
43
        $this->secret = $secret;
44
    }
45
46
    /**
47
     * Signs provided HTTP request
48
     *
49
     * @param RequestInterface $request
50
     * @return RequestInterface
51
     */
52
    public function signRequest(RequestInterface $request)
53
    {
54
        // Generating random NONCE
55
        $nonce = microtime(true) . mt_rand();
56
57
        // Generating signature
58
        $signature = hash('sha256', $nonce . $request->getBody()->getContents() . $this->secret);
59
60
        return $request
61
            ->withHeader('X-Auth-Token', $this->token)
62
            ->withHeader('X-Auth-Nonce', $nonce)
63
            ->withHeader('X-Auth-Signature', $signature)
64
            ->withHeader('X-Auth-Version', '1.0');
65
    }
66
}
67