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

ArrayExpression   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 105
Duplicated Lines 4.76 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 16
c 0
b 0
f 0
lcom 1
cbo 2
dl 5
loc 105
ccs 0
cts 53
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getTypecast() 0 13 3
C buildUsing() 5 43 11
A buildSubqueryArray() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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