Completed
Pull Request — 3.x (#1042)
by Vincent
01:51
created

ArrayFilter::getRenderSettings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 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\ContainsOperatorType;
19
20
final class ArrayFilter extends Filter
21
{
22
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
23
    {
24
        if (!$data || !\is_array($data) || !\array_key_exists('type', $data) || !\array_key_exists('value', $data)) {
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...
25
            return;
26
        }
27
28
        if (!\is_array($data['value'])) {
29
            $data['value'] = [$data['value']];
30
        }
31
32
        $operator = ContainsOperatorType::TYPE_NOT_CONTAINS === $data['type'] ? 'NOT LIKE' : 'LIKE';
33
34
        $andConditions = $queryBuilder->expr()->andX();
35
        foreach ($data['value'] as $value) {
36
            $parameterName = $this->getNewParameterName($queryBuilder);
37
            $andConditions->add(sprintf('%s.%s %s :%s', $alias, $field, $operator, $parameterName));
38
39
            $queryBuilder->setParameter($parameterName, '%'.serialize($value).'%');
40
        }
41
42
        if (ContainsOperatorType::TYPE_EQUAL === $data['type']) {
43
            $andConditions->add(sprintf('%s.%s LIKE \'a:%s:%%\'', $alias, $field, \count($data['value'])));
44
        }
45
46
        $this->applyWhere($queryBuilder, $andConditions);
47
    }
48
49
    public function getDefaultOptions()
50
    {
51
        return [];
52
    }
53
54
    public function getRenderSettings()
55
    {
56
        return [ChoiceType::class, [
57
            'field_type' => $this->getFieldType(),
58
            'field_options' => $this->getFieldOptions(),
59
            'label' => $this->getLabel(),
60
        ]];
61
    }
62
}
63