Completed
Push — 15630-fixed-like-escaping ( 1da559 )
by Alexander
11:08
created

LikeConditionBuilder   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 96.97%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 4
dl 0
loc 93
ccs 32
cts 33
cp 0.9697
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
D build() 0 37 10
A getEscapeSql() 0 8 2
A parseOperator() 0 11 3
1
<?php
2
3
namespace yii\db\conditions;
4
5
use yii\base\InvalidArgumentException;
6
use yii\db\ExpressionBuilderInterface;
7
use yii\db\ExpressionBuilderTrait;
8
use yii\db\ExpressionInterface;
9
10
/**
11
 * Class LikeConditionBuilder builds objects of [[LikeCondition]]
12
 *
13
 * @author Dmytro Naumenko <[email protected]>
14
 * @since 2.0.14
15
 */
16
class LikeConditionBuilder implements ExpressionBuilderInterface
17
{
18
    use ExpressionBuilderTrait;
19
20
    /**
21
     * @var array map of chars to their replacements in LIKE conditions.
22
     * By default it's configured to escape `%`, `_` and `\` with `\`.
23
     */
24
    protected $escapingReplacements = [
25
        '%' => '\%',
26
        '_' => '\_',
27
        '\\' => '\\\\',
28
    ];
29
    /**
30
     * @var string|null character used to escape special characters in LIKE conditions.
31
     * By default it's assumed to be `\`.
32
     */
33
    protected $escapeCharacter;
34
35
    /**
36
     * Method builds the raw SQL from the $expression that will not be additionally
37
     * escaped or quoted.
38
     *
39
     * @param ExpressionInterface|LikeCondition $expression the expression to be built.
40
     * @param array $params the binding parameters.
41
     * @return string the raw SQL that will not be additionally escaped or quoted.
42
     */
43 78
    public function build(ExpressionInterface $expression, array &$params = [])
44
    {
45 78
        $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\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...
46 78
        $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...
47 78
        $values = $expression->getValue();
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 getValue() does only exist in the following implementations of said interface: yii\db\ArrayExpression, yii\db\JsonExpression, yii\db\PdoValue, 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...
48 78
        $escape = $expression->getEscapingReplacements();
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 getEscapingReplacements() does only exist in the following implementations of said interface: yii\db\conditions\LikeCondition.

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...
49 78
        if ($escape === null || $escape === []) {
50 75
            $escape = $this->escapingReplacements;
51
        }
52
53 78
        list($andor, $not, $operator) = $this->parseOperator($operator);
54
55 78
        if (!is_array($values)) {
56 34
            $values = [$values];
57
        }
58
59 78
        if (empty($values)) {
60 16
            return $not ? '' : '0=1';
61
        }
62
63 62
        if (strpos($column, '(') === false) {
64 62
            $column = $this->queryBuilder->db->quoteColumnName($column);
65
        }
66
67 62
        $escapeSql = $this->getEscapeSql();
68 62
        $parts = [];
69 62
        foreach ($values as $value) {
70 62
            if ($value instanceof ExpressionInterface) {
71 24
                $phName = $this->queryBuilder->buildExpression($value, $params);
72
            } else {
73 50
                $phName = $this->queryBuilder->bindParam(empty($escape) ? $value : ('%' . strtr($value, $escape) . '%'), $params);
74
            }
75 62
            $parts[] = "{$column} {$operator} {$phName}{$escapeSql}";
76
        }
77
78 62
        return implode($andor, $parts);
79
    }
80
81
    /**
82
     * @return string
83
     */
84 62
    private function getEscapeSql()
85
    {
86 62
        if ($this->escapeCharacter !== null) {
87 18
            return " ESCAPE '{$this->escapeCharacter}'";
88
        }
89
90 44
        return '';
91
    }
92
93
    /**
94
     * @param string $operator
95
     * @return array
96
     */
97 78
    protected function parseOperator($operator)
98
    {
99 78
        if (!preg_match('/^(AND |OR |)(((NOT |))I?LIKE)/', $operator, $matches)) {
100
            throw new InvalidArgumentException("Invalid operator '$operator'.");
101
        }
102 78
        $andor = ' ' . (!empty($matches[1]) ? $matches[1] : 'AND ');
103 78
        $not = !empty($matches[3]);
104 78
        $operator = $matches[2];
105
106 78
        return [$andor, $not, $operator];
107
    }
108
}
109