Skip to content

Implement Annotation filters @ApiFilter #1117

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 1 commit into from
Oct 12, 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
3 changes: 3 additions & 0 deletions features/bootstrap/FeatureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,9 @@ public function thereIsAFileConfigDummyObject()
public function thereIsAFooEntityWithRelatedBars()
{
$foo = new DummyCar();
$foo->setName('mustli');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A car called mustli ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your nickname is Simperfit, so why not Mustli for a car? 😄

$foo->setCanSell(true);
$foo->setAvailableAt(new \DateTime());
$this->manager->persist($foo);

$bar1 = new DummyCarColor();
Expand Down
74 changes: 61 additions & 13 deletions features/doctrine/search_filter.feature
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,67 @@ Feature: Search filter on collections
"@id": "/dummy_cars?colors.prop=red",
"@type": "hydra:PartialCollectionView"
},
"hydra:search": {
"@type": "hydra:IriTemplate",
"hydra:template": "/dummy_cars{?colors.prop}",
"hydra:variableRepresentation": "BasicRepresentation",
"hydra:mapping": [
{
"@type": "IriTemplateMapping",
"variable": "colors.prop",
"property": "colors.prop",
"required": false
}
]
}
"hydra:search": {
"@type": "hydra:IriTemplate",
"hydra:template": "\/dummy_cars{?availableAt[before],availableAt[strictly_before],availableAt[after],availableAt[strictly_after],canSell,foobar[],foobargroups[],colors.prop,name}",
"hydra:variableRepresentation": "BasicRepresentation",
"hydra:mapping": [
{
"@type": "IriTemplateMapping",
"variable": "availableAt[before]",
"property": "availableAt",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "availableAt[strictly_before]",
"property": "availableAt",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "availableAt[after]",
"property": "availableAt",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "availableAt[strictly_after]",
"property": "availableAt",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "canSell",
"property": "canSell",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "foobar[]",
"property": null,
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "foobargroups[]",
"property": null,
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "colors.prop",
"property": "colors.prop",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "name",
"property": "name",
"required": false
}
]
}
}
"""

Expand Down
70 changes: 70 additions & 0 deletions src/Annotation/ApiFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?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.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Annotation;

use ApiPlatform\Core\Api\FilterInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;

/**
* Filter annotation.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*
* @Annotation
* @Target({"PROPERTY", "CLASS"})
Copy link
Member Author

@soyuka soyuka May 16, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure that METHOD targets are a good thing here. Also, they add complexity.

*/
final class ApiFilter
{
/**
* @var string
*/
public $strategy;

/**
* @var string
*/
public $filterClass;

/**
* @var array
*/
public $properties = [];

/**
* @var array raw arguments for the filter
*/
public $arguments = [];

public function __construct($options = [])
{
if (!isset($options['value'])) {
throw new InvalidArgumentException('This annotation needs a value representing the filter class.');
}

if (!is_subclass_of($options['value'], FilterInterface::class)) {
throw new InvalidArgumentException(sprintf('The filter class "%s" does not implement "%s".', $options['value'], FilterInterface::class));
}

$this->filterClass = $options['value'];
unset($options['value']);

foreach ($options as $key => $value) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really necessary? IIRC, Doctrine Annot will hydrate properties.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either this or my test AnnotationFilterPassTest is wrong. If I remove this, the filter arguments are empty (see AnnotationFilterExtractorTrait->readFilterAnnotations).

if (!property_exists($this, $key)) {
throw new InvalidArgumentException(sprintf('Property "%s" does not exist on the ApiFilter annotation.', $key));
}

$this->$key = $value;
}
}
}
2 changes: 2 additions & 0 deletions src/Bridge/Symfony/Bundle/ApiPlatformBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\Core\Bridge\Symfony\Bundle;

use ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection\Compiler\AnnotationFilterPass;
use ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection\Compiler\DataProviderPass;
use ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection\Compiler\DoctrineQueryExtensionPass;
use ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection\Compiler\FilterPass;
Expand All @@ -34,6 +35,7 @@ public function build(ContainerBuilder $container)
parent::build($container);

$container->addCompilerPass(new DataProviderPass());
$container->addCompilerPass(new AnnotationFilterPass());
$container->addCompilerPass(new FilterPass());
$container->addCompilerPass(new DoctrineQueryExtensionPass());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?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.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection\Compiler;

use ApiPlatform\Core\Util\AnnotationFilterExtractorTrait;
use ApiPlatform\Core\Util\ReflectionClassRecursiveIterator;
use Doctrine\Common\Annotations\Reader;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

/**
* Injects filters.
*
* @internal
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
final class AnnotationFilterPass implements CompilerPassInterface
{
use AnnotationFilterExtractorTrait;

const TAG_FILTER_NAME = 'api_platform.filter';

/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$resourceClassDirectories = $container->getParameter('api_platform.resource_class_directories');
$reader = $container->get('annotation_reader');

foreach (ReflectionClassRecursiveIterator::getReflectionClassesFromDirectories($resourceClassDirectories) as $className => $reflectionClass) {
$this->createFilterDefinitions($reflectionClass, $reader, $container);
}
}

private function createFilterDefinitions(\ReflectionClass $reflectionClass, Reader $reader, ContainerBuilder $container)
{
foreach ($this->readFilterAnnotations($reflectionClass, $reader) as $id => list($arguments, $filterClass)) {
if ($container->hasDefinition($id)) {
continue;
}

$definition = new Definition();
$definition->setClass($filterClass);
$definition->addTag(self::TAG_FILTER_NAME);
$definition->setAutowired(true);

foreach ($arguments as $key => $value) {
$definition->setArgument("$$key", $value);
}

$container->setDefinition($id, $definition);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
<argument type="service" id="api_platform.metadata.resource.metadata_factory.annotation.inner" />
</service>

<service id="api_platform.metadata.resource.filter_metadata_factory.annotation" decorates="api_platform.metadata.resource.metadata_factory" decoration-priority="20" class="ApiPlatform\Core\Metadata\Resource\Factory\AnnotationResourceFilterMetadataFactory" public="false">
<argument type="service" id="annotation_reader" />
<argument type="service" id="api_platform.metadata.resource.filter_metadata_factory.annotation.inner" />
</service>

<!--
Not used, the PropertyInfo factory is preferred.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?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.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Metadata\Resource\Factory;

use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Util\AnnotationFilterExtractorTrait;
use Doctrine\Common\Annotations\Reader;

/**
* Adds filters to the resource metadata {@see ApiFilter} annotation.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
final class AnnotationResourceFilterMetadataFactory implements ResourceMetadataFactoryInterface
{
use AnnotationFilterExtractorTrait;

private $reader;
private $decorated;

public function __construct(Reader $reader, ResourceMetadataFactoryInterface $decorated = null)
{
$this->reader = $reader;
$this->decorated = $decorated;
}

/**
* {@inheritdoc}
*/
public function create(string $resourceClass): ResourceMetadata
{
$parentResourceMetadata = null;
if ($this->decorated) {
try {
$parentResourceMetadata = $this->decorated->create($resourceClass);
} catch (ResourceClassNotFoundException $resourceNotFoundException) {
// Ignore not found exception from decorated factories
}
}

if (null === $parentResourceMetadata) {
return $this->handleNotFound($parentResourceMetadata, $resourceClass);
}

try {
$reflectionClass = new \ReflectionClass($resourceClass);
} catch (\ReflectionException $reflectionException) {
return $this->handleNotFound($parentResourceMetadata, $resourceClass);
}

$filters = array_keys($this->readFilterAnnotations($reflectionClass, $this->reader));

if (!$filters) {
return $parentResourceMetadata;
}

$parentFilters = $parentResourceMetadata->getAttribute('filters', []);

if ($parentFilters) {
$filters = array_merge($parentFilters, $filters);
}

$attributes = $parentResourceMetadata->getAttributes();

if (!$attributes) {
$attributes = [];
}

return $parentResourceMetadata->withAttributes(array_merge($attributes, ['filters' => $filters]));
}

/**
* Returns the metadata from the decorated factory if available or throws an exception.
*
* @param ResourceMetadata|null $parentPropertyMetadata
* @param string $resourceClass
*
* @throws ResourceClassNotFoundException
*
* @return ResourceMetadata
*/
private function handleNotFound(ResourceMetadata $parentPropertyMetadata = null, string $resourceClass): ResourceMetadata
{
if (null !== $parentPropertyMetadata) {
return $parentPropertyMetadata;
}

throw new ResourceClassNotFoundException(sprintf('Resource "%s" not found.', $resourceClass));
}
}
Loading