Completed
Pull Request — master (#15643)
by Dmitry
10:34
created

InConditionBuilder::buildValues()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7.2269

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 10
cts 12
cp 0.8333
rs 8.2222
c 0
b 0
f 0
cc 7
eloc 13
nc 10
nop 3
crap 7.2269
1
<?php
2
3
namespace yii\db\conditions;
4
5
use yii\db\ExpressionBuilderInterface;
6
use yii\db\ExpressionBuilderTrait;
7
use yii\db\ExpressionInterface;
8
use yii\db\Query;
9
10
/**
11
 * Class InConditionBuilder builds objects of [[InCondition]]
12
 *
13
 * @author Dmytro Naumenko <[email protected]>
14
 * @since 2.0.14
15
 */
16
class InConditionBuilder implements ExpressionBuilderInterface
17
{
18
    use ExpressionBuilderTrait;
19
20
    /**
21
     * Method builds the raw SQL from the $expression that will not be additionally
22
     * escaped or quoted.
23
     *
24
     * @param ExpressionInterface|InCondition $expression the expression to be built.
25
     * @param array $params the binding parameters.
26
     * @return string the raw SQL that will not be additionally escaped or quoted.
27
     */
28 248
    public function build(ExpressionInterface $expression, array &$params = [])
29
    {
30 248
        $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...
31 248
        $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...
32 248
        $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...
33
34 248
        if ($column === []) {
35
            // no columns to test against
36
            return $operator === 'IN' ? '0=1' : '';
37
        }
38
39 248
        if ($values instanceof Query) {
40 14
            return $this->buildSubqueryInCondition($operator, $column, $values, $params);
41
        }
42
43 234
        if (!is_array($values) && !$values instanceof \Traversable) {
44
            // ensure values is an array
45 3
            $values = (array) $values;
46
        }
47 234
        if ($column instanceof \Traversable || ((is_array($column) || $column instanceof \Countable) && count($column) > 1)) {
48 18
            return $this->buildCompositeInCondition($operator, $column, $values, $params);
49
        }
50
51 219
        if (is_array($column)) {
52 148
            $column = reset($column);
53
        }
54
55 219
        $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...
56 219
        if (empty($sqlValues)) {
57 21
            return $operator === 'IN' ? '0=1' : '';
58
        }
59
60 219
        if (strpos($column, '(') === false) {
61 219
            $column = $this->queryBuilder->db->quoteColumnName($column);
62
        }
63 219
        if (count($sqlValues) > 1) {
64 146
            return "$column $operator (" . implode(', ', $sqlValues) . ')';
65
        }
66
67 152
        $operator = $operator === 'IN' ? '=' : '<>';
68
69 152
        return $column . $operator . reset($sqlValues);
70
    }
71
72
    /**
73
     * Builds $values to be used in [[InCondition]]
74
     *
75
     * @param ConditionInterface|InCondition $condition
76
     * @param array $values
77
     * @param array $params the binding parameters
78
     * @return array of prepared for SQL placeholders
79
     */
80 219
    protected function buildValues(ConditionInterface $condition, $values, &$params)
81
    {
82 219
        $sqlValues = [];
83 219
        $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...
84
85 219
        foreach ($values as $i => $value) {
86 219
            if (is_array($value) || $value instanceof \ArrayAccess) {
87
                $value = isset($value[$column]) ? $value[$column] : null;
88
            }
89 219
            if ($value === null) {
90
                $sqlValues[$i] = 'NULL';
91 219
            } elseif ($value instanceof ExpressionInterface) {
92 3
                $sqlValues[$i] = $this->queryBuilder->buildExpression($value, $params);
93
            } else {
94 219
                $sqlValues[$i] = $this->queryBuilder->bindParam($value, $params);
95
            }
96
        }
97
98 219
        return $sqlValues;
99
    }
100
101
    /**
102
     * Builds SQL for IN condition.
103
     *
104
     * @param string $operator
105
     * @param array|string $columns
106
     * @param Query $values
107
     * @param array $params
108
     * @return string SQL
109
     */
110 14
    protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
111
    {
112 14
        $sql = $this->queryBuilder->buildExpression($values, $params);
113
114 14
        if (is_array($columns)) {
115 4
            foreach ($columns as $i => $col) {
116 4
                if (strpos($col, '(') === false) {
117 4
                    $columns[$i] = $this->queryBuilder->db->quoteColumnName($col);
118
                }
119
            }
120
121 4
            return '(' . implode(', ', $columns) . ") $operator $sql";
122
        }
123
124 10
        if (strpos($columns, '(') === false) {
125 10
            $columns = $this->queryBuilder->db->quoteColumnName($columns);
126
        }
127
128 10
        return "$columns $operator $sql";
129
    }
130
131
    /**
132
     * Builds SQL for IN condition.
133
     *
134
     * @param string $operator
135
     * @param array|\Traversable $columns
136
     * @param array $values
137
     * @param array $params
138
     * @return string SQL
139
     */
140 12
    protected function buildCompositeInCondition($operator, $columns, $values, &$params)
141
    {
142 12
        $vss = [];
143 12
        foreach ($values as $value) {
144 12
            $vs = [];
145 12
            foreach ($columns as $column) {
146 12
                if (isset($value[$column])) {
147 12
                    $vs[] = $this->queryBuilder->bindParam($value[$column], $params);
148
                } else {
149 12
                    $vs[] = 'NULL';
150
                }
151
            }
152 12
            $vss[] = '(' . implode(', ', $vs) . ')';
153
        }
154
155 12
        if (empty($vss)) {
156
            return $operator === 'IN' ? '0=1' : '';
157
        }
158
159 12
        $sqlColumns = [];
160 12
        foreach ($columns as $i => $column) {
161 12
            $sqlColumns[] = strpos($column, '(') === false ? $this->queryBuilder->db->quoteColumnName($column) : $column;
162
        }
163
164 12
        return '(' . implode(', ', $sqlColumns) . ") $operator (" . implode(', ', $vss) . ')';
165
    }
166
}
167