Completed
Pull Request — master (#43)
by Dominic
02:32
created

InfoResponse   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 16
lcom 2
cbo 2
dl 0
loc 82
ccs 0
cts 51
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setBody() 0 8 4
C parse() 0 33 8
A parseRow() 0 5 1
A parseSection() 0 16 3
1
<?php
2
3
namespace Disque\Command\Response;
4
5
class InfoResponse extends BaseResponse implements ResponseInterface
6
{
7
    /**
8
     * Set response body
9
     *
10
     * @param mixed $body Response body
11
     * @return void
12
     * @throws InvalidResponseException
13
     */
14
    public function setBody($body)
15
    {
16
        if ($body !== false && (empty($body) || !is_string($body))) {
17
            throw new InvalidResponseException($this->command, $body);
18
        }
19
20
        parent::setBody($body);
21
    }
22
23
    /**
24
     * Parse response
25
     *
26
     * Taken from https://github.com/nrk/predis/blob/v1.1/src/Command/ServerInfoV26x.php
27
     *
28
     * @return array Parsed response
29
     */
30
    public function parse()
31
    {
32
        if ($this->body === false || !is_string($this->body)) {
33
            return null;
34
        }
35
36
        $data = $this->body;
37
        $info = [];
38
39
        $current = null;
40
        $infoLines = preg_split('/\r?\n/', $data);
41
42
        if (isset($infoLines[0]) && $infoLines[0][0] !== '#') {
43
            return $this->parseSection($data);
44
        }
45
46
        foreach ($infoLines as $row) {
47
            if ($row === '') {
48
                continue;
49
            }
50
51
            if (preg_match('/^# (\w+)$/', $row, $matches)) {
52
                $info[$matches[1]] = [];
53
                $current = &$info[$matches[1]];
54
                continue;
55
            }
56
57
            list($k, $v) = $this->parseRow($row);
58
            $current[$k] = $v;
59
        }
60
61
        return $info;
62
    }
63
64
    protected function parseRow($row)
65
    {
66
        list($k, $v) = explode(':', $row, 2);
67
        return [$k, $v];
68
    }
69
70
    protected function parseSection($data)
71
    {
72
        $info = [];
73
        $infoLines = preg_split('/\r?\n/', $data);
74
75
        foreach ($infoLines as $row) {
76
            if (strpos($row, ':') === false) {
77
                continue;
78
            }
79
80
            list($k, $v) = $this->parseRow($row);
81
            $info[$k] = $v;
82
        }
83
84
        return $info;
85
    }
86
}
87