Completed
Pull Request — 2.x (#311)
by
unknown
01:26
created

TranslationFieldFilter::applyKnplabsFilters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 4
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\TranslationBundle\Filter;
15
16
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
17
use Sonata\AdminBundle\Form\Type\Filter\DefaultType;
18
use Sonata\DoctrineORMAdminBundle\Filter\Filter;
19
use Sonata\TranslationBundle\Enum\TranslationFilterMode;
20
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
21
use Symfony\Component\Form\Extension\Core\Type\TextType;
22
23
final class TranslationFieldFilter extends Filter
24
{
25
    /**
26
     * @var string
27
     */
28
    private $filterMode;
29
30
    public function __construct(string $filterMode = TranslationFilterMode::GEDMO)
31
    {
32
        $this->filterMode = $filterMode;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
39
    {
40
        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...
41
            return;
42
        }
43
44
        $data['value'] = trim($data['value']);
45
46
        if (0 === \strlen($data['value'])) {
47
            return;
48
        }
49
        $joinAlias = 'tff';
50
        $filterMode = $this->getOption('filter_mode');
51
52
        // verify if the join is not already done
53
        $aliasAlreadyExists = false;
54
        foreach ($queryBuilder->getDQLParts()['join'] as $joins) {
55
            foreach ($joins as $join) {
56
                if ($join->getAlias() === $joinAlias) {
57
                    $aliasAlreadyExists = true;
58
                    break 2;
59
                }
60
            }
61
        }
62
63
        if (!$aliasAlreadyExists) {
64
            $queryBuilder->leftJoin($alias.'.translations', $joinAlias);
65
        }
66
67
        if (TranslationFilterMode::GEDMO === $filterMode) {
68
            // search on translation OR on normal field when using Gedmo
69
            $this->applyGedmoFilters($queryBuilder, $joinAlias, $alias, $field, $data);
70
71
            $this->active = true;
72
        } elseif (TranslationFilterMode::KNPLABS === $filterMode) {
73
            // search on translation OR on normal field when using Knp
74
            $this->applyKnplabsFilters($queryBuilder, $joinAlias, $field, $data);
75
76
            $this->active = true;
77
        } else {
78
            throw new \LogicException(
79
                sprintf('Invalid filter mode given: "%s"', $filterMode)
80
            );
81
        }
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    public function getDefaultOptions()
88
    {
89
        return [
90
            'field_type' => TextType::class,
91
            'operator_type' => HiddenType::class,
92
            'filter_mode' => $this->filterMode,
93
            'operator_options' => [],
94
        ];
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function getRenderSettings()
101
    {
102
        return [DefaultType::class, [
103
            'field_type' => $this->getFieldType(),
104
            'field_options' => $this->getFieldOptions(),
105
            'operator_type' => $this->getOption('operator_type'),
106
            'operator_options' => $this->getOption('operator_options'),
107
            'label' => $this->getLabel(),
108
        ]];
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    protected function association(ProxyQueryInterface $queryBuilder, $data)
115
    {
116
        $alias = $queryBuilder->entityJoin($this->getParentAssociationMappings());
117
118
        return [$this->getOption('alias', $alias), $this->getFieldName()];
119
    }
120
121
    /**
122
     * @param mixed[] $data
123
     */
124
    private function applyGedmoFilters(ProxyQueryInterface $queryBuilder, string $joinAlias, string $alias, string $field, $data): void
125
    {
126
        $this->applyWhere($queryBuilder, $queryBuilder->expr()->orX(
127
            $queryBuilder->expr()->andX(
128
                $queryBuilder->expr()->eq($joinAlias.'.field', $queryBuilder->expr()->literal($field)),
129
                $queryBuilder->expr()->like(
130
                    $joinAlias.'.content',
131
                    $queryBuilder->expr()->literal('%'.$data['value'].'%')
132
                )
133
            ),
134
            $queryBuilder->expr()->like(
135
                sprintf('%s.%s', $alias, $field),
136
                $queryBuilder->expr()->literal('%'.$data['value'].'%')
137
            )
138
        ));
139
    }
140
141
    /**
142
     * @param mixed[] $data
143
     */
144
    private function applyKnplabsFilters(ProxyQueryInterface $queryBuilder, string $joinAlias, string $field, $data): void
145
    {
146
        $this->applyWhere($queryBuilder,
147
            $queryBuilder->expr()->andX(
148
                $queryBuilder->expr()->like(
149
                    $joinAlias.".$field",
150
                    $queryBuilder->expr()->literal('%'.$data['value'].'%')
151
                )
152
            )
153
        );
154
    }
155
}
156