Skip to content
Draft
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
9 changes: 9 additions & 0 deletions src/Laravel/ApiPlatformProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\Pagination\PaginationOptions;
use ApiPlatform\State\Processor\AddLinkHeaderProcessor;
use ApiPlatform\State\Processor\LinkedDataPlatformProcessor;
use ApiPlatform\State\Processor\RespondProcessor;
use ApiPlatform\State\Processor\SerializeProcessor;
use ApiPlatform\State\Processor\WriteProcessor;
Expand Down Expand Up @@ -424,6 +425,14 @@ public function register(): void
return new AddLinkHeaderProcessor($decorated, new HttpHeaderSerializer());
});

$this->app->singleton(LinkedDataPlatformProcessor::class, function (Application $app) {
return new LinkedDataPlatformProcessor(
$app->make(AddLinkHeaderProcessor::class), // Original service
$app->make(ResourceClassResolverInterface::class),
$app->make(ResourceMetadataCollectionFactoryInterface::class)
);
});

$this->app->singleton(SerializeProcessor::class, function (Application $app) {
return new SerializeProcessor($app->make(RespondProcessor::class), $app->make(Serializer::class), $app->make(SerializerContextBuilderInterface::class));
});
Expand Down
78 changes: 78 additions & 0 deletions src/State/Processor/LinkedDataPlatformProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?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\State\Processor;

use ApiPlatform\Metadata\Error;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\State\ProcessorInterface;
use Symfony\Component\HttpFoundation\Response;

/**
* @template T1
* @template T2
*
* @implements ProcessorInterface<T1, T2>
*/
final class LinkedDataPlatformProcessor implements ProcessorInterface
{
private const DEFAULT_ALLOWED_METHODS = ['OPTIONS', 'HEAD'];

/**
* @param ProcessorInterface<T1, T2> $decorated
*/
public function __construct(
private readonly ProcessorInterface $decorated,
private readonly ResourceClassResolverInterface $resourceClassResolver,
private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
) {
}

public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{
$response = $this->decorated->process($data, $operation, $uriVariables, $context);
if (
!$response instanceof Response
|| !$operation instanceof HttpOperation
|| $operation instanceof Error
|| !$operation->getUriTemplate()
|| !$this->resourceClassResolver->isResourceClass($operation->getClass())
) {
return $response;
}

$acceptPost = null;
$allowedMethods = self::DEFAULT_ALLOWED_METHODS;
$resourceCollection = $this->resourceMetadataCollectionFactory->create($operation->getClass());
foreach ($resourceCollection as $resource) {
foreach ($resource->getOperations() as $op) {
if ($op->getUriTemplate() === $operation->getUriTemplate()) {
$allowedMethods[] = $method = $op->getMethod();
if ('POST' === $method && \is_array($outputFormats = $op->getOutputFormats())) {
$acceptPost = implode(', ', array_merge(...array_values($outputFormats)));
}
Copy link
Member

Choose a reason for hiding this comment

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

this is interesting, we've never had the use case before where we want all "POST" operation that belong to the same URI. Note to self that it's here if I need it elsewhere :D.

}
}
}
if ($acceptPost) {
$response->headers->set('Accept-Post', $acceptPost);
}

$response->headers->set('Allow', implode(', ', $allowedMethods));

return $response;
}
}
22 changes: 22 additions & 0 deletions src/State/Tests/Fixtures/ApiResource/Dummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\State\Tests\Fixtures\ApiResource;

use ApiPlatform\Metadata\ApiResource;

#[ApiResource()]
class Dummy
{
public int $id;
}
161 changes: 161 additions & 0 deletions src/State/Tests/Processor/LinkedDataPlatformProcessorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
<?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\State\Tests\Processor;

