Completed
Push — master ( c5e2a6...55323d )
by thomas
21s
created

Assuan::send()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 1
nop 3
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 6
rs 10
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
    /**
14
     * @param ProcessInterface $process
15
     * @return Response
16
     * @throws RemotePinEntryException
17
     */
18
    public function parseResponse(ProcessInterface $process): Response
19
    {
20
        $data = [];
21
        $statuses = [];
22
        $comments = [];
23
        $okMsg = null;
24
25
        for (;;) {
26
            $buffer = $process->recv();
27
            foreach (explode("\n", $buffer) as $piece) {
28
                if (substr($piece, 0, 4) === "ERR ") {
29
                    $c = explode(" ", $piece, 3);
30
                    // don't change state, it's only a single line
31
                    throw new RemotePinEntryException($c[2], (int)$c[1]);
32
                }
33
34
                $prefix = substr($piece, 0, 2);
35
                if ($prefix === "D ") {
36
                    $data[] = substr($piece, 2);
37
                } else if ($prefix === "S ") {
38
                    $statuses[] = substr($piece, 2);
39
                } else if ($prefix === "# ") {
40
                    // don't change state, it's only a single line
41
                    $comments[] = substr($piece, 2);
42
                } else if ($prefix === "OK") {
43
                    if (strlen($piece) > 2) {
44
                        $okMsg = substr($piece, 3);
45
                    }
46
                    break 2;
47
                }
48
            }
49
        }
50
51
        return new Response($data, $statuses, $comments, $okMsg);
52
    }
53
54
    /**
55
     * @param ProcessInterface $process
56
     * @param string $command
57
     * @param string|null $params
58
     */
59
    public function send(ProcessInterface $process, string $command, string $params = null)
60
    {
61
        $process->send(sprintf("%s%s\n", $command, $params ? " {$params}" : ""));
62
    }
63
}
64