Repository navigation
Expand file tree
/
Copy pathSonicMessage.php
More file actions
95 lines (77 loc) · 2.07 KB
/
Copy pathSonicMessage.php
File metadata and controls
95 lines (77 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace SonicSearch;
/**
* Wrapper for constructing, serializing and deserializing of messages to and from Sonic.
*/
class SonicMessage
{
private $segments = null;
public function __construct(array $segments)
{
$this->segments = $segments;
}
public static function fromStr(string $message): SonicMessage
{
return new SonicMessage(explode(' ', $message));
}
public function serialize(): string
{
return implode(' ', $this->segments);
}
public function getVerb(): string
{
return $this->segments[0];
}
public function setVerb(string $verb)
{
$this->segments[0] = $verb;
}
public function getArgument(int $idx): string
{
return $this->segments[$idx + 1];
}
public function getArgumentInt(int $idx): int
{
return intval($this->getArgument($idx));
}
public function setArgument(int $idx, string $value)
{
$this->segments[$idx + 1] = $value;
}
public function setArgumentInt(int $idx, int $value)
{
$this->setArgument($idx, (string)$value);
}
public function setArgumentKeyVal(int $idx, string $key, string $value)
{
$this->setArgument($idx, "$key($value)");
}
public function asArgumentList(int $startIdx): SonicArgumentList
{
return SonicArgumentList::fromMessage($this->segments, $startIdx + 1);
}
public function asArray(int $startIdx): array
{
return array_slice($this->segments, $startIdx + 1);
}
public static function sanitizeValue(string &$value): string
{
return preg_replace('/[\r\n\t"]/', ' ', $value);
}
public static function quoted(string &$value): string
{
return '"' . $value . '"';
}
public function length(): int
{
$result = 0;
foreach ($this->segments as $segment) {
$result += strlen($segment);
}
return $result + count($this->segments) - 1;
}
public function argumentCnt(): int
{
return count($this->segments) - 1;
}
}