Completed
Push — remove-intl-polyfills ( 129df4...a6e727 )
by Alexander
16:22 queued 12:49
created

InConditionBuilder::buildCompositeInCondition()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8.0189

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 14
cts 15
cp 0.9333
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 16
nc 20
nop 4
crap 8.0189
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db\conditions;
9
10
use yii\db\ExpressionBuilderInterface;
11
use yii\db\ExpressionBuilderTrait;
12
use yii\db\ExpressionInterface;
13
use yii\db\Query;
14
15
/**
16
 * Class InConditionBuilder builds objects of [[InCondition]]
17
 *
18
 * @author Dmytro Naumenko <[email protected]>
19
 * @since 2.0.14
20
 */
21
class InConditionBuilder implements ExpressionBuilderInterface
22
{
23
    use ExpressionBuilderTrait;
24
25
26
    /**
27
     * Method builds the raw SQL from the $expression that will not be additionally
28
     * escaped or quoted.
29
     *
30
     * @param ExpressionInterface|InCondition $expression the expression to be built.
31
     * @param array $params the binding parameters.
32
     * @return string the raw SQL that will not be additionally escaped or quoted.
33
     */
34 274
    public function build(ExpressionInterface $expression, array &$params = [])
35
    {
36 274
        $operator = $expression->getOperator();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\ExpressionInterface as the method getOperator() does only exist in the following implementations of said interface: yii\db\conditions\AndCondition, yii\db\conditions\BetweenColumnsCondition, yii\db\conditions\BetweenCondition, yii\db\conditions\ConjunctionCondition, yii\db\conditions\ExistsCondition, yii\db\conditions\InCondition, yii\db\conditions\LikeCondition, yii\db\conditions\OrCondition, yii\db\conditions\SimpleCondition.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
37 274
        $column = $expression->getColumn();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\ExpressionInterface as the method getColumn() does only exist in the following implementations of said interface: yii\db\conditions\BetweenCondition, yii\db\conditions\InCondition, yii\db\conditions\LikeCondition, yii\db\conditions\SimpleCondition.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
38 274
        $values = $expression->getValues();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\ExpressionInterface as the method getValues() does only exist in the following implementations of said interface: yii\db\conditions\InCondition.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
39
40 274
        if ($column === []) {
41
            // no columns to test against
42
            return $operator === 'IN' ? '0=1' : '';
43
        }
44
45 274
        if ($values instanceof Query) {
46 14
            return $this->buildSubqueryInCondition($operator, $column, $values, $params);
47
        }
48
49 260
        if (!is_array($values) && !$values instanceof \Traversable) {
50
            // ensure values is an array
51 3
            $values = (array) $values;
52
        }
53 260
        if ($column instanceof \Traversable || ((is_array($column) || $column instanceof \Countable) && count($column) > 1)) {
54 18
            return $this->buildCompositeInCondition($operator, $column, $values, $params);
55
        }
56
57 245
        if (is_array($column)) {
58 169
            $column = reset($column);
59
        }
60
61 245
        $sqlValues = $this->buildValues($expression, $values, $params);
0 ignored issues
show
Compatibility introduced by
$expression of type object<yii\db\ExpressionInterface> is not a sub-type of object<yii\db\conditions\ConditionInterface>. It seems like you assume a child interface of the interface yii\db\ExpressionInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
62 245
        if (empty($sqlValues)) {
63 24
            return $operator === 'IN' ? '0=1' : '';
64
        }
65
66 242
        if (strpos($column, '(') === false) {
67 242
            $column = $this->queryBuilder->db->quoteColumnName($column);
68
        }
69 242
        if (count($sqlValues) > 1) {
70 154
            return "$column $operator (" . implode(', ', $sqlValues) . ')';
71
        }
72
73 167
        $operator = $operator === 'IN' ? '=' : '<>';
74
75 167
        return $column . $operator . reset($sqlValues);
76
    }
77
78
    /**
79
     * Builds $values to be used in [[InCondition]]
80
     *
81
     * @param ConditionInterface|InCondition $condition
82
     * @param array $values
83
     * @param array $params the binding parameters
84
     * @return array of prepared for SQL placeholders
85
     */
86 245
    protected function buildValues(ConditionInterface $condition, $values, &$params)
87
    {
88 245
        $sqlValues = [];
89 245
        $column = $condition->getColumn();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\conditions\ConditionInterface as the method getColumn() does only exist in the following implementations of said interface: yii\db\conditions\BetweenCondition, yii\db\conditions\InCondition, yii\db\conditions\LikeCondition, yii\db\conditions\SimpleCondition.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
90
91 245
        foreach ($values as $i => $value) {
92 242
            if (is_array($value) || $value instanceof \ArrayAccess) {
93
                $value = $value[$column] ?? null;
94
            }
95 242
            if ($value === null) {
96
                $sqlValues[$i] = 'NULL';
97 242
            } elseif ($value instanceof ExpressionInterface) {
98 3
                $sqlValues[$i] = $this->queryBuilder->buildExpression($value, $params);
99
            } else {
100 242
                $sqlValues[$i] = $this->queryBuilder->bindParam($value, $params);
101
            }
102
        }
103
104 245
        return $sqlValues;
105
    }
106
107
    /**
108
     * Builds SQL for IN condition.
109
     *
110
     * @param string $operator
111
     * @param array|string $columns
112
     * @param Query $values
113
     * @param array $params
114
     * @return string SQL
115
     */
116 14
    protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
117
    {
118 14
        $sql = $this->queryBuilder->buildExpression($values, $params);
119
120 14
        if (is_array($columns)) {
121 4
            foreach ($columns as $i => $col) {
122 4
                if (strpos($col, '(') === false) {
123 4
                    $columns[$i] = $this->queryBuilder->db->quoteColumnName($col);
124
                }
125
            }
126
127 4
            return '(' . implode(', ', $columns) . ") $operator $sql";
128
        }
129
130 10
        if (strpos($columns, '(') === false) {
131 10
            $columns = $this->queryBuilder->db->quoteColumnName($columns);
132
        }
133
134 10
        return "$columns $operator $sql";
135
    }
136
137
    /**
138
     * Builds SQL for IN condition.
139
     *
140
     * @param string $operator
141
     * @param array|\Traversable $columns
142
     * @param array $values
143
     * @param array $params
144
     * @return string SQL
145
     */
146 12
    protected function buildCompositeInCondition($operator, $columns, $values, &$params)
147
    {
148 12
        $vss = [];
149 12
        foreach ($values as $value) {
150 12
            $vs = [];
151 12
            foreach ($columns as $column) {
152 12
                if (isset($value[$column])) {
153 12
                    $vs[] = $this->queryBuilder->bindParam($value[$column], $params);
154
                } else {
155 12
                    $vs[] = 'NULL';
156
                }
157
            }
158 12
            $vss[] = '(' . implode(', ', $vs) . ')';
159
        }
160
161 12
        if (empty($vss)) {
162
            return $operator === 'IN' ? '0=1' : '';
163
        }
164
165 12
        $sqlColumns = [];
166 12
        foreach ($columns as $i => $column) {
167 12
            $sqlColumns[] = strpos($column, '(') === false ? $this->queryBuilder->db->quoteColumnName($column) : $column;
168
        }
169
170 12
        return '(' . implode(', ', $sqlColumns) . ") $operator (" . implode(', ', $vss) . ')';
171
    }
172
}
173