-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathStructuredParser.php
More file actions
82 lines (71 loc) · 1.93 KB
/
StructuredParser.php
File metadata and controls
82 lines (71 loc) · 1.93 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
<?php
declare(strict_types=1);
namespace Yiisoft\Db\Pgsql\Data;
use function preg_match;
use function strcspn;
use function stripslashes;
use function strlen;
use function substr;
/**
* Structured type representation to PHP array parser for PostgreSQL Server.
*/
final class StructuredParser
{
/**
* Converts structured (composite) type value from PostgreSQL to PHP array.
*
* @param string $value Value to parse.
*
* @return (string|null)[]|null Parsed value.
*
* @psalm-return non-empty-list<null|string>|null
*/
public function parse(string $value): ?array
{
if ($value[0] !== '(') {
return null;
}
return $this->parseComposite($value);
}
/**
* Parses PostgreSQL composite type value encoded in string.
*
* @param string $value String to parse.
*
* @return (string|null)[] Parsed value.
*
* @psalm-return non-empty-list<null|string>
*/
private function parseComposite(string $value): array
{
for ($result = [], $i = 1;; ++$i) {
$result[] = match ($value[$i]) {
',', ')' => null,
'"' => $this->parseQuotedString($value, $i),
default => $this->parseUnquotedString($value, $i),
};
if ($value[$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 stripslashes($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;
}
}