Skip to content

Add support for the Accept-Patch header #3089

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
Sep 24, 2019
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
30 changes: 30 additions & 0 deletions features/main/patch.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Feature: Sending PATCH requets
As a client software developer
I need to be able to send partial updates

@createSchema
Scenario: Detect accepted patch formats
Given I add "Content-Type" header equal to "application/ld+json"
And I send a "POST" request to "/patch_dummies" with body:
"""
{"name": "Hello"}
"""
When I add "Content-Type" header equal to "application/ld+json"
And I send a "GET" request to "/patch_dummies/1"
Then the header "Accept-Patch" should be equal to "application/merge-patch+json, application/vnd.api+json"

Scenario: Patch an item
When I add "Content-Type" header equal to "application/merge-patch+json"
And I send a "PATCH" request to "/patch_dummies/1" with body:
"""
{"name": "Patched"}
"""
Then the JSON node "name" should contain "Patched"

Scenario: Remove a property according to RFC 7386
When I add "Content-Type" header equal to "application/merge-patch+json"
And I send a "PATCH" request to "/patch_dummies/1" with body:
"""
{"name": null}
"""
Then the JSON node "name" should not exist
1 change: 0 additions & 1 deletion src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@

<service id="api_platform.serializer.context_builder" class="ApiPlatform\Core\Serializer\SerializerContextBuilder" public="false">
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument>%api_platform.patch_formats%</argument>
</service>
<service id="ApiPlatform\Core\Serializer\SerializerContextBuilderInterface" alias="api_platform.serializer.context_builder" />

Expand Down
29 changes: 28 additions & 1 deletion src/EventListener/RespondListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Core\EventListener;

use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
Expand Down Expand Up @@ -51,7 +52,7 @@ public function onKernelView(GetResponseForControllerResultEvent $event): void

return;
}
if ($controllerResult instanceof Response || !($attributes['respond'] ?? $request->attributes->getBoolean('_api_respond', false))) {
if ($controllerResult instanceof Response || !($attributes['respond'] ?? $request->attributes->getBoolean('_api_respond'))) {
return;
}

Expand All @@ -78,6 +79,7 @@ public function onKernelView(GetResponseForControllerResultEvent $event): void
$headers['Sunset'] = (new \DateTimeImmutable($sunset))->format(\DateTime::RFC1123);
}

$headers = $this->addAcceptPatchHeader($headers, $attributes, $resourceMetadata);
$status = $resourceMetadata->getOperationAttribute($attributes, 'status');
}

Expand All @@ -87,4 +89,29 @@ public function onKernelView(GetResponseForControllerResultEvent $event): void
$headers
));
}

private function addAcceptPatchHeader(array $headers, array $attributes, ResourceMetadata $resourceMetadata): array
{
if (!isset($attributes['item_operation_name'])) {
return $headers;
}

$patchMimeTypes = [];
foreach ($resourceMetadata->getItemOperations() as $operation) {
if ('PATCH' !== ($operation['method'] ?? '') || !isset($operation['input_formats'])) {
continue;
}

foreach ($operation['input_formats'] as $mimeTypes) {
foreach ($mimeTypes as $mimeType) {
$patchMimeTypes[] = $mimeType;
}
}
$headers['Accept-Patch'] = implode(', ', $patchMimeTypes);

return $headers;
}

return $headers;
}
}
20 changes: 11 additions & 9 deletions src/Serializer/SerializerContextBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@
final class SerializerContextBuilder implements SerializerContextBuilderInterface
{
private $resourceMetadataFactory;
private $patchFormats;

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

/**
Expand Down Expand Up @@ -91,12 +89,16 @@ public function createFromRequest(Request $request, bool $normalization, array $

unset($context[DocumentationNormalizer::SWAGGER_DEFINITION_NAME]);

if (
isset($this->patchFormats['json'])
&& !isset($context['skip_null_values'])
&& \in_array('application/merge-patch+json', $this->patchFormats['json'], true)
) {
$context['skip_null_values'] = true;
if (isset($context['skip_null_values'])) {
return $context;
}

foreach ($resourceMetadata->getItemOperations() as $operation) {
if ('PATCH' === $operation['method'] && \in_array('application/merge-patch+json', $operation['input_formats']['json'] ?? [], true)) {
$context['skip_null_values'] = true;

break;
}
}

return $context;
Expand Down
41 changes: 41 additions & 0 deletions tests/Fixtures/TestBundle/Document/PatchDummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Tests\Fixtures\TestBundle\Document;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
* @author Kévin Dunglas <[email protected]>
*
* @ApiResource(
* itemOperations={
* "get",
* "patch"={"input_formats"={"json"={"application/merge-patch+json"}, "jsonapi"}}
* }
* )
* @ODM\Document
*/
class PatchDummy
{
/**
* @ODM\Id(strategy="INCREMENT", type="integer")
*/
public $id;

/**
* @ODM\Field(type="string")
*/
public $name;
}
43 changes: 43 additions & 0 deletions tests/Fixtures/TestBundle/Entity/PatchDummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;

/**
* @author Kévin Dunglas <[email protected]>
*
* @ApiResource(
* itemOperations={
* "get",
* "patch"={"input_formats"={"json"={"application/merge-patch+json"}, "jsonapi"}}
* }
* )
* @ORM\Entity
*/
class PatchDummy
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;

/**
* @ORM\Column(nullable=true)
*/
public $name;
}