use ApiPlatform\Hal\Tests\Fixtures\Dummy;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Error;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\State\Processor\LinkedDataPlatformProcessor;
use ApiPlatform\State\ProcessorInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class LinkedDataPlatformProcessorTest extends TestCase
{
private ResourceMetadataCollectionFactoryInterface&MockObject $resourceMetadataCollectionFactory;

private ResourceClassResolverInterface&MockObject $resourceClassResolver;

private ProcessorInterface&MockObject $decorated;

protected function setUp(): void
{
$this->resourceClassResolver = $this->createMock(ResourceClassResolverInterface::class);
$this->resourceClassResolver
->method('isResourceClass')
->willReturn(true);

$this->resourceMetadataCollectionFactory = $this->createMock(ResourceMetadataCollectionFactoryInterface::class);
$this->resourceMetadataCollectionFactory
->method('create')
->willReturn(
new ResourceMetadataCollection(Dummy::class, [
new ApiResource(operations: [
new Get(uriTemplate: '/dummy/{dummyResourceId}{._format}', class: Dummy::class, name: 'get'),
new GetCollection(uriTemplate: '/dummy{._format}', class: Dummy::class, name: 'get_collections'),
new Post(uriTemplate: '/dummy{._format}', outputFormats: ['jsonld' => ['application/ld+json'], 'text/turtle' => ['text/turtle']], class: Dummy::class, name: 'post'),
new Delete(uriTemplate: '/dummy/{dummyResourceId}{._format}', class: Dummy::class, name: 'delete'),
new Put(uriTemplate: '/dummy/{dummyResourceId}{._format}', class: Dummy::class, name: 'put'),
]),
])
);

$this->decorated = $this->createMock(ProcessorInterface::class);
$this->decorated->method('process')->willReturn(new Response());
}

public function testHeadersAcceptPostIsReturnWhenPostAllowed(): void
{
$operation = new Get('/dummy{._format}', class: Dummy::class);

$context = $this->getContext();

$processor = new LinkedDataPlatformProcessor(
$this->decorated,
$this->resourceClassResolver,
$this->resourceMetadataCollectionFactory
);
/** @var Response $response */
$response = $processor->process(null, $operation, [], $context);

$this->assertSame('application/ld+json, text/turtle', $response->headers->get('Accept-Post'));
}

public function testHeadersAcceptPostIsNotSetWhenPostIsNotAllowed(): void
{
$operation = new Get('/dummy/{dummyResourceId}{._format}', class: Dummy::class);
$context = $this->getContext();

$processor = new LinkedDataPlatformProcessor(
$this->decorated,
$this->resourceClassResolver,
$this->resourceMetadataCollectionFactory
);
/** @var Response $response */
$response = $processor->process(null, $operation, [], $context);

$this->assertNull($response->headers->get('Accept-Post'));
}

public function testHeaderAllowReflectsResourceAllowedMethods(): void
{
$operation = new Get('/dummy{._format}', class: Dummy::class);
$context = $this->getContext();

$processor = new LinkedDataPlatformProcessor(
$this->decorated,
$this->resourceClassResolver,
$this->resourceMetadataCollectionFactory
);
/** @var Response $response */
$response = $processor->process(null, $operation, [], $context);
$allowHeader = $response->headers->get('Allow');
$this->assertStringContainsString('OPTIONS', $allowHeader);
$this->assertStringContainsString('HEAD', $allowHeader);
$this->assertStringContainsString('GET', $allowHeader);
$this->assertStringContainsString('POST', $allowHeader);
$operation = new Get('/dummy/{dummyResourceId}{._format}', class: Dummy::class);

/** @var Response $response */
$processor = new LinkedDataPlatformProcessor(
$this->decorated,
$this->resourceClassResolver,
$this->resourceMetadataCollectionFactory
);
/** @var Response $response */
$response = $processor->process('data', $operation, [], $this->getContext());
$allowHeader = $response->headers->get('Allow');
$this->assertStringContainsString('OPTIONS', $allowHeader);
$this->assertStringContainsString('HEAD', $allowHeader);
$this->assertStringContainsString('GET', $allowHeader);
$this->assertStringContainsString('PUT', $allowHeader);
$this->assertStringContainsString('DELETE', $allowHeader);
}

public function testProcessorWithoutRequiredConditionReturnOriginalResponse(): void
{
// Operation is an Error
$processor = new LinkedDataPlatformProcessor($this->decorated, $this->resourceClassResolver, $this->resourceMetadataCollectionFactory);
$response = $processor->process(null, new Error(), $this->getContext());
$this->assertNull($response->headers->get('Allow'));
}

private function createGetRequest(): Request
{
$request = new Request();
$request->setMethod('GET');
$request->setRequestFormat('json');
$request->headers->set('Accept', 'application/ld+json');

return $request;
}

private function getContext(): array
{
return [
'resource_class' => Dummy::class,
'request' => $this->createGetRequest(),
];
}
}
6 changes: 6 additions & 0 deletions src/Symfony/Bundle/Resources/config/state/processor.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,11 @@
<service id="api_platform.state_processor.add_link_header" class="ApiPlatform\State\Processor\AddLinkHeaderProcessor" decorates="api_platform.state_processor.respond">
<argument type="service" id="api_platform.state_processor.add_link_header.inner" />
</service>

<service id="api_platform.state_processor.linked_data_platform" class="ApiPlatform\State\Processor\LinkedDataPlatformProcessor" decorates="api_platform.state_processor.respond">
<argument type="service" id="api_platform.state_processor.linked_data_platform.inner" />
<argument type="service" id="api_platform.resource_class_resolver" />
<argument type="service" id="api_platform.metadata.resource.metadata_collection_factory" />
</service>
</services>
</container>
6 changes: 6 additions & 0 deletions src/Symfony/Bundle/Resources/config/symfony/events.xml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@
<argument type="service" id="api_platform.state_processor.add_link_header.inner" />
</service>

<service id="api_platform.state_processor.linked_data_platform" class="ApiPlatform\State\Processor\LinkedDataPlatformProcessor" decorates="api_platform.state_processor.respond">
<argument type="service" id="api_platform.state_processor.linked_data_platform.inner" />
<argument type="service" id="api_platform.resource_class_resolver" />
<argument type="service" id="api_platform.metadata.resource.metadata_collection_factory" />
</service>

<service id="api_platform.listener.view.write" class="ApiPlatform\Symfony\EventListener\WriteListener">
<argument type="service" id="api_platform.state_processor.write" />
<argument type="service" id="api_platform.metadata.resource.metadata_collection_factory" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?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\Tests\Fixtures\TestBundle\ApiResource;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;

#[ApiResource(operations: [
new Get(
uriTemplate: '/dummy_get_post_delete_operations/{id}',
provider: [self::class, 'provideItem'],
),
new GetCollection(
uriTemplate: '/dummy_get_post_delete_operations',
provider: [self::class, 'provide'], ),
new Post(
uriTemplate: '/dummy_get_post_delete_operations',
provider: [self::class, 'provide'], ),
new Delete(
uriTemplate: '/dummy_get_post_delete_operations/{id}',
provider: [self::class, 'provideItem'], ),
])]
class DummyGetPostDeleteOperation
{
public ?int $id;

public ?string $name = null;

public static function provide(Operation $operation, array $uriVariables = [], array $context = []): array
{
$dummyResource = new self();
$dummyResource->id = 1;
$dummyResource->name = 'Dummy name';

return [
$dummyResource,
];
}

public static function provideItem(Operation $operation, array $uriVariables = [], array $context = []): self
{
$dummyResource = new self();
$dummyResource->id = $uriVariables['id'];
$dummyResource->name = 'Dummy name';

return $dummyResource;
}
}
Loading
Loading