Skip to content

Make it easier to configure operations #1470

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
Nov 1, 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
2 changes: 1 addition & 1 deletion src/Bridge/Symfony/Routing/ApiLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private function addRoute(RouteCollection $routeCollection, string $resourceClas
}

if (!isset($operation['method'])) {
throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
throw new RuntimeException(sprintf('Either a "route_name" or a "method" operation attribute must exist for the operation "%s" of the resource "%s".', $operationName, $resourceClass));
}

if (null === $controller = $operation['controller'] ?? null) {
Expand Down
9 changes: 1 addition & 8 deletions src/Bridge/Symfony/Routing/OperationMethodResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,7 @@ private function getOperationMethod(string $resourceClass, string $operationName
throw new RuntimeException(sprintf('Either a "route_name" or a "method" operation attribute must exist for the operation "%s" of the resource "%s".', $operationName, $resourceClass));
}

$route = $this->getRoute($routeName);
$methods = $route->getMethods();

if (empty($methods)) {
return 'GET';
}

return $methods[0];
return $this->getRoute($routeName)->getMethods()[0] ?? 'GET';
}

/**
Expand Down
57 changes: 53 additions & 4 deletions src/Metadata/Resource/Factory/OperationResourceMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,23 @@
*/
final class OperationResourceMetadataFactory implements ResourceMetadataFactoryInterface
{
/**
* @internal
*/
const SUPPORTED_COLLECTION_OPERATION_METHODS = [
'GET' => true,
'POST' => true,
];

/**
* @internal
*/
const SUPPORTED_ITEM_OPERATION_METHODS = [
'GET' => true,
'PUT' => true,
'DELETE' => true,
];

private $decorated;
private $formats;

Expand All @@ -37,16 +54,19 @@ public function __construct(ResourceMetadataFactoryInterface $decorated, array $
public function create(string $resourceClass): ResourceMetadata
{
$resourceMetadata = $this->decorated->create($resourceClass);
$reflectionClass = new \ReflectionClass($resourceClass);
$isAbstract = $reflectionClass->isAbstract();
$isAbstract = (new \ReflectionClass($resourceClass))->isAbstract();

if (null === $resourceMetadata->getCollectionOperations()) {
$collectionOperations = $resourceMetadata->getCollectionOperations();
if (null === $collectionOperations) {
$resourceMetadata = $resourceMetadata->withCollectionOperations($this->createOperations(
$isAbstract ? ['GET'] : ['GET', 'POST']
));
} else {
$resourceMetadata = $this->normalize(true, $resourceMetadata, $collectionOperations);
}

if (null === $resourceMetadata->getItemOperations()) {
$itemOperations = $resourceMetadata->getItemOperations();
if (null === $itemOperations) {
$methods = ['GET', 'DELETE'];

if (!$isAbstract) {
Expand All @@ -58,6 +78,8 @@ public function create(string $resourceClass): ResourceMetadata
}

$resourceMetadata = $resourceMetadata->withItemOperations($this->createOperations($methods));
} else {
$resourceMetadata = $this->normalize(false, $resourceMetadata, $itemOperations);
}

return $resourceMetadata;
Expand All @@ -72,4 +94,31 @@ private function createOperations(array $methods): array

return $operations;
}

private function normalize(bool $collection, ResourceMetadata $resourceMetadata, array $operations): ResourceMetadata
{
$newOperations = [];
foreach ($operations as $operationName => $operation) {
// e.g.: @ApiResource(itemOperations={"get"})
if (is_int($operationName) && is_string($operation)) {
$operationName = $operation;
$operation = [];
}

$upperOperationName = strtoupper($operationName);
if ($collection) {
$supported = isset(self::SUPPORTED_COLLECTION_OPERATION_METHODS[$upperOperationName]);
} else {
$supported = isset(self::SUPPORTED_ITEM_OPERATION_METHODS[$upperOperationName]) || (isset($this->formats['jsonapi']) && 'PATCH' === $upperOperationName);
}

if ($supported && !isset($operation['method']) && !isset($operation['route_name'])) {
$operation['method'] = $upperOperationName;
}

$newOperations[$operationName] = $operation;
}

return $collection ? $resourceMetadata->withCollectionOperations($newOperations) : $resourceMetadata->withItemOperations($newOperations);
}
}
4 changes: 2 additions & 2 deletions tests/Fixtures/TestBundle/Entity/CustomActionDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
/**
* @ORM\Entity
* @ApiResource(itemOperations={
* "get"={"method"="GET"},
* "get",
* "custom_normalization"={"route_name"="custom_normalization"}
* }, collectionOperations={
* "get"={"method"="GET"},
* "get",
* "custom_denormalization"={"route_name"="custom_denormalization"}
* })
*
Expand Down
7 changes: 3 additions & 4 deletions tests/Fixtures/TestBundle/Entity/OverriddenOperationDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,17 @@
* "denormalization_context"={"groups"={"overridden_operation_dummy_write"}}
* },
* collectionOperations={
*
* "get"={"method"="GET"},
* "post"={"method"="POST"},
* "swagger"= {
* "path"="/override/swagger",
* "method"="GET",
* }
* }
* },
* itemOperations={
* "swagger"= {
* "method"="GET",
* },
* "method"="GET",
* },
* "get"={
* "method"="GET",
* "normalization_context"={"groups"={"overridden_operation_dummy_get"}},
Expand Down
6 changes: 3 additions & 3 deletions tests/Fixtures/TestBundle/Entity/RelationEmbedder.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
* "hydra_context"={"@type"="hydra:Operation", "hydra:title"="A custom operation", "returns"="xmls:string"}
* },
* itemOperations={
* "get"={"method"="GET"},
* "put"={"method"="PUT"},
* "delete"={"method"="DELETE"},
* "get",
* "put"={},
* "delete",
* "custom_get"={"route_name"="relation_embedded.custom_get"},
* "custom1"={"path"="/api/custom-call/{id}", "method"="GET"},
* "custom2"={"path"="/api/custom-call/{id}", "method"="PUT"},
Expand Down
6 changes: 3 additions & 3 deletions tests/Fixtures/TestBundle/Entity/SecuredDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
* @ApiResource(
* attributes={"access_control"="has_role('ROLE_USER')"},
* collectionOperations={
* "get"={"method"="GET"},
* "post"={"method"="POST", "access_control"="has_role('ROLE_ADMIN')"}
* "get",
* "post"={"access_control"="has_role('ROLE_ADMIN')"}
* },
* itemOperations={
* "get"={"method"="GET", "access_control"="has_role('ROLE_USER') and object.getOwner() == user"}
* "get"={"access_control"="has_role('ROLE_USER') and object.getOwner() == user"}
* }
* )
* @ORM\Entity
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?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\Metadata\Resource\Factory;

use ApiPlatform\Core\Metadata\Resource\Factory\OperationResourceMetadataFactory;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy;
use PHPUnit\Framework\TestCase;

/**
* @author Kévin Dunglas <[email protected]>
*/
class OperationResourceMetadataFactoryTest extends TestCase
{
/**
* @dataProvider getMetadata
*/
public function testCreateOperation(ResourceMetadata $before, ResourceMetadata $after, array $formats = [])
{
$decoratedProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
$decoratedProphecy->create(Dummy::class)->shouldBeCalled()->willReturn($before);

$this->assertEquals($after, (new OperationResourceMetadataFactory($decoratedProphecy->reveal(), $formats))->create(Dummy::class));
}

public function getMetadata()
{
$jsonapi = ['jsonapi' => ['application/vnd.api+json']];

return [
// Item operations
[new ResourceMetadata(null, null, null, null, []), new ResourceMetadata(null, null, null, ['get' => ['method' => 'GET'], 'put' => ['method' => 'PUT'], 'delete' => ['method' => 'DELETE']], [])],
[new ResourceMetadata(null, null, null, null, []), new ResourceMetadata(null, null, null, ['get' => ['method' => 'GET'], 'put' => ['method' => 'PUT'], 'patch' => ['method' => 'PATCH'], 'delete' => ['method' => 'DELETE']], []), $jsonapi],
[new ResourceMetadata(null, null, null, ['get'], []), new ResourceMetadata(null, null, null, ['get' => ['method' => 'GET']], [])],
[new ResourceMetadata(null, null, null, ['put'], []), new ResourceMetadata(null, null, null, ['put' => ['method' => 'PUT']], [])],
[new ResourceMetadata(null, null, null, ['delete'], []), new ResourceMetadata(null, null, null, ['delete' => ['method' => 'DELETE']], [])],
[new ResourceMetadata(null, null, null, ['patch'], []), new ResourceMetadata(null, null, null, ['patch' => []], [])],
[new ResourceMetadata(null, null, null, ['patch'], []), new ResourceMetadata(null, null, null, ['patch' => ['method' => 'PATCH']], []), $jsonapi],

// Collection operations
[new ResourceMetadata(null, null, null, []), new ResourceMetadata(null, null, null, [], ['get' => ['method' => 'GET'], 'post' => ['method' => 'POST']])],
[new ResourceMetadata(null, null, null, [], ['get']), new ResourceMetadata(null, null, null, [], ['get' => ['method' => 'GET']])],
[new ResourceMetadata(null, null, null, [], ['post']), new ResourceMetadata(null, null, null, [], ['post' => ['method' => 'POST']])],
[new ResourceMetadata(null, null, null, [], ['options']), new ResourceMetadata(null, null, null, [], ['options' => []])],
];
}
}