Skip to content

[RFR] Allow to specify formats per resources/operations #1798

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
Jun 9, 2018
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
33 changes: 33 additions & 0 deletions features/main/content_negotiation.feature
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,36 @@ Feature: Content Negotiation support
And I send a "GET" request to "/dummies/666"
Then the response status code should be 404
And the header "Content-Type" should be equal to "text/html; charset=utf-8"

Scenario: Retrieve a collection in JSON should not be possible if the format has been removed at resource level
When I add "Accept" header equal to "application/json"
And I send a "GET" request to "/dummy_custom_formats"
Then the response status code should be 406
And the header "Content-Type" should be equal to "application/problem+json; charset=utf-8"

Scenario: Post an CSV body allowed on a single resource
When I add "Accept" header equal to "application/xml"
And I add "Content-Type" header equal to "text/csv"
And I send a "POST" request to "/dummy_custom_formats" with body:
"""
name
Kevin
"""
Then the response status code should be 201
And the header "Content-Type" should be equal to "application/xml; charset=utf-8"
And the response should be equal to
"""
<?xml version="1.0"?>
<response><id>1</id><name>Kevin</name></response>
"""

Scenario: Retrieve a collection in CSV should be possible if the format is at resource level
When I add "Accept" header equal to "text/csv"
And I send a "GET" request to "/dummy_custom_formats"
Then the response status code should be 200
And the header "Content-Type" should be equal to "text/csv; charset=utf-8"
And the response should be equal to
"""
id,name
1,Kevin
"""
8 changes: 8 additions & 0 deletions src/Annotation/ApiResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
* @Attribute("description", type="string"),
* @Attribute("fetchPartial", type="bool"),
* @Attribute("forceEager", type="bool"),
* @Attribute("formats", type="array"),
* @Attribute("filters", type="string[]"),
* @Attribute("graphql", type="array"),
* @Attribute("hydraContext", type="array"),
Expand Down Expand Up @@ -135,6 +136,13 @@ final class ApiResource
*/
private $forceEager;

/**
* @see https://github.com/Haehnchen/idea-php-annotation-plugin/issues/112
Copy link
Contributor

Choose a reason for hiding this comment

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

In my PR (#1685) it was mentioned that the core team does not want to add more root annotation configuration values but instead put it into attributes. Just saying that this may need to be modified but I let @dunglas decide on this. I don't remember the exact reason for this anymore because I actually like when things are specific 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this just follows #1788, nothing more

*
* @var array
*/
private $formats;

/**
* @see https://github.com/Haehnchen/idea-php-annotation-plugin/issues/112
*
Expand Down
85 changes: 85 additions & 0 deletions src/Api/FormatsProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?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\Api;

use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;

/**
* {@inheritdoc}
*
* @author Anthony GRASSIOT <antograssiot@free.fr>
*/
final class FormatsProvider implements FormatsProviderInterface
{
private $configuredFormats;
private $resourceMetadataFactory;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, array $configuredFormats)
{
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->configuredFormats = $configuredFormats;
}

/**
* {@inheritdoc}
*
* @throws InvalidArgumentException
*/
public function getFormatsFromAttributes(array $attributes): array
{
if (!$attributes || !isset($attributes['resource_class'])) {
return $this->configuredFormats;
}

$resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);

if (!$formats = $resourceMetadata->getOperationAttribute($attributes, 'formats', [], true)) {
return $this->configuredFormats;
}

if (!\is_array($formats)) {
throw new InvalidArgumentException(sprintf("The 'formats' attributes must be an array, %s given for resource class '%s'.", \gettype($formats), $attributes['resource_class']));
}

return $this->getOperationFormats($formats);
}

/**
* Filter and populate the acceptable formats.
*
* @throws InvalidArgumentException
*/
private function getOperationFormats(array $annotationFormats): array
{
$resourceFormats = [];
foreach ($annotationFormats as $format => $value) {
if (!is_numeric($format)) {
$resourceFormats[$format] = (array) $value;
continue;
}
if (!\is_string($value)) {
throw new InvalidArgumentException(sprintf("The 'formats' attributes value must be a string when trying to include an already configured format, %s given.", \gettype($value)));
}
if (array_key_exists($value, $this->configuredFormats)) {
$resourceFormats[$value] = $this->configuredFormats[$value];
continue;
}

throw new InvalidArgumentException(sprintf("You either need to add the format '%s' to your project configuration or declare a mime type for it in your annotation.", $value));
Copy link
Member

Choose a reason for hiding this comment

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

Can you add the @throws annotation in the PHPDoc?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

}

return $resourceFormats;
}
}
27 changes: 27 additions & 0 deletions src/Api/FormatsProviderInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?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\Api;

