ModelFilter   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 124
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 3
dl 0
loc 124
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
B filter() 0 16 7
A getDefaultOptions() 0 11 1
A getRenderSettings() 0 10 1
A handleMultiple() 0 30 5
A association() 0 19 2
A getParentAlias() 0 17 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\DoctrineORMAdminBundle\Filter;
15
16
use Doctrine\Common\Collections\Collection;
17
use Doctrine\ORM\Mapping\ClassMetadata;
18
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
19
use Sonata\AdminBundle\Form\Type\Filter\DefaultType;
20
use Sonata\AdminBundle\Form\Type\Operator\EqualOperatorType;
21
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
22
23
class ModelFilter extends Filter
24
{
25
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data): void
26
    {
27
        if (!$data || !\is_array($data) || !\array_key_exists('value', $data) || empty($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...
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
    public function getDefaultOptions()
43
    {
44
        return [
45
            'mapping_type' => false,
46
            'field_name' => false,
47
            'field_type' => EntityType::class,
48
            'field_options' => [],
49
            'operator_type' => EqualOperatorType::class,
50
            'operator_options' => [],
51
        ];
52
    }
53
54
    public function getRenderSettings()
55
    {
56
        return [DefaultType::class, [
57
            'field_type' => $this->getFieldType(),
58
            'field_options' => $this->getFieldOptions(),
59
            'operator_type' => $this->getOption('operator_type'),
60
            'operator_options' => $this->getOption('operator_options'),
61
            'label' => $this->getLabel(),
62
        ]];
63
    }
64
65
    /**
66
     * For the record, the $alias value is provided by the association method (and the entity join method)
67
     *  so the field value is not used here.
68
     *
69
     * @param string $alias
70
     * @param mixed  $data
71
     *
72
     * @return mixed
73
     */
74
    protected function handleMultiple(ProxyQueryInterface $queryBuilder, $alias, $data)
75
    {
76
        if (0 === \count($data['value'])) {
77
            return;
78
        }
79
80
        $parameterName = $this->getNewParameterName($queryBuilder);
81
82
        if (isset($data['type']) && EqualOperatorType::TYPE_NOT_EQUAL === $data['type']) {
83
            $or = $queryBuilder->expr()->orX();
84
85
            $or->add($queryBuilder->expr()->notIn($alias, ':'.$parameterName));
86
87
            if (ClassMetadata::MANY_TO_MANY === $this->getOption('mapping_type')) {
88
                $or->add(
89
                    sprintf('%s.%s IS EMPTY', $this->getParentAlias($queryBuilder, $alias), $this->getFieldName())
90
                );
91
            } else {
92
                $or->add($queryBuilder->expr()->isNull(
93
                    sprintf('IDENTITY(%s.%s)', $this->getParentAlias($queryBuilder, $alias), $this->getFieldName())
94
                ));
95
            }
96
97
            $this->applyWhere($queryBuilder, $or);
98
        } else {
99
            $this->applyWhere($queryBuilder, $queryBuilder->expr()->in($alias, ':'.$parameterName));
100
        }
101
102
        $queryBuilder->setParameter($parameterName, $data['value']);
103
    }
104
105
    protected function association(ProxyQueryInterface $queryBuilder, $data)
106
    {
107
        $types = [
108
            ClassMetadata::ONE_TO_ONE,
109
            ClassMetadata::ONE_TO_MANY,
110
            ClassMetadata::MANY_TO_MANY,
111
            ClassMetadata::MANY_TO_ONE,
112
        ];
113
114
        if (!\in_array($this->getOption('mapping_type'), $types, true)) {
115
            throw new \RuntimeException('Invalid mapping type');
116
        }
117
118
        $associationMappings = $this->getParentAssociationMappings();
119
        $associationMappings[] = $this->getAssociationMapping();
120
        $alias = $queryBuilder->entityJoin($associationMappings);
121
122
        return [$alias, false];
0 ignored issues
show
Best Practice introduced by
The expression return array($alias, false); seems to be an array, but some of its elements' types (false) are incompatible with the return type of the parent method Sonata\DoctrineORMAdminB...ter\Filter::association of type string[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
123
    }
124
125
    /**
126
     * Retrieve the parent alias for given alias.
127
     * Root alias for direct association or entity joined alias for association depth >= 2.
128
     */
129
    private function getParentAlias(ProxyQueryInterface $queryBuilder, string $alias): string
130
    {
131
        $parentAlias = $rootAlias = current($queryBuilder->getRootAliases());
132
        $joins = $queryBuilder->getDQLPart('join');
133
        if (isset($joins[$rootAlias])) {
134
            foreach ($joins[$rootAlias] as $join) {
135
                if ($join->getAlias() === $alias) {
136
                    $parts = explode('.', $join->getJoin());
137
                    $parentAlias = $parts[0];
138
139
                    break;
140
                }
141
            }
142
        }
143
144
        return $parentAlias;
145
    }
146
}
147