-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathArrayParser.php
More file actions
88 lines (77 loc) · 2.09 KB
/
ArrayParser.php
File metadata and controls
88 lines (77 loc) · 2.09 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
<?php
declare(strict_types=1);
namespace Yiisoft\Db\Pgsql\Data;
use function preg_match;
use function strcspn;
use function stripcslashes;
use function strlen;
use function substr;
/**
* Array representation to PHP array parser for PostgreSQL Server.
*/
final class ArrayParser
{
/**
* Convert an array from PostgresSQL to PHP.
*
* @param string $value String to parse.
*
* @return (array|string|null)[]|null Parsed value.
*
* @psalm-return list<array|string|null>|null
*/
public function parse(string $value): ?array
{
return $value[0] === '{'
? $this->parseArray($value)
: null;
}
/**
* Parse PostgreSQL array encoded in string.
*
* @param string $value String to parse.
* @param int $i parse starting position.
*
* @return (array|string|null)[] Parsed value.
*
* @psalm-return list<array|string|null>
*/
private function parseArray(string $value, int &$i = 0): array
{
if ($value[++$i] === '}') {
++$i;
return [];
}
for ($result = [];; ++$i) {
$result[] = match ($value[$i]) {
'{' => $this->parseArray($value, $i),
',', '}' => null,
'"' => $this->parseQuotedString($value, $i),
default => $this->parseUnquotedString($value, $i),
};
if ($value[$i] === '}') {
++$i;
return $result;
}
}
}
/**
* Parses quoted string.
*/
private function parseQuotedString(string $value, int &$i): string
{
preg_match('/(?>[^"\\\\]+|\\\\.)*/', $value, $matches, 0, $i + 1);
$i += strlen($matches[0]) + 2;
return stripcslashes($matches[0]);
}
/**
* Parses unquoted string.
*/
private function parseUnquotedString(string $value, int &$i): ?string
{
$length = strcspn($value, ',}', $i);
$result = substr($value, $i, $length);
$i += $length;
return $result !== 'NULL' ? $result : null;
}
}