|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Pgsql; |
|
6
|
|
|
|
|
7
|
|
|
use function in_array; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Array representation to PHP array parser for PostgreSQL Server. |
|
11
|
|
|
*/ |
|
12
|
|
|
final class ArrayParser |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Convert an array from PostgresSQL to PHP. |
|
16
|
|
|
* |
|
17
|
|
|
* @param string|null $value String to convert. |
|
18
|
|
|
*/ |
|
19
|
11 |
|
public function parse(string|null $value): array|null |
|
20
|
|
|
{ |
|
21
|
11 |
|
return $value !== null && $value[0] === '{' |
|
22
|
11 |
|
? $this->parseArray($value) |
|
23
|
11 |
|
: null; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Parse PostgreSQL array encoded in string. |
|
28
|
|
|
* |
|
29
|
|
|
* @param string $value String to parse. |
|
30
|
|
|
* @param int $i parse starting position. |
|
31
|
|
|
*/ |
|
32
|
11 |
|
private function parseArray(string $value, int &$i = 0): array |
|
33
|
|
|
{ |
|
34
|
11 |
|
if ($value[++$i] === '}') { |
|
35
|
1 |
|
++$i; |
|
36
|
1 |
|
return []; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
11 |
|
for ($result = [];; ++$i) { |
|
40
|
11 |
|
$result[] = match ($value[$i]) { |
|
41
|
11 |
|
'{' => $this->parseArray($value, $i), |
|
42
|
11 |
|
',', '}' => null, |
|
43
|
11 |
|
'"' => $this->parseQuotedString($value, $i), |
|
44
|
11 |
|
default => $this->parseUnquotedString($value, $i), |
|
45
|
11 |
|
}; |
|
46
|
|
|
|
|
47
|
11 |
|
if ($value[$i] === '}') { |
|
48
|
11 |
|
++$i; |
|
49
|
11 |
|
return $result; |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
|
|
|
|
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Parses quoted string. |
|
56
|
|
|
*/ |
|
57
|
2 |
|
private function parseQuotedString(string $value, int &$i): string |
|
58
|
|
|
{ |
|
59
|
2 |
|
for ($result = '', ++$i;; ++$i) { |
|
60
|
2 |
|
if ($value[$i] === '\\') { |
|
61
|
2 |
|
++$i; |
|
62
|
2 |
|
} elseif ($value[$i] === '"') { |
|
63
|
2 |
|
++$i; |
|
64
|
2 |
|
return $result; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
2 |
|
$result .= $value[$i]; |
|
68
|
|
|
} |
|
|
|
|
|
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Parses unquoted string. |
|
73
|
|
|
*/ |
|
74
|
11 |
|
private function parseUnquotedString(string $value, int &$i): string|null |
|
75
|
|
|
{ |
|
76
|
11 |
|
for ($result = '';; ++$i) { |
|
77
|
11 |
|
if (in_array($value[$i], [',', '}'], true)) { |
|
78
|
11 |
|
return $result !== 'NULL' |
|
79
|
11 |
|
? $result |
|
80
|
11 |
|
: null; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
11 |
|
$result .= $value[$i]; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example: