StringArrayType   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 25
c 0
b 0
f 0
dl 0
loc 51
ccs 0
cts 23
cp 0
rs 10
wmc 13

2 Methods

Rating   Name   Duplication   Size   Complexity  
A convertToSQL() 0 19 5
B convertToPHP() 0 23 8
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