Completed
Pull Request — master (#3)
by thomas
18:16
created

Assuan::parseResponse()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 22
nc 9
nop 1
dl 0
loc 34
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\PinEntry\Assuan;
6
7
use BitWasp\PinEntry\Exception\RemotePinEntryException;
8
use BitWasp\PinEntry\Process\ProcessInterface;
9
use BitWasp\PinEntry\Response;
10
11
class Assuan
12
{
13
    public function parseResponse(ProcessInterface $process)
14
    {
15
        $data = [];
16
        $statuses = [];
17
        $comments = [];
18
        $okMsg = null;
19
20
        for (;;) {
21
            $buffer = $process->recv();
22
            foreach (explode("\n", $buffer) as $piece) {
23
                if (substr($piece, 0, 4) === "ERR ") {
24
                    $c = explode(" ", $piece, 3);
25
                    // don't change state, it's only a single line
26
                    throw new RemotePinEntryException($c[2], (int)$c[1]);
27
                }
28
29
                $prefix = substr($piece, 0, 2);
30
                if ($prefix === "D ") {
31
                    $data[] = substr($piece, 2);
32
                } else if ($prefix === "S ") {
33
                    $statuses[] = substr($piece, 2);
34
                } else if ($prefix === "# ") {
35
                    // don't change state, it's only a single line
36
                    $comments[] = substr($piece, 2);
37
                } else if ($prefix === "OK") {
38
                    if (strlen($piece) > 2) {
39
                        $okMsg = substr($piece, 3);
40
                    }
41
                    break 2;
42
                }
43
            }
44
        }
45
46
        return new Response($data, $statuses, $comments, $okMsg);
47
    }
48
49
    public function send(ProcessInterface $process, string $command, string $params = null)
50
    {
51
        $process->send(sprintf("%s%s\n", $command, $params ? " {$params}" : ""));
52
    }
53
}
54