Completed
Push — master ( b794f5...f9eb18 )
by Andrii
03:04
created

ArrayExpression::buildUsing()   C

Complexity

Conditions 11
Paths 25

Size

Total Lines 43
Code Lines 27

Duplication

Lines 5
Ratio 11.63 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 5
loc 43
ccs 0
cts 33
cp 0
rs 5.2653
cc 11
eloc 27
nc 25
nop 2
crap 132

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace hiapi\db;
4
5
use yii\db\Expression;
6
use yii\db\Query;
7
use yii\db\QueryBuilder;
8
use yii\db\QueryInterface;
9
10
/**
11
 * ArrayExpression represents a SQL expression that represents a PostreSQL array.
12
 *
13
 * Expressions of this type can be used for example in conditions, like:
14
 *
15
 * ```php
16
 * $query->andWhere(['@>', 'items', new ArrayExpression([1, 2, 3], 'integer')])
17
 * ```
18
 *
19
 * which will result in a condition `WHERE "items" @> ARRAY[1, 2, 3]::integer[]`.
20
 *
21
 * @author Dmitry Naumenko <[email protected]>
22
 */
23
class ArrayExpression implements ExpressionInterface
24
{
25
    const PARAM_PREFIX = ':axp';
26
27
    /**
28
     * @var null|string the type of the array elements. Defaults to `null` which means the type is
29
     * not explicitly specified. This may result in an error if the type can not be inferred from the context.
30
     * @see https://www.postgresql.org/docs/9.6/static/arrays.html
31
     */
32
    protected $type;
33
34
    /**
35
     * @var array|QueryInterface|mixed the array content. Either represented as an array of values or a Query that
36
     * returns these values. A single value will be considered as an array containing one element.
37
     */
38
    protected $values;
39
40
    /**
41
     * ArrayExpression constructor.
42
     *
43
     * @param array|QueryInterface|mixed $values the array content. Either represented as an array of values or a Query that
44
     * returns these values. A single value will be considered as an array containing one element.
45
     * @param string|null $type the type of the array elements. Defaults to `null` which means the type is
46
     * not explicitly specified. This may result in an error if the type can not be inferred from the context.
47
     */
48
    public function __construct($values, $type = null)
49
    {
50
        $this->values = $values;
51
        $this->type = $type;
52
    }
53
54
    /**
55
     * @return string the typecast expression based on [[type]].
56
     */
57
    protected function getTypecast()
58
    {
59
        if ($this->type === null) {
60
            return '';
61
        }
62
63
        $result = '::' . $this->type;
64
        if (strpos($this->type, '[]') === false) {
65
            $result .= '[]';
66
        }
67
68
        return $result;
69
    }
70
71
    /**
72
     * @inheritdoc
73
     */
74
    public function buildUsing(QueryBuilder $queryBuilder, &$params = [])
75
    {
76
        $value = $this->values;
77
78
        if ($value instanceof Query) {
79
            list ($sql, $params) = $queryBuilder->build($value, $params);
80
            return $this->buildSubqueryArray($sql);
81
        }
82
83
        if (!is_array($value) && !$value instanceof \Traversable) {
84
            $value = [$value];
85
        }
86
87
        $placeholders = [];
88
        foreach ($value as $item) {
89
            if (is_array($item) || $item instanceof \Traversable) {
90
                $placeholders[] = (new self($item))->buildUsing($queryBuilder, $params);
91
                continue;
92
            }
93 View Code Duplication
            if ($item instanceof Query) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
                list ($sql, $params) = $queryBuilder->build($item, $params);
95
                $placeholders[] = $this->buildSubqueryArray($sql);
96
                continue;
97
            }
98
            if ($item instanceof ExpressionInterface) {
99
                $placeholders[] = $item->buildUsing($queryBuilder, $params);
100
                continue;
101
            }
102
            if ($item === null) {
103
                $placeholders[] = 'NULL';
104
                continue;
105
            }
106
107
            $placeholders[] = $placeholder = static::PARAM_PREFIX . count($params);
108
            $params[$placeholder] = $item;
109
        }
110
111
        if (empty($placeholders)) {
112
            return "'{}'";
113
        }
114
115
        return 'ARRAY[' . implode(', ', $placeholders) . ']' . $this->getTypecast();
116
    }
117
118
    /**
119
     * Build an array expression from a subquery SQL.
120
     * @param string $sql the subquery SQL.
121
     * @return string the subquery array expression.
122
     */
123
    protected function buildSubqueryArray($sql)
124
    {
125
        return 'ARRAY(' . $sql . ')' . $this->getTypecast();
126
    }
127
}
128