Completed
Push — master ( 5c78d7...6647db )
by thomas
8s
created

RequestFactory::response()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 8.2222
cc 7
eloc 12
nc 9
nop 1
crap 7
1
<?php
2
3
namespace BitWasp\Stratum\Request;
4
5
use BitWasp\Stratum\Exceptions\ApiError;
6
7
class RequestFactory
8
{
9
    /**
10
     * @var array
11
     */
12
    private $nonces = [];
13
14
    /**
15
     * @param string $method
16
     * @param array $params
17
     * @return Request
18
     */
19 3
    public function create($method, $params = array())
20
    {
21
        do {
22 3
            $id = mt_rand(0, PHP_INT_MAX);
23 3
        } while (in_array($id, $this->nonces));
24
25 3
        return new Request($id, $method, $params);
26
    }
27
28
    /**
29
     * @param $string
30
     * @return Response|Request
31
     * @throws \Exception
32
     */
33 20
    public function response($string)
34
    {
35 20
        $decoded = json_decode(trim($string), true);
36
37 20
        if (json_last_error() === JSON_ERROR_NONE) {
38 19
            $id = isset($decoded['id']) ? $decoded['id'] : null;
39
40 19
            if (isset($decoded['error'])) {
41 1
                throw new ApiError($id, $decoded['error']);
42 18
            } elseif (isset($decoded['method']) && isset($decoded['params'])) {
43 14
                return new Request($id, $decoded['method'], $decoded['params']);
44 5
            } elseif (isset($decoded['result'])) {
45 4
                return new Response($id, $decoded['result']);
46
            }
47
48 1
            throw new \Exception('Response missing error/params/result');
49
        }
50
51 1
        throw new \Exception('Invalid JSON');
52
    }
53
}
54