StringFilter::getOperator()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\DoctrineORMAdminBundle\Filter;
15
16
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
17
use Sonata\AdminBundle\Form\Type\Filter\ChoiceType;
18
use Sonata\AdminBundle\Form\Type\Operator\StringOperatorType;
19
20
class StringFilter extends Filter
21
{
22
    public const CHOICES = [
23
        StringOperatorType::TYPE_CONTAINS => 'LIKE',
24
        StringOperatorType::TYPE_STARTS_WITH => 'LIKE',
25
        StringOperatorType::TYPE_ENDS_WITH => 'LIKE',
26
        StringOperatorType::TYPE_NOT_CONTAINS => 'NOT LIKE',
27
        StringOperatorType::TYPE_EQUAL => '=',
28
    ];
29
30
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data): void
31
    {
32
        if (!$data || !\is_array($data) || !\array_key_exists('value', $data) || null === $data['value']) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
33
            return;
34
        }
35
36
        $data['value'] = trim($data['value']);
37
38
        if (0 === \strlen($data['value'])) {
39
            return;
40
        }
41
42
        $type = $data['type'] ?? StringOperatorType::TYPE_CONTAINS;
43
        $operator = $this->getOperator((int) $type);
44
45
        // c.name > '1' => c.name OPERATOR :FIELDNAME
46
        $parameterName = $this->getNewParameterName($queryBuilder);
47
48
        $or = $queryBuilder->expr()->orX();
49
50
        if ($this->getOption('case_sensitive')) {
51
            $or->add(sprintf('%s.%s %s :%s', $alias, $field, $operator, $parameterName));
52
        } else {
53
            $or->add(sprintf('LOWER(%s.%s) %s :%s', $alias, $field, $operator, $parameterName));
54
        }
55
56
        if (StringOperatorType::TYPE_NOT_CONTAINS === $type) {
57
            $or->add($queryBuilder->expr()->isNull(sprintf('%s.%s', $alias, $field)));
58
        }
59
60
        $this->applyWhere($queryBuilder, $or);
61
62
        if (StringOperatorType::TYPE_EQUAL === $type) {
63
            $queryBuilder->setParameter(
64
                $parameterName,
65
                $this->getOption('case_sensitive') ? $data['value'] : mb_strtolower($data['value'])
66
            );
67
        } else {
68
            switch ($type) {
69
                case StringOperatorType::TYPE_STARTS_WITH:
70
                    $format = '%s%%';
71
                    break;
72
                case StringOperatorType::TYPE_ENDS_WITH:
73
                    $format = '%%%s';
74
                    break;
75
                default:
76
                    $format = $this->getOption('format');
77
78
                    if ('%%%s%%' !== $format) {
79
                        @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
80
                            'The "format" option is deprecated since sonata-project/doctrine-orm-admin-bundle 3.21 and will be removed in version 4.0.',
81
                            E_USER_DEPRECATED
82
                        );
83
                    }
84
            }
85
86
            $queryBuilder->setParameter(
87
                $parameterName,
88
                sprintf(
89
                    $format,
90
                    $this->getOption('case_sensitive') ? $data['value'] : mb_strtolower($data['value'])
91
                )
92
            );
93
        }
94
    }
95
96
    public function getDefaultOptions()
97
    {
98
        return [
99
            // NEXT_MAJOR: Remove the format option.
100
            'format' => '%%%s%%',
101
            'case_sensitive' => true,
102
        ];
103
    }
104
105
    public function getRenderSettings()
106
    {
107
        return [ChoiceType::class, [
108
            'field_type' => $this->getFieldType(),
109
            'field_options' => $this->getFieldOptions(),
110
            'label' => $this->getLabel(),
111
        ]];
112
    }
113
114
    private function getOperator(int $type): string
115
    {
116
        return self::CHOICES[$type] ?? self::CHOICES[StringOperatorType::TYPE_CONTAINS];
117
    }
118
}
119