Completed
Push — master ( d5ece8...84095f )
by Rasmus
03:25 queued 01:34
created

StringArrayType::convertToPHP()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

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