Completed
Push — master ( 29b346...1faa7f )
by Amrouche
19s
created

src/Bridge/Doctrine/Orm/Filter/ExistsFilter.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Filter;
15
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
17
use ApiPlatform\Core\Exception\InvalidArgumentException;
18
use Doctrine\ORM\Mapping\ClassMetadataInfo;
19
use Doctrine\ORM\QueryBuilder;
20
21
/**
22
 * Filters the collection by whether a property value exists or not.
23
 *
24
 * For each property passed, if the resource does not have such property or if
25
 * the value is not one of ( "true" | "false" | "1" | "0" ) the property is ignored.
26
 *
27
 * A query parameter with key but no value is treated as `true`, e.g.:
28
 * Request: GET /products?brand[exists]
29
 * Interpretation: filter products which have a brand
30
 *
31
 * @author Teoh Han Hui <[email protected]>
32
 */
33
class ExistsFilter extends AbstractFilter
34
{
35
    const QUERY_PARAMETER_KEY = 'exists';
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function getDescription(string $resourceClass): array
41
    {
42
        $description = [];
43
44
        $properties = $this->properties;
45
        if (null === $properties) {
46
            $properties = array_fill_keys($this->getClassMetadata($resourceClass)->getFieldNames(), null);
47
        }
48
49
        foreach ($properties as $property => $unused) {
50
            if (!$this->isPropertyMapped($property, $resourceClass, true) || !$this->isNullableField($property, $resourceClass)) {
51
                continue;
52
            }
53
54
            $description[sprintf('%s[%s]', $property, self::QUERY_PARAMETER_KEY)] = [
55
                'property' => $property,
56
                'type' => 'bool',
57
                'required' => false,
58
            ];
59
        }
60
61
        return $description;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
68
    {
69
        if (
70
            !isset($value[self::QUERY_PARAMETER_KEY]) ||
71
            !$this->isPropertyEnabled($property, $resourceClass) ||
72
            !$this->isPropertyMapped($property, $resourceClass, true) ||
73
            !$this->isNullableField($property, $resourceClass)
74
        ) {
75
            return;
76
        }
77
78
        if (in_array($value[self::QUERY_PARAMETER_KEY], ['true', '1', '', null], true)) {
79
            $value = true;
80
        } elseif (in_array($value[self::QUERY_PARAMETER_KEY], ['false', '0'], true)) {
81
            $value = false;
82 View Code Duplication
        } else {
83
            $this->logger->notice('Invalid filter ignored', [
84
                'exception' => new InvalidArgumentException(sprintf('Invalid value for "%s[%s]", expected one of ( "%s" )', $property, self::QUERY_PARAMETER_KEY, implode('" | "', [
85
                    'true',
86
                    'false',
87
                    '1',
88
                    '0',
89
                ]))),
90
            ]);
91
92
            return;
93
        }
94
95
        $alias = 'o';
96
        $field = $property;
97
98 View Code Duplication
        if ($this->isPropertyNested($property, $resourceClass)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
            list($alias, $field) = $this->addJoinsForNestedProperty($property, $alias, $queryBuilder, $queryNameGenerator, $resourceClass);
100
        }
101
102
        $propertyParts = $this->splitPropertyParts($property, $resourceClass);
103
        $metadata = $this->getNestedMetadata($resourceClass, $propertyParts['associations']);
104
105
        if ($metadata->hasAssociation($field)) {
106
            if ($metadata->isCollectionValuedAssociation($field)) {
107
                $queryBuilder
108
                    ->andWhere(sprintf('%s.%s %s EMPTY', $alias, $field, $value ? 'IS NOT' : 'IS'));
109
110
                return;
111
            }
112
113
            $queryBuilder
114
                ->andWhere(sprintf('%s.%s %s NULL', $alias, $field, $value ? 'IS NOT' : 'IS'));
115
116
            return;
117
        }
118
119
        if ($metadata->hasField($field)) {
120
            $queryBuilder
121
                ->andWhere(sprintf('%s.%s %s NULL', $alias, $field, $value ? 'IS NOT' : 'IS'));
122
        }
123
    }
124
125
    /**
126
     * Determines whether the given property refers to a nullable field.
127
     *
128
     * @param string $property
129
     * @param string $resourceClass
130
     *
131
     * @return bool
132
     */
133
    protected function isNullableField(string $property, string $resourceClass): bool
134
    {
135
        $propertyParts = $this->splitPropertyParts($property, $resourceClass);
136
        $metadata = $this->getNestedMetadata($resourceClass, $propertyParts['associations']);
137
138
        $field = $propertyParts['field'];
139
140
        if ($metadata->hasAssociation($field)) {
141
            if ($metadata->isSingleValuedAssociation($field)) {
142
                if (!($metadata instanceof ClassMetadataInfo)) {
143
                    return false;
144
                }
145
146
                $associationMapping = $metadata->getAssociationMapping($field);
147
148
                return $this->isAssociationNullable($associationMapping);
149
            }
150
151
            return true;
152
        }
153
154
        if ($metadata instanceof ClassMetadataInfo && $metadata->hasField($field)) {
155
            return $metadata->isNullable($field);
156
        }
157
158
        return false;
159
    }
160
161
    /**
162
     * Determines whether an association is nullable.
163
     *
164
     * @param array $associationMapping
165
     *
166
     * @return bool
167
     *
168
     * @see https://github.com/doctrine/doctrine2/blob/v2.5.4/lib/Doctrine/ORM/Tools/EntityGenerator.php#L1221-L1246
169
     */
170
    private function isAssociationNullable(array $associationMapping): bool
171
    {
172
        if (isset($associationMapping['id']) && $associationMapping['id']) {
173
            return false;
174
        }
175
176
        if (!isset($associationMapping['joinColumns'])) {
177
            return true;
178
        }
179
180
        $joinColumns = $associationMapping['joinColumns'];
181
        foreach ($joinColumns as $joinColumn) {
182
            if (isset($joinColumn['nullable']) && !$joinColumn['nullable']) {
183
                return false;
184
            }
185
        }
186
187
        return true;
188
    }
189
}
190