|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Pgsql; |
|
6
|
|
|
|
|
7
|
|
|
use function in_array; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Structured type representation to PHP array parser for PostgreSQL Server. |
|
11
|
|
|
*/ |
|
12
|
|
|
final class StructuredParser |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Converts structured (composite) type value from PostgreSQL to PHP array |
|
16
|
|
|
* |
|
17
|
|
|
* @param string $value String to convert. |
|
18
|
|
|
*/ |
|
19
|
6 |
|
public function parse(string $value): array|null |
|
20
|
|
|
{ |
|
21
|
6 |
|
if ($value[0] !== '(') { |
|
22
|
1 |
|
return null; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
6 |
|
return $this->parseComposite($value); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Parses PostgreSQL composite type value encoded in string. |
|
30
|
|
|
* |
|
31
|
|
|
* @param string $value String to parse. |
|
32
|
|
|
*/ |
|
33
|
6 |
|
private function parseComposite(string $value): array |
|
34
|
|
|
{ |
|
35
|
6 |
|
for ($result = [], $i = 1;; ++$i) { |
|
36
|
6 |
|
$result[] = match ($value[$i]) { |
|
37
|
6 |
|
',', ')' => null, |
|
38
|
6 |
|
'"' => $this->parseQuotedString($value, $i), |
|
39
|
6 |
|
default => $this->parseUnquotedString($value, $i), |
|
40
|
6 |
|
}; |
|
41
|
|
|
|
|
42
|
6 |
|
if ($value[$i] === ')') { |
|
43
|
6 |
|
return $result; |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
|
|
|
|
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Parses quoted string. |
|
50
|
|
|
*/ |
|
51
|
6 |
|
private function parseQuotedString(string $value, int &$i): string |
|
52
|
|
|
{ |
|
53
|
6 |
|
for ($result = '', ++$i;; ++$i) { |
|
54
|
6 |
|
if ($value[$i] === '\\') { |
|
55
|
1 |
|
++$i; |
|
56
|
6 |
|
} elseif ($value[$i] === '"') { |
|
57
|
6 |
|
++$i; |
|
58
|
6 |
|
return $result; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
6 |
|
$result .= $value[$i]; |
|
62
|
|
|
} |
|
|
|
|
|
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* Parses unquoted string. |
|
67
|
|
|
*/ |
|
68
|
6 |
|
private function parseUnquotedString(string $value, int &$i): string |
|
69
|
|
|
{ |
|
70
|
6 |
|
for ($result = '';; ++$i) { |
|
71
|
6 |
|
if (in_array($value[$i], [',', ')'], true)) { |
|
72
|
6 |
|
return $result; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
6 |
|
$result .= $value[$i]; |
|
76
|
|
|
} |
|
|
|
|
|
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
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: