Debian Codegraph @

vendor/clue/redis-protocol/src/Model/MultiBulkReply.php

raw
1 <?php
2
3 namespace Clue\Redis\Protocol\Model;
4
5 use Clue\Redis\Protocol\Serializer\SerializerInterface;
6 use InvalidArgumentException;
7 use UnexpectedValueException;
8
9 class MultiBulkReply implements ModelInterface
10 {
11 /**
12 * @var array|null
13 */
14 private $data;
15
16 /**
17 * create multi bulk reply (an array of other replies, usually bulk replies)
18 *
19 * @param array|null $data
20 * @throws InvalidArgumentException
21 */
22 public function __construct($data = null)
23 {
24 if ($data !== null && !is_array($data)) { // manual type check to support legacy PHP < 7.1
25 throw new InvalidArgumentException('Argument #1 ($data) expected array|null');
26 }
27 $this->data = $data;
28 }
29
30 public function getValueNative()
31 {
32 if ($this->data === null) {
33 return null;
34 }
35
36 $ret = array();
37 foreach ($this->data as $one) {
38 if ($one instanceof ModelInterface) {
39 $ret []= $one->getValueNative();
40 } else {
41 $ret []= $one;
42 }
43 }
44 return $ret;
45 }
46
47 public function getMessageSerialized(SerializerInterface $serializer)
48 {
49 return $serializer->getMultiBulkMessage($this->data);
50 }
51
52 /**
53 * Checks whether this model represents a valid unified request protocol message
54 *
55 * The new unified protocol was introduced in Redis 1.2, but it became the
56 * standard way for talking with the Redis server in Redis 2.0. The unified
57 * request protocol is what Redis already uses in replies in order to send
58 * list of items to clients, and is called a Multi Bulk Reply.
59 *
60 * @return boolean
61 * @link http://redis.io/topics/protocol
62 */
63 public function isRequest()
64 {
65 if (!$this->data) {
66 return false;
67 }
68
69 foreach ($this->data as $one) {
70 if (!($one instanceof BulkReply) && !is_string($one)) {
71 return false;
72 }
73 }
74
75 return true;
76 }
77
78 public function getRequestModel()
79 {
80 if (!$this->data) {
81 throw new UnexpectedValueException('Null-multi-bulk message can not be represented as a request, must contain string/bulk values');
82 }
83
84 $command = null;
85 $args = array();
86
87 foreach ($this->data as $one) {
88 if ($one instanceof BulkReply) {
89 $one = $one->getValueNative();
90 } elseif (!is_string($one)) {
91 throw new UnexpectedValueException('Message can not be represented as a request, must only contain string/bulk values');
92 }
93
94 if ($command === null) {
95 $command = $one;
96 } else {
97 $args []= $one;
98 }
99 }
100
101 return new Request($command, $args);
102 }
103 }