StringArrayType::convertToPHP()   B
last analyzed

Complexity

Conditions 8
Paths 4

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
cc 8
eloc 12
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 23
ccs 0
cts 12
cp 0
crap 72
rs 8.4444
1
<?php
2
3
namespace mindplay\sql\model\types\postgres;
4
5
use mindplay\sql\model\schema\Type;
6
use RuntimeException;
7
8
/**
9
 * Support for one-dimensional (Postgres) string arrays
10
 *
11
 * TODO add unit-test
12
 *
13
 * @see https://github.com/opensoft/doctrine-postgres-types/blob/master/src/Doctrine/DBAL/PostgresTypes/TextArrayType.php
14
 */
15
class StringArrayType implements Type
16
{
17
    /**
18
     * @see http://stackoverflow.com/a/19082849/1160901
19
     */
20
    const POSTGRES_SYNTAX_PATTERN = '/(?<=^\{|,)(([^,"{]*)|\s*"((?:[^"\\\\]|\\\\(?:.|[0-9]+|x[0-9a-f]+))*)"\s*)(,|(?<!^\{)(?=\}$))/iu';
21
22
    public function convertToSQL($value): string
23
    {
24
        if (empty($value)) {
25
            return '{}';
26
        }
27
28
        $result = '';
29
30
        foreach ($value as $part) {
31
            if (null === $part) {
32
                $result .= 'NULL,';
33
            } elseif ('' === $part) {
34
                $result .= '"",';
35
            } else {
36
                $result .= '"' . addcslashes($part, '"') . '",';
37
            }
38
        }
39
40
        return '{' . substr($result, 0, -1) . '}';
41
    }
42
43
    public function convertToPHP($value)
44
    {
45
        if (empty($value) || '{}' === $value) {
46
            return [];
47
        }
48
49
        if (gettype($value) !== 'string') {
50
            throw new RuntimeException('Expected string, got: ' . gettype($value));
51
        }
52
53
        $array = [];
54
55
        if (preg_match_all(self::POSTGRES_SYNTAX_PATTERN, $value, $matches, PREG_SET_ORDER)) {
56
            foreach ($matches as $match) {
57
                if ('' !== $match[3]) {
58
                    $array[] = stripcslashes($match[3]);
59
                } else {
60
                    $array[] = 'NULL' === $match[2] ? null : $match[2];
61
                }
62
            }
63
        }
64
65
        return $array;
66
    }
67
}
68