Completed
Pull Request — master (#738)
by Grégoire
13:17
created

ModelFilter   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 142
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 20
c 2
b 1
f 0
lcom 1
cbo 3
dl 0
loc 142
rs 10
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 25 and the first side effect is on line 20.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\DoctrineORMAdminBundle\Filter;
13
14
use Doctrine\Common\Collections\Collection;
15
use Doctrine\ORM\Mapping\ClassMetadataInfo;
16
use Doctrine\ORM\QueryBuilder;
17
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
18
use Sonata\CoreBundle\Form\Type\EqualType;
19
20
class ModelFilter extends Filter
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
26
    {
27
        if (!$data || !is_array($data) || !array_key_exists('value', $data) || empty($data['value'])) {
28
            return;
29
        }
30
31
        if ($data['value'] instanceof Collection) {
32
            $data['value'] = $data['value']->toArray();
33
        }
34
35
        if (!is_array($data['value'])) {
36
            $data['value'] = [$data['value']];
37
        }
38
39
        $this->handleMultiple($queryBuilder, $alias, $data);
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getDefaultOptions()
46
    {
47
        return [
48
            'mapping_type' => false,
49
            'field_name' => false,
50
            'field_type' => 'Symfony\Bridge\Doctrine\Form\Type\EntityType',
51
            'field_options' => [],
52
            'operator_type' => 'Sonata\CoreBundle\Form\Type\EqualType',
53
            'operator_options' => [],
54
        ];
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function getRenderSettings()
61
    {
62
<<<<<<< HEAD
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_SL
Loading history...
63
        return ['Sonata\AdminBundle\Form\Type\Filter\DefaultType', [
64
=======
65
        // NEXT_MAJOR: Remove this line when drop Symfony <2.8 support
66
        $type = method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix')
67
            ? 'Sonata\AdminBundle\Form\Type\Filter\DefaultType'
68
            : 'sonata_type_filter_default';
69
70
        return [$type, [
71
>>>>>>> origin/3.x
72
            'field_type' => $this->getFieldType(),
73
            'field_options' => $this->getFieldOptions(),
74
            'operator_type' => $this->getOption('operator_type'),
75
            'operator_options' => $this->getOption('operator_options'),
76
            'label' => $this->getLabel(),
77
        ]];
78
    }
79
80
    /**
81
     * For the record, the $alias value is provided by the association method (and the entity join method)
82
     *  so the field value is not used here.
83
     *
84
     * @param ProxyQueryInterface|QueryBuilder $queryBuilder
85
     * @param string                           $alias
86
     * @param mixed                            $data
87
     *
88
     * @return mixed
89
     */
90
    protected function handleMultiple(ProxyQueryInterface $queryBuilder, $alias, $data)
91
    {
92
        if (count($data['value']) == 0) {
93
            return;
94
        }
95
96
        $parameterName = $this->getNewParameterName($queryBuilder);
97
98
        if (isset($data['type']) && $data['type'] == EqualType::TYPE_IS_NOT_EQUAL) {
99
            $or = $queryBuilder->expr()->orX();
100
101
            $or->add($queryBuilder->expr()->notIn($alias, ':'.$parameterName));
102
103
            if ($this->getOption('mapping_type') === ClassMetadataInfo::MANY_TO_MANY) {
104
                $or->add(
105
                    sprintf('%s.%s IS EMPTY', $this->getParentAlias($queryBuilder, $alias), $this->getFieldName())
106
                );
107
            } else {
108
                $or->add($queryBuilder->expr()->isNull(
109
                    sprintf('IDENTITY(%s.%s)', $this->getParentAlias($queryBuilder, $alias), $this->getFieldName())
110
                ));
111
            }
112
113
            $this->applyWhere($queryBuilder, $or);
114
        } else {
115
            $this->applyWhere($queryBuilder, $queryBuilder->expr()->in($alias, ':'.$parameterName));
116
        }
117
118
        $queryBuilder->setParameter($parameterName, $data['value']);
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    protected function association(ProxyQueryInterface $queryBuilder, $data)
125
    {
126
        $types = [
127
            ClassMetadataInfo::ONE_TO_ONE,
128
            ClassMetadataInfo::ONE_TO_MANY,
129
            ClassMetadataInfo::MANY_TO_MANY,
130
            ClassMetadataInfo::MANY_TO_ONE,
131
        ];
132
133
        if (!in_array($this->getOption('mapping_type'), $types)) {
134
            throw new \RuntimeException('Invalid mapping type');
135
        }
136
137
        $associationMappings = $this->getParentAssociationMappings();
138
        $associationMappings[] = $this->getAssociationMapping();
139
        $alias = $queryBuilder->entityJoin($associationMappings);
140
141
        return [$alias, false];
142
    }
143
144
    /**
145
     * Retrieve the parent alias for given alias.
146
     * Root alias for direct association or entity joined alias for association depth >= 2.
147
     *
148
     * @param ProxyQueryInterface $queryBuilder
149
     * @param string              $alias
150
     *
151
     * @return string
152
     */
153
    private function getParentAlias(ProxyQueryInterface $queryBuilder, $alias)
154
    {
155
        $parentAlias = $rootAlias = current($queryBuilder->getRootAliases());
156
        $joins = $queryBuilder->getDQLPart('join');
157
        if (isset($joins[$rootAlias])) {
158
            foreach ($joins[$rootAlias] as $join) {
159
                if ($join->getAlias() == $alias) {
160
                    $parts = explode('.', $join->getJoin());
161
                    $parentAlias = $parts[0];
162
163
                    break;
164
                }
165
            }
166
        }
167
168
        return $parentAlias;
169
    }
170
}
171