Completed
Push — master ( aab50e...8053c5 )
by Han Hui
11s
created

ExistsFilter::isNullableField()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
cc 6
eloc 14
nc 5
nop 2
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
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Filter;
13
14
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
15
use ApiPlatform\Core\Exception\InvalidArgumentException;
16
use Doctrine\Common\Persistence\ManagerRegistry;
17
use Doctrine\ORM\Mapping\ClassMetadataInfo;
18
use Doctrine\ORM\QueryBuilder;
19
use Psr\Log\LoggerInterface;
20
use Symfony\Component\HttpFoundation\RequestStack;
21
22
/**
23
 * Filters the collection by whether a property value exists or not.
24
 *
25
 * For each property passed, if the resource does not have such property or if
26
 * the value is not one of ( "true" | "false" | "1" | "0" ) the property is ignored.
27
 *
28
 * A query parameter with key but no value is treated as `true`, e.g.:
29
 * Request: GET /products?brand[exists]
30
 * Interpretation: filter products which have a brand
31
 *
32
 * @author Teoh Han Hui <[email protected]>
33
 */
34
class ExistsFilter extends AbstractFilter
35
{
36
    const QUERY_PARAMETER_KEY = 'exists';
37
38
    public function __construct(ManagerRegistry $managerRegistry, RequestStack $requestStack, LoggerInterface $logger = null, array $properties = null)
39
    {
40
        parent::__construct($managerRegistry, $requestStack, $logger, $properties);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function getDescription(string $resourceClass): array
47
    {
48
        $description = [];
49
50
        $properties = $this->properties;
51
        if (null === $properties) {
52
            $properties = array_fill_keys($this->getClassMetadata($resourceClass)->getFieldNames(), null);
53
        }
54
55
        foreach ($properties as $property => $unused) {
56
            if (!$this->isPropertyMapped($property, $resourceClass, true) || !$this->isNullableField($property, $resourceClass)) {
57
                continue;
58
            }
59
60
            $description[sprintf('%s[%s]', $property, self::QUERY_PARAMETER_KEY)] = [
61
                'property' => $property,
62
                'type' => 'bool',
63
                'required' => false,
64
            ];
65
        }
66
67
        return $description;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
74
    {
75
        if (
76
            !isset($value[self::QUERY_PARAMETER_KEY]) ||
77
            !$this->isPropertyEnabled($property) ||
78
            !$this->isPropertyMapped($property, $resourceClass, true) ||
79
            !$this->isNullableField($property, $resourceClass)
80
        ) {
81
            return;
82
        }
83
84
        if (in_array($value[self::QUERY_PARAMETER_KEY], ['true', '1', '', null], true)) {
85
            $value = true;
86
        } elseif (in_array($value[self::QUERY_PARAMETER_KEY], ['false', '0'], true)) {
87
            $value = false;
88 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
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...
89
            $this->logger->notice('Invalid filter ignored', [
90
                'exception' => new InvalidArgumentException(sprintf('Invalid value for "%s[%s]", expected one of ( "%s" )', $property, self::QUERY_PARAMETER_KEY, implode('" | "', [
91
                    'true',
92
                    'false',
93
                    '1',
94
                    '0',
95
                ]))),
96
            ]);
97
98
            return;
99
        }
100
101
        $alias = 'o';
102
        $field = $property;
103
104
        if ($this->isPropertyNested($property)) {
105
            list($alias, $field) = $this->addJoinsForNestedProperty($property, $alias, $queryBuilder, $queryNameGenerator);
106
        }
107
108
        $propertyParts = $this->splitPropertyParts($property);
109
        $metadata = $this->getNestedMetadata($resourceClass, $propertyParts['associations']);
110
111
        if ($metadata->hasAssociation($field)) {
112
            if ($metadata->isCollectionValuedAssociation($field)) {
113
                $queryBuilder
114
                    ->andWhere(sprintf('%s.%s %s EMPTY', $alias, $field, $value ? 'IS NOT' : 'IS'));
115
116
                return;
117
            }
118
119
            $queryBuilder
120
                ->andWhere(sprintf('%s.%s %s NULL', $alias, $field, $value ? 'IS NOT' : 'IS'));
121
122
            return;
123
        }
124
125
        if ($metadata->hasField($field)) {
126
            $queryBuilder
127
                ->andWhere(sprintf('%s.%s %s NULL', $alias, $field, $value ? 'IS NOT' : 'IS'));
128
        }
129
    }
130
131
    /**
132
     * Determines whether the given property refers to a nullable field.
133
     *
134
     * @param string $property
135
     * @param string $resourceClass
136
     *
137
     * @return bool
138
     */
139
    protected function isNullableField(string $property, string $resourceClass): bool
140
    {
141
        $propertyParts = $this->splitPropertyParts($property);
142
        $metadata = $this->getNestedMetadata($resourceClass, $propertyParts['associations']);
143
144
        $field = $propertyParts['field'];
145
146
        if ($metadata->hasAssociation($field)) {
147
            if ($metadata->isSingleValuedAssociation($field)) {
148
                if (!($metadata instanceof ClassMetadataInfo)) {
149
                    return false;
150
                }
151
152
                $associationMapping = $metadata->getAssociationMapping($field);
153
154
                return $this->isAssociationNullable($associationMapping);
155
            }
156
157
            return true;
158
        }
159
160
        if ($metadata instanceof ClassMetadataInfo && $metadata->hasField($field)) {
161
            return $metadata->isNullable($field);
162
        }
163
164
        return false;
165
    }
166
167
    /**
168
     * Determines whether an association is nullable.
169
     *
170
     * @param array $associationMapping
171
     *
172
     * @return bool
173
     *
174
     * @see https://github.com/doctrine/doctrine2/blob/v2.5.4/lib/Doctrine/ORM/Tools/EntityGenerator.php#L1221-L1246
175
     */
176
    private function isAssociationNullable(array $associationMapping): bool
177
    {
178
        if (isset($associationMapping['id']) && $associationMapping['id']) {
179
            return false;
180
        }
181
182
        if (!isset($associationMapping['joinColumns'])) {
183
            return true;
184
        }
185
186
        $joinColumns = $associationMapping['joinColumns'];
187
        foreach ($joinColumns as $joinColumn) {
188
            if (isset($joinColumn['nullable']) && !$joinColumn['nullable']) {
189
                return false;
190
            }
191
        }
192
193
        return true;
194
    }
195
}
196