-
-
Notifications
You must be signed in to change notification settings - Fork 920
Add ExistsFilter #906
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add ExistsFilter #906
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
Feature: Exists filter on collections | ||
In order to retrieve large collections of resources | ||
As a client software developer | ||
I need to retrieve collections that exists | ||
|
||
@createSchema | ||
Scenario: Get collection where exists does not exist | ||
Given there is "15" dummy objects with dummyBoolean true | ||
When I send a "GET" request to "/dummies?dummyBoolean[exists]=0" | ||
Then the response status code should be 200 | ||
And the response should be in JSON | ||
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8" | ||
And the JSON should be valid according to this schema: | ||
""" | ||
{ | ||
"type": "object", | ||
"properties": { | ||
"@context": {"pattern": "^/contexts/Dummy$"}, | ||
"@id": {"pattern": "^/dummies$"}, | ||
"@type": {"pattern": "^hydra:Collection$"}, | ||
"hydra:totalItems": {"type":"number", "maximum": 0}, | ||
"hydra:member": { | ||
"type": "array", | ||
"maxItems": 0 | ||
}, | ||
"hydra:view": { | ||
"type": "object", | ||
"properties": { | ||
"@id": {"pattern": "^/dummies\\?dummyBoolean%5Bexists%5D=0$"}, | ||
"@type": {"pattern": "^hydra:PartialCollectionView$"} | ||
} | ||
} | ||
} | ||
} | ||
""" | ||
|
||
@dropSchema | ||
Scenario: Get collection where exists does exist | ||
When I send a "GET" request to "/dummies?dummyBoolean[exists]=1" | ||
Then the response status code should be 200 | ||
And the response should be in JSON | ||
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8" | ||
And the JSON should be valid according to this schema: | ||
""" | ||
{ | ||
"type": "object", | ||
"properties": { | ||
"@context": {"pattern": "^/contexts/Dummy$"}, | ||
"@id": {"pattern": "^/dummies$"}, | ||
"@type": {"pattern": "^hydra:Collection$"}, | ||
"hydra:totalItems": {"type":"number", "minimum": 3}, | ||
"hydra:member": { | ||
"type": "array", | ||
"minItems": 3 | ||
}, | ||
"hydra:view": { | ||
"type": "object", | ||
"properties": { | ||
"@id": {"pattern": "^/dummies\\?dummyBoolean%5Bexists%5D=1&page=1$"}, | ||
"@type": {"pattern": "^hydra:PartialCollectionView$"} | ||
} | ||
} | ||
} | ||
} | ||
""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,195 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the API Platform project. | ||
* | ||
* (c) Kévin Dunglas <dunglas@gmail.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Filter; | ||
|
||
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; | ||
use ApiPlatform\Core\Exception\InvalidArgumentException; | ||
use Doctrine\Common\Persistence\ManagerRegistry; | ||
use Doctrine\ORM\Mapping\ClassMetadataInfo; | ||
use Doctrine\ORM\QueryBuilder; | ||
use Psr\Log\LoggerInterface; | ||
use Symfony\Component\HttpFoundation\RequestStack; | ||
|
||
/** | ||
* Filters the collection by whether a property value exists or not. | ||
* | ||
* For each property passed, if the resource does not have such property or if | ||
* the value is not one of ( "true" | "false" | "1" | "0" ) the property is ignored. | ||
* | ||
* A query parameter with key but no value is treated as `true`, e.g.: | ||
* Request: GET /products?brand[exists] | ||
* Interpretation: filter products which have a brand | ||
* | ||
* @author Teoh Han Hui <teohhanhui@gmail.com> | ||
*/ | ||
class ExistsFilter extends AbstractFilter | ||
{ | ||
const QUERY_PARAMETER_KEY = 'exists'; | ||
|
||
public function __construct(ManagerRegistry $managerRegistry, RequestStack $requestStack, LoggerInterface $logger = null, array $properties = null) | ||
{ | ||
parent::__construct($managerRegistry, $requestStack, $logger, $properties); | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function getDescription(string $resourceClass): array | ||
{ | ||
$description = []; | ||
|
||
$properties = $this->properties; | ||
if (null === $properties) { | ||
$properties = array_fill_keys($this->getClassMetadata($resourceClass)->getFieldNames(), null); | ||
} | ||
|
||
foreach ($properties as $property => $unused) { | ||
if (!$this->isPropertyMapped($property, $resourceClass, true) || !$this->isNullableField($property, $resourceClass)) { | ||
continue; | ||
} | ||
|
||
$description[sprintf('%s[%s]', $property, self::QUERY_PARAMETER_KEY)] = [ | ||
'property' => $property, | ||
'type' => 'bool', | ||
'required' => false, | ||
]; | ||
} | ||
|
||
return $description; | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null) | ||
{ | ||
if ( | ||
!isset($value[self::QUERY_PARAMETER_KEY]) || | ||
!$this->isPropertyEnabled($property) || | ||
!$this->isPropertyMapped($property, $resourceClass, true) || | ||
!$this->isNullableField($property, $resourceClass) | ||
) { | ||
return; | ||
} | ||
|
||
if (in_array($value[self::QUERY_PARAMETER_KEY], ['true', '1', '', null], true)) { | ||
$value = true; | ||
} elseif (in_array($value[self::QUERY_PARAMETER_KEY], ['false', '0'], true)) { | ||
$value = false; | ||
} else { | ||
$this->logger->notice('Invalid filter ignored', [ | ||
'exception' => new InvalidArgumentException(sprintf('Invalid value for "%s[%s]", expected one of ( "%s" )', $property, self::QUERY_PARAMETER_KEY, implode('" | "', [ | ||
'true', | ||
'false', | ||
'1', | ||
'0', | ||
]))), | ||
]); | ||
|
||
return; | ||
} | ||
|
||
$alias = 'o'; | ||
$field = $property; | ||
|
||
if ($this->isPropertyNested($property)) { | ||
list($alias, $field) = $this->addJoinsForNestedProperty($property, $alias, $queryBuilder, $queryNameGenerator); | ||
} | ||
|
||
$propertyParts = $this->splitPropertyParts($property); | ||
$metadata = $this->getNestedMetadata($resourceClass, $propertyParts['associations']); | ||
|
||
if ($metadata->hasAssociation($field)) { | ||
if ($metadata->isCollectionValuedAssociation($field)) { | ||
$queryBuilder | ||
->andWhere(sprintf('%s.%s %s EMPTY', $alias, $field, $value ? 'IS NOT' : 'IS')); | ||
|
||
return; | ||
} | ||
|
||
$queryBuilder | ||
->andWhere(sprintf('%s.%s %s NULL', $alias, $field, $value ? 'IS NOT' : 'IS')); | ||
|
||
return; | ||
} | ||
|
||
if ($metadata->hasField($field)) { | ||
$queryBuilder | ||
->andWhere(sprintf('%s.%s %s NULL', $alias, $field, $value ? 'IS NOT' : 'IS')); | ||
} | ||
} | ||
|
||
/** | ||
* Determines whether the given property refers to a nullable field. | ||
* | ||
* @param string $property | ||
* @param string $resourceClass | ||
* | ||
* @return bool | ||
*/ | ||
protected function isNullableField(string $property, string $resourceClass): bool | ||
{ | ||
$propertyParts = $this->splitPropertyParts($property); | ||
$metadata = $this->getNestedMetadata($resourceClass, $propertyParts['associations']); | ||
|
||
$field = $propertyParts['field']; | ||
|
||
if ($metadata->hasAssociation($field)) { | ||
if ($metadata->isSingleValuedAssociation($field)) { | ||
if (!($metadata instanceof ClassMetadataInfo)) { | ||
return false; | ||
} | ||
|
||
$associationMapping = $metadata->getAssociationMapping($field); | ||
|
||
return $this->isAssociationNullable($associationMapping); | ||
} | ||
|
||
return true; | ||
} | ||
|
||
if ($metadata instanceof ClassMetadataInfo && $metadata->hasField($field)) { | ||
return $metadata->isNullable($field); | ||
} | ||
|
||
return false; | ||
} | ||
|
||
/** | ||
* Determines whether an association is nullable. | ||
* | ||
* @param array $associationMapping | ||
* | ||
* @return bool | ||
* | ||
* @see https://github.com/doctrine/doctrine2/blob/v2.5.4/lib/Doctrine/ORM/Tools/EntityGenerator.php#L1221-L1246 | ||
*/ | ||
private function isAssociationNullable(array $associationMapping): bool | ||
{ | ||
if (isset($associationMapping['id']) && $associationMapping['id']) { | ||
return false; | ||
} | ||
|
||
if (!isset($associationMapping['joinColumns'])) { | ||
return true; | ||
} | ||
|
||
$joinColumns = $associationMapping['joinColumns']; | ||
foreach ($joinColumns as $joinColumn) { | ||
if (isset($joinColumn['nullable']) && !$joinColumn['nullable']) { | ||
return false; | ||
} | ||
} | ||
|
||
return true; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can't we refacto that to avoid that complexity ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You mean to reduce the cyclomatic complexity?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Look at my commit (made my changes in a separate commit), I refactored it a bit.