/**
* Extracts formats for a given operation according to the retrieved Metadata.
*
* @author Anthony GRASSIOT <antograssiot@free.fr>
*/
interface FormatsProviderInterface
{
/**
* Finds formats for an operation.
*/
public function getFormatsFromAttributes(array $attributes): array;
}
32 changes: 29 additions & 3 deletions src/Bridge/Symfony/Bundle/Action/SwaggerUiAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@

namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Action;

use ApiPlatform\Core\Api\FormatsProviderInterface;
use ApiPlatform\Core\Documentation\Documentation;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
Expand All @@ -37,7 +40,7 @@ final class SwaggerUiAction
private $title;
private $description;
private $version;
private $formats;
private $formats = [];
private $oauthEnabled;
private $oauthClientId;
private $oauthClientSecret;
Expand All @@ -46,8 +49,12 @@ final class SwaggerUiAction
private $oauthTokenUrl;
private $oauthAuthorizationUrl;
private $oauthScopes;
private $formatsProvider;

public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, NormalizerInterface $normalizer, \Twig_Environment $twig, UrlGeneratorInterface $urlGenerator, string $title = '', string $description = '', string $version = '', array $formats = [], $oauthEnabled = false, $oauthClientId = '', $oauthClientSecret = '', $oauthType = '', $oauthFlow = '', $oauthTokenUrl = '', $oauthAuthorizationUrl = '', $oauthScopes = [])
/**
* @throws InvalidArgumentException
*/
public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, NormalizerInterface $normalizer, \Twig_Environment $twig, UrlGeneratorInterface $urlGenerator, string $title = '', string $description = '', string $version = '', /* FormatsProviderInterface */ $formatsProvider = [], $oauthEnabled = false, $oauthClientId = '', $oauthClientSecret = '', $oauthType = '', $oauthFlow = '', $oauthTokenUrl = '', $oauthAuthorizationUrl = '', $oauthScopes = [])
{
$this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
$this->resourceMetadataFactory = $resourceMetadataFactory;
Expand All @@ -57,7 +64,6 @@ public function __construct(ResourceNameCollectionFactoryInterface $resourceName
$this->title = $title;
$this->description = $description;
$this->version = $version;
$this->formats = $formats;
$this->oauthEnabled = $oauthEnabled;
$this->oauthClientId = $oauthClientId;
$this->oauthClientSecret = $oauthClientSecret;
Expand All @@ -66,10 +72,30 @@ public function __construct(ResourceNameCollectionFactoryInterface $resourceName
$this->oauthTokenUrl = $oauthTokenUrl;
$this->oauthAuthorizationUrl = $oauthAuthorizationUrl;
$this->oauthScopes = $oauthScopes;

if (\is_array($formatsProvider)) {
if ($formatsProvider) {
// Only trigger notification for non-default argument
@trigger_error('Using an array as formats provider is deprecated since API Platform 2.3 and will not be possible anymore in API Platform 3', E_USER_DEPRECATED);
Copy link
Contributor

Choose a reason for hiding this comment

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

Using an array as formats provider is deprecated since API Platform 2.3 and will not be possible anymore in API Platform 3.0.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

is this about the 3 versus 3.0 ?
All other places are using this sentence @Simperfit

Copy link
Contributor Author

Choose a reason for hiding this comment

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

the only exception seems to be the AbstractFilter ... but I can update of course if necessary

Copy link
Contributor

Choose a reason for hiding this comment

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

I think to be coherent it's better to update the AbstractFilter ;). let it like this

}
$this->formats = $formatsProvider;

return;
}
if (!$formatsProvider instanceof FormatsProviderInterface) {
throw new InvalidArgumentException(sprintf('The "$formatsProvider" argument is expected to be an implementation of the "%s" interface.', FormatsProviderInterface::class));
}

$this->formatsProvider = $formatsProvider;
}

public function __invoke(Request $request)
{
// BC check to be removed in 3.0
if (null !== $this->formatsProvider) {
$this->formats = $this->formatsProvider->getFormatsFromAttributes(RequestAttributesExtractor::extractAttributes($request));
}

$documentation = new Documentation($this->resourceNameCollectionFactory->create(), $this->title, $this->description, $this->version, $this->formats);

return new Response($this->twig->render('@ApiPlatform/SwaggerUi/index.html.twig', $this->getContext($request, $documentation)));
Expand Down
11 changes: 8 additions & 3 deletions src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@
</service>
<service id="ApiPlatform\Core\Api\IriConverterInterface" alias="api_platform.iri_converter" />

<service id="api_platform.formats_provider" class="ApiPlatform\Core\Api\FormatsProvider">
<argument type="service" id="api_platform.metadata.resource.metadata_factory"></argument>
<argument>%api_platform.formats%</argument>
</service>

<!-- Serializer -->

<service id="api_platform.serializer.context_builder" class="ApiPlatform\Core\Serializer\SerializerContextBuilder" public="false">
Expand Down Expand Up @@ -130,7 +135,7 @@
<!-- kernel.request priority must be < 8 to be executed after the Firewall -->
<service id="api_platform.listener.request.add_format" class="ApiPlatform\Core\EventListener\AddFormatListener">
<argument type="service" id="api_platform.negotiator" />
<argument>%api_platform.formats%</argument>
<argument type="service" id="api_platform.formats_provider"></argument>

<tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" priority="7" />
</service>
Expand All @@ -154,7 +159,7 @@
<service id="api_platform.listener.request.deserialize" class="ApiPlatform\Core\EventListener\DeserializeListener">
<argument type="service" id="api_platform.serializer" />
<argument type="service" id="api_platform.serializer.context_builder" />
<argument>%api_platform.formats%</argument>
<argument type="service" id="api_platform.formats_provider" />

<tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" priority="2" />
</service>
Expand Down Expand Up @@ -205,7 +210,7 @@
<argument>%api_platform.title%</argument>
<argument>%api_platform.description%</argument>
<argument>%api_platform.version%</argument>
<argument>%api_platform.formats%</argument>
<argument type="service" id="api_platform.formats_provider" />
</service>

<service id="api_platform.action.exception" class="ApiPlatform\Core\Action\ExceptionAction" public="true">
Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/Symfony/Bundle/Resources/config/swagger.xml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
<argument>%api_platform.title%</argument>
<argument>%api_platform.description%</argument>
<argument>%api_platform.version%</argument>
<argument>%api_platform.formats%</argument>
<argument type="service" id="api_platform.formats_provider" />
<argument>%api_platform.oauth.enabled%</argument>
<argument>%api_platform.oauth.clientId%</argument>
<argument>%api_platform.oauth.clientSecret%</argument>
Expand Down
32 changes: 29 additions & 3 deletions src/Documentation/Action/DocumentationAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@

namespace ApiPlatform\Core\Documentation\Action;

use ApiPlatform\Core\Api\FormatsProviderInterface;
use ApiPlatform\Core\Documentation\Documentation;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpFoundation\Request;

/**
Expand All @@ -28,15 +31,32 @@ final class DocumentationAction
private $title;
private $description;
private $version;
private $formats;
private $formats = [];
private $formatsProvider;

public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, string $title = '', string $description = '', string $version = '', array $formats = [])
/**
* @throws InvalidArgumentException
*/
public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, string $title = '', string $description = '', string $version = '', /* FormatsProviderInterface */ $formatsProvider = [])
{
$this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
$this->title = $title;
$this->description = $description;
$this->version = $version;
$this->formats = $formats;
if (\is_array($formatsProvider)) {
if ($formatsProvider) {
// Only trigger notification for non-default argument
@trigger_error('Using an array as formats provider is deprecated since API Platform 2.3 and will not be possible anymore in API Platform 3', E_USER_DEPRECATED);
}
$this->formats = $formatsProvider;

return;
}
if (!$formatsProvider instanceof FormatsProviderInterface) {
throw new InvalidArgumentException(sprintf('The "$formatsProvider" argument is expected to be an implementation of the "%s" interface.', FormatsProviderInterface::class));
}

$this->formatsProvider = $formatsProvider;
}

public function __invoke(Request $request = null): Documentation
Expand All @@ -47,6 +67,12 @@ public function __invoke(Request $request = null): Documentation
$context['api_gateway'] = true;
}
$request->attributes->set('_api_normalization_context', $request->attributes->get('_api_normalization_context', []) + $context);

$attributes = RequestAttributesExtractor::extractAttributes($request);
}
// BC check to be removed in 3.0
if (null !== $this->formatsProvider) {
$this->formats = $this->formatsProvider->getFormatsFromAttributes($attributes ?? []);
Copy link
Contributor

Choose a reason for hiding this comment

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

There is no need to declare $attributes (line 71) out of this if, it could be:

$this->formats = $this->formatsProvider->getFormatsFromAttributes(RequestAttributesExtractor::extractAttributes($request));

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is needed because RequestAttributesExtractor::extractAttributes(Request $request) doesn't accept null
https://github.com/api-platform/core/blob/master/src/Util/RequestAttributesExtractor.php#L40

}

return new Documentation($this->resourceNameCollectionFactory->create(), $this->title, $this->description, $this->version, $this->formats);
Expand Down
Loading