Skip to content

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 2 commits into from
Mar 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion features/doctrine/date_filter.feature
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ Feature: Date filter on collections
},
"hydra:search": {
"@type": "hydra:IriTemplate",
"hydra:template": "\/dummies{?id,id[],name,alias,description,relatedDummy.name,relatedDummy.name[],relatedDummies,relatedDummies[],dummy,order[id],order[name],order[relatedDummy.symfony],dummyDate[before],dummyDate[after],relatedDummy.dummyDate[before],relatedDummy.dummyDate[after],dummyFloat[between],dummyFloat[gt],dummyFloat[gte],dummyFloat[lt],dummyFloat[lte],dummyPrice[between],dummyPrice[gt],dummyPrice[gte],dummyPrice[lt],dummyPrice[lte],dummyBoolean,dummyFloat,dummyPrice}",
"hydra:template": "\/dummies{?id,id[],name,alias,description,relatedDummy.name,relatedDummy.name[],relatedDummies,relatedDummies[],dummy,order[id],order[name],order[relatedDummy.symfony],dummyDate[before],dummyDate[after],relatedDummy.dummyDate[before],relatedDummy.dummyDate[after],dummyFloat[between],dummyFloat[gt],dummyFloat[gte],dummyFloat[lt],dummyFloat[lte],dummyPrice[between],dummyPrice[gt],dummyPrice[gte],dummyPrice[lt],dummyPrice[lte],dummyBoolean,dummyFloat,dummyPrice,description[exists],relatedDummy.name[exists],dummyBoolean[exists]}",
"hydra:variableRepresentation": "BasicRepresentation",
"hydra:mapping": [
{
Expand Down Expand Up @@ -588,6 +588,24 @@ Feature: Date filter on collections
"variable": "dummyPrice",
"property": "dummyPrice",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "description[exists]",
"property": "description",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "relatedDummy.name[exists]",
"property": "relatedDummy.name",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "dummyBoolean[exists]",
"property": "dummyBoolean",
"required": false
}
]
}
Expand Down
65 changes: 65 additions & 0 deletions features/doctrine/exists_filter.feature
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$"}
}
}
}
}
"""
20 changes: 19 additions & 1 deletion features/main/crud.feature
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ Feature: Create-Retrieve-Update-Delete
"hydra:totalItems": 1,
"hydra:search": {
"@type": "hydra:IriTemplate",
"hydra:template": "/dummies{?id,id[],name,alias,description,relatedDummy.name,relatedDummy.name[],relatedDummies,relatedDummies[],dummy,order[id],order[name],order[relatedDummy.symfony],dummyDate[before],dummyDate[after],relatedDummy.dummyDate[before],relatedDummy.dummyDate[after],dummyFloat[between],dummyFloat[gt],dummyFloat[gte],dummyFloat[lt],dummyFloat[lte],dummyPrice[between],dummyPrice[gt],dummyPrice[gte],dummyPrice[lt],dummyPrice[lte],dummyBoolean,dummyFloat,dummyPrice}",
"hydra:template": "/dummies{?id,id[],name,alias,description,relatedDummy.name,relatedDummy.name[],relatedDummies,relatedDummies[],dummy,order[id],order[name],order[relatedDummy.symfony],dummyDate[before],dummyDate[after],relatedDummy.dummyDate[before],relatedDummy.dummyDate[after],dummyFloat[between],dummyFloat[gt],dummyFloat[gte],dummyFloat[lt],dummyFloat[lte],dummyPrice[between],dummyPrice[gt],dummyPrice[gte],dummyPrice[lt],dummyPrice[lte],dummyBoolean,dummyFloat,dummyPrice,description[exists],relatedDummy.name[exists],dummyBoolean[exists]}",
"hydra:variableRepresentation": "BasicRepresentation",
"hydra:mapping": [
{
Expand Down Expand Up @@ -305,6 +305,24 @@ Feature: Create-Retrieve-Update-Delete
"variable": "dummyPrice",
"property": "dummyPrice",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "description[exists]",
"property": "description",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "relatedDummy.name[exists]",
"property": "relatedDummy.name",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "dummyBoolean[exists]",
"property": "dummyBoolean",
"required": false
}
]
}
Expand Down
195 changes: 195 additions & 0 deletions src/Bridge/Doctrine/Orm/Filter/ExistsFilter.php
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)) {
Copy link
Contributor

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 ?

Copy link
Contributor Author

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?

Copy link
Member

@soyuka soyuka Mar 16, 2017

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.

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;
}
}
6 changes: 6 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/doctrine_orm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@
<argument type="service" id="logger" on-invalid="ignore" />
</service>

<service id="api_platform.doctrine.orm.exists_filter" class="ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\ExistsFilter" public="false" abstract="true">
<argument type="service" id="doctrine" />
<argument type="service" id="request_stack" />
<argument type="service" id="logger" on-invalid="ignore" />
</service>

<!-- Metadata loader -->

<service id="api_platform.doctrine.orm.metadata.property.metadata_factory" class="ApiPlatform\Core\Bridge\Doctrine\Orm\Metadata\Property\DoctrineOrmPropertyMetadataFactory" decorates="api_platform.metadata.property.metadata_factory" decoration-priority="40" public="false">
Expand Down
Loading