1 | <?php |
||
2 | |||
3 | namespace Psonic; |
||
4 | |||
5 | use Psonic\Contracts\Response as ResponseInterface; |
||
6 | use Psonic\Exceptions\CommandFailedException; |
||
7 | |||
8 | class SonicResponse implements ResponseInterface |
||
9 | { |
||
10 | private $message; |
||
11 | private $pieces; |
||
12 | private $results; |
||
13 | |||
14 | /** |
||
15 | * SonicResponse constructor. |
||
16 | * @param $message |
||
17 | */ |
||
18 | public function __construct($message) |
||
19 | { |
||
20 | $this->message = (string) $message; |
||
21 | $this->parse(); |
||
22 | } |
||
23 | |||
24 | /** |
||
25 | * parses the read buffer into a readable object |
||
26 | * @throws CommandFailedException |
||
27 | */ |
||
28 | private function parse() |
||
29 | { |
||
30 | $this->pieces = explode(" ", $this->message); |
||
31 | |||
32 | if(preg_match_all("/buffer\((\d+)\)/", $this->message, $matches)) { |
||
33 | $this->pieces['bufferSize'] = $matches[1][0]; |
||
34 | } |
||
35 | |||
36 | $this->pieces['status'] = $this->pieces[0]; |
||
37 | unset($this->pieces[0]); |
||
38 | |||
39 | if($this->pieces['status'] === 'ERR') { |
||
40 | throw new CommandFailedException($this->message); |
||
41 | } |
||
42 | |||
43 | if($this->pieces['status'] === 'RESULT') { |
||
44 | $this->pieces['count'] = (int) $this->pieces[1]; |
||
45 | unset($this->pieces[1]); |
||
46 | } |
||
47 | |||
48 | if($this->pieces['status'] === 'EVENT') { |
||
49 | $this->pieces['query_key'] = $this->pieces[2]; |
||
50 | $this->results = array_slice($this->pieces, 2, count($this->pieces)-4); |
||
51 | } |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * @return mixed |
||
56 | */ |
||
57 | public function getResults() |
||
58 | { |
||
59 | return $this->results; |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * @return string |
||
64 | */ |
||
65 | public function __toString() |
||
66 | { |
||
67 | return implode(" ", $this->pieces); |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * @param $key |
||
72 | * @return mixed |
||
73 | */ |
||
74 | public function get($key) |
||
75 | { |
||
76 | if(isset($this->pieces[$key])){ |
||
77 | return $this->pieces[$key]; |
||
78 | } |
||
79 | } |
||
80 | |||
81 | /** |
||
82 | * @return mixed |
||
83 | */ |
||
84 | public function getStatus(): string |
||
85 | { |
||
86 | return $this->get('status'); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
87 | } |
||
88 | |||
89 | /** |
||
90 | * @return int |
||
91 | */ |
||
92 | public function getCount():int |
||
93 | { |
||
94 | return $this->get('count') ?? 0; |
||
95 | } |
||
96 | } |
||
97 |