Skip to content

Commit

Permalink
refactor(metadata): replace HttpOperation constants by raw strings (#…
Browse files Browse the repository at this point in the history
…5494)

updateing metadata
  • Loading branch information
helyakin committed Apr 21, 2023
1 parent ccef472 commit 26cd25c
Show file tree
Hide file tree
Showing 21 changed files with 38 additions and 43 deletions.
2 changes: 1 addition & 1 deletion src/Doctrine/Common/State/PersistProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function process(mixed $data, Operation $operation, array $uriVariables =
// PUT: reset the existing object managed by Doctrine and merge data sent by the user in it
// This custom logic is needed because EntityManager::merge() has been deprecated and UPSERT isn't supported:
// https://github.com/doctrine/orm/issues/8461#issuecomment-1250233555
if ($operation instanceof HttpOperation && HttpOperation::METHOD_PUT === $operation->getMethod() && ($operation->getExtraProperties()['standard_put'] ?? false)) {
if ($operation instanceof HttpOperation && 'PUT' === $operation->getMethod() && ($operation->getExtraProperties()['standard_put'] ?? false)) {
\assert(method_exists($manager, 'getReference'));
// TODO: the call to getReference is most likely to fail with complex identifiers
$newData = $data;
Expand Down
4 changes: 2 additions & 2 deletions src/Hydra/Serializer/DocumentationNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ private function getHydraOperations(bool $collection, ?ResourceMetadataCollectio
$hydraOperations = [];
foreach ($resourceMetadataCollection as $resourceMetadata) {
foreach ($resourceMetadata->getOperations() as $operation) {
if ((HttpOperation::METHOD_POST === $operation->getMethod() || $operation instanceof CollectionOperationInterface) !== $collection) {
if (('POST' === $operation->getMethod() || $operation instanceof CollectionOperationInterface) !== $collection) {
continue;
}

Expand All @@ -241,7 +241,7 @@ private function getHydraOperations(bool $collection, ?ResourceMetadataCollectio
*/
private function getHydraOperation(HttpOperation $operation, string $prefixedShortName): array
{
$method = $operation->getMethod() ?: HttpOperation::METHOD_GET;
$method = $operation->getMethod() ?: 'GET';

$hydraOperation = $operation->getHydraContext() ?? [];
if ($operation->getDeprecationReason()) {
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/Delete.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public function __construct(
array $extraProperties = [],
) {
parent::__construct(
method: self::METHOD_DELETE,
method: 'DELETE',
uriTemplate: $uriTemplate,
types: $types,
formats: $formats,
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/HttpOperation.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class HttpOperation extends Operation
* @param string|callable|null $processor {@see https://api-platform.com/docs/core/state-processors/#state-processors}
*/
public function __construct(
protected string $method = self::METHOD_GET,
protected string $method = 'GET',
protected ?string $uriTemplate = null,
protected ?array $types = null,
protected $formats = null,
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/NotExposed.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ final class NotExposed extends HttpOperation
* {@inheritdoc}
*/
public function __construct(
string $method = self::METHOD_GET,
string $method = 'GET',
?string $uriTemplate = null,
?array $types = null,
$formats = null,
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/Patch.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public function __construct(
array $extraProperties = [],
) {
parent::__construct(
method: self::METHOD_PATCH,
method: 'PATCH',
uriTemplate: $uriTemplate,
types: $types,
formats: $formats,
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public function __construct(
private ?string $itemUriTemplate = null
) {
parent::__construct(
method: self::METHOD_POST,
method: 'POST',
uriTemplate: $uriTemplate,
types: $types,
formats: $formats,
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/Put.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public function __construct(
private ?bool $allowCreate = null,
) {
parent::__construct(
method: self::METHOD_PUT,
method: 'PUT',
uriTemplate: $uriTemplate,
types: $types,
formats: $formats,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operations;
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;

Expand Down Expand Up @@ -69,7 +68,7 @@ private function normalize(array $resourceInputFormats, array $resourceOutputFor
$operation = $operation->withFormats($this->normalizeFormats($operation->getFormats()));
}

if (($isPatch = HttpOperation::METHOD_PATCH === $operation->getMethod()) && !$operation->getFormats() && !$operation->getInputFormats()) {
if (($isPatch = 'PATCH' === $operation->getMethod()) && !$operation->getFormats() && !$operation->getInputFormats()) {
$operation = $operation->withInputFormats($this->patchFormats);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function create(string $resourceClass): ResourceMetadataCollection

foreach ($operations as $operation) {
// An item operation has been found, nothing to do anymore in this factory
if ((HttpOperation::METHOD_GET === $operation->getMethod() && !$operation instanceof CollectionOperationInterface) || ($operation->getExtraProperties()['is_legacy_resource_metadata'] ?? false)) {
if (('GET' === $operation->getMethod() && !$operation instanceof CollectionOperationInterface) || ($operation->getExtraProperties()['is_legacy_resource_metadata'] ?? false)) {
return $resourceMetadataCollection;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ private function configureUriVariables(ApiResource|HttpOperation $operation): Ap
$operation = $this->normalizeUriVariables($operation);

if (!($uriTemplate = $operation->getUriTemplate())) {
if ($operation instanceof HttpOperation && HttpOperation::METHOD_POST === $operation->getMethod()) {
if ($operation instanceof HttpOperation && 'POST' === $operation->getMethod()) {
return $operation->withUriVariables([]);
}

Expand Down Expand Up @@ -207,7 +207,7 @@ private function configureUriVariables(ApiResource|HttpOperation $operation): Ap
}

// We generated this operation but there're some missing identifiers
$uriVariables = HttpOperation::METHOD_POST === $operation->getMethod() || $operation instanceof CollectionOperationInterface ? [] : $operation->getUriVariables();
$uriVariables = 'POST' === $operation->getMethod() || $operation instanceof CollectionOperationInterface ? [] : $operation->getUriVariables();

foreach ($diff as $key) {
$uriVariables[$key] = $this->linkFactory->createLinkFromProperty($operation, $key);
Expand Down
4 changes: 2 additions & 2 deletions src/Metadata/Resource/ResourceMetadataCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ public function getOperation(?string $operationName = null, bool $forceCollectio

foreach ($metadata->getOperations() ?? [] as $name => $operation) {
$isCollection = $operation instanceof CollectionOperationInterface;
$method = $operation->getMethod() ?? HttpOperation::METHOD_GET;
$isGetOperation = HttpOperation::METHOD_GET === $method || HttpOperation::METHOD_OPTIONS === $method || HttpOperation::METHOD_HEAD === $method;
$method = $operation->getMethod() ?? 'GET';
$isGetOperation = 'GET' === $method || 'OPTIONS' === $method || 'HEAD' === $method;
if ('' === $operationName && $isGetOperation && ($forceCollection ? $isCollection : !$isCollection)) {
return $this->operationCache[$httpCacheKey] = $operation;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/Tests/Fixtures/Metadata/Get.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ final class Get extends HttpOperation
*/
public function __construct(...$args)
{
parent::__construct(self::METHOD_GET, ...$args);
parent::__construct('GET', ...$args);
}
}
24 changes: 12 additions & 12 deletions src/OpenApi/Factory/OpenApiFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection
}

$path = $this->getPath($path);
$method = $operation->getMethod() ?? HttpOperation::METHOD_GET;
$method = $operation->getMethod() ?? 'GET';

if (!\in_array($method, PathItem::$methods, true)) {
continue;
Expand Down Expand Up @@ -267,7 +267,7 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection
$openapiOperation = $openapiOperation->withParameter($parameter);
}

if ($operation instanceof CollectionOperationInterface && HttpOperation::METHOD_POST !== $method) {
if ($operation instanceof CollectionOperationInterface && 'POST' !== $method) {
foreach (array_merge($this->getPaginationParameters($operation), $this->getFiltersParameters($operation)) as $parameter) {
if ($this->hasParameter($openapiOperation, $parameter)) {
continue;
Expand All @@ -280,11 +280,11 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection
$existingResponses = $openapiOperation?->getResponses() ?: [];
// Create responses
switch ($method) {
case HttpOperation::METHOD_GET:
case 'GET':
$successStatus = (string) $operation->getStatus() ?: 200;
$openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, sprintf('%s %s', $resourceShortName, $operation instanceof CollectionOperationInterface ? 'collection' : 'resource'), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas);
break;
case HttpOperation::METHOD_POST:
case 'POST':
$successStatus = (string) $operation->getStatus() ?: 201;

$openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, sprintf('%s resource created', $resourceShortName), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas, $resourceMetadataCollection);
Expand All @@ -293,8 +293,8 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection

$openapiOperation = $this->buildOpenApiResponse($existingResponses, '422', 'Unprocessable entity', $openapiOperation);
break;
case HttpOperation::METHOD_PATCH:
case HttpOperation::METHOD_PUT:
case 'PATCH':
case 'PUT':
$successStatus = (string) $operation->getStatus() ?: 200;
$openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, sprintf('%s resource updated', $resourceShortName), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas, $resourceMetadataCollection);
$openapiOperation = $this->buildOpenApiResponse($existingResponses, '400', 'Invalid input', $openapiOperation);
Expand All @@ -303,15 +303,15 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection
}
$openapiOperation = $this->buildOpenApiResponse($existingResponses, '422', 'Unprocessable entity', $openapiOperation);
break;
case HttpOperation::METHOD_DELETE:
case 'DELETE':
$successStatus = (string) $operation->getStatus() ?: 204;

$openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, sprintf('%s resource deleted', $resourceShortName), $openapiOperation);

break;
}

if (!$operation instanceof CollectionOperationInterface && HttpOperation::METHOD_POST !== $operation->getMethod()) {
if (!$operation instanceof CollectionOperationInterface && 'POST' !== $operation->getMethod()) {
if (!isset($existingResponses[404])) {
$openapiOperation = $openapiOperation->withResponse(404, new Response('Resource not found'));
}
Expand Down Expand Up @@ -341,15 +341,15 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection
'The "openapiContext" option is deprecated, use "openapi" instead.'
);
$openapiOperation = $openapiOperation->withRequestBody(new RequestBody($contextRequestBody['description'] ?? '', new \ArrayObject($contextRequestBody['content']), $contextRequestBody['required'] ?? false));
} elseif (null === $openapiOperation->getRequestBody() && \in_array($method, [HttpOperation::METHOD_PATCH, HttpOperation::METHOD_PUT, HttpOperation::METHOD_POST], true)) {
} elseif (null === $openapiOperation->getRequestBody() && \in_array($method, ['PATCH', 'PUT', 'POST'], true)) {
$operationInputSchemas = [];
foreach ($requestMimeTypes as $operationFormat) {
$operationInputSchema = $this->jsonSchemaFactory->buildSchema($resourceClass, $operationFormat, Schema::TYPE_INPUT, $operation, $schema, null, $forceSchemaCollection);
$operationInputSchemas[$operationFormat] = $operationInputSchema;
$this->appendSchemaDefinitions($schemas, $operationInputSchema->getDefinitions());
}

$openapiOperation = $openapiOperation->withRequestBody(new RequestBody(sprintf('The %s %s resource', HttpOperation::METHOD_POST === $method ? 'new' : 'updated', $resourceShortName), $this->buildContent($requestMimeTypes, $operationInputSchemas), true));
$openapiOperation = $openapiOperation->withRequestBody(new RequestBody(sprintf('The %s %s resource', 'POST' === $method ? 'new' : 'updated', $resourceShortName), $this->buildContent($requestMimeTypes, $operationInputSchemas), true));
}

// TODO Remove in 4.0
Expand Down Expand Up @@ -492,12 +492,12 @@ private function getLinks(ResourceMetadataCollection $resourceMetadataCollection
foreach ($resourceMetadataCollection as $resource) {
foreach ($resource->getOperations() as $operationName => $operation) {
$parameters = [];
$method = $operation instanceof HttpOperation ? $operation->getMethod() : HttpOperation::METHOD_GET;
$method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
if (
$operationName === $operation->getName() ||
isset($links[$operationName]) ||
$operation instanceof CollectionOperationInterface ||
HttpOperation::METHOD_GET !== $method
'GET' !== $method
) {
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion src/OpenApi/Tests/Factory/OpenApiFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function testInvoke(): void
'getDummyItem' => (new Get())->withUriTemplate('/dummies/{id}')->withOperation($baseOperation)->withUriVariables(['id' => (new Link())->withFromClass(Dummy::class)->withIdentifiers(['id'])]),
'putDummyItem' => (new Put())->withUriTemplate('/dummies/{id}')->withOperation($baseOperation)->withUriVariables(['id' => (new Link())->withFromClass(Dummy::class)->withIdentifiers(['id'])]),
'deleteDummyItem' => (new Delete())->withUriTemplate('/dummies/{id}')->withOperation($baseOperation)->withUriVariables(['id' => (new Link())->withFromClass(Dummy::class)->withIdentifiers(['id'])]),
'customDummyItem' => (new HttpOperation())->withMethod(HttpOperation::METHOD_HEAD)->withUriTemplate('/foo/{id}')->withOperation($baseOperation)->withUriVariables(['id' => (new Link())->withFromClass(Dummy::class)->withIdentifiers(['id'])])->withOpenapi(new OpenApiOperation(
'customDummyItem' => (new HttpOperation())->withMethod('HEAD')->withUriTemplate('/foo/{id}')->withOperation($baseOperation)->withUriVariables(['id' => (new Link())->withFromClass(Dummy::class)->withIdentifiers(['id'])])->withOpenapi(new OpenApiOperation(
tags: ['Dummy', 'Profile'],
responses: [
'202' => new OpenApiResponse(
Expand Down
7 changes: 3 additions & 4 deletions src/Symfony/EventListener/DeserializeListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
namespace ApiPlatform\Symfony\EventListener;

use ApiPlatform\Api\FormatMatcher;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Serializer\SerializerContextBuilderInterface;
use ApiPlatform\Symfony\Validator\Exception\ValidationException;
Expand Down Expand Up @@ -88,9 +87,9 @@ public function onKernelRequest(RequestEvent $event): void
if (
null !== $data &&
(
HttpOperation::METHOD_POST === $method ||
HttpOperation::METHOD_PATCH === $method ||
(HttpOperation::METHOD_PUT === $method && !($operation->getExtraProperties()['standard_put'] ?? false))
'POST' === $method ||
'PATCH' === $method ||
('PUT' === $method && !($operation->getExtraProperties()['standard_put'] ?? false))
)
) {
$context[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
Expand Down
3 changes: 1 addition & 2 deletions src/Symfony/EventListener/ReadListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
use ApiPlatform\Api\UriVariablesConverterInterface;
use ApiPlatform\Exception\InvalidIdentifierException;
use ApiPlatform\Exception\InvalidUriVariableException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Serializer\SerializerContextBuilderInterface;
Expand Down Expand Up @@ -97,7 +96,7 @@ public function onKernelRequest(RequestEvent $event): void
if (
null === $data &&
(
HttpOperation::METHOD_PUT !== $operation->getMethod() ||
'PUT' !== $operation->getMethod() ||
($operation instanceof Put && !($operation->getAllowCreate() ?? false))
)
) {
Expand Down
5 changes: 2 additions & 3 deletions src/Symfony/EventListener/RespondListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

use ApiPlatform\Api\IriConverterInterface;
use ApiPlatform\Api\UrlGeneratorInterface;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Util\OperationRequestInitiatorTrait;
Expand Down Expand Up @@ -91,7 +90,7 @@ public function onKernelView(ViewEvent $event): void
) {
$status = 301;
$headers['Location'] = $this->iriConverter->getIriFromResource($request->attributes->get('data'), UrlGeneratorInterface::ABS_PATH, $operation);
} elseif (HttpOperation::METHOD_PUT === $method && !($attributes['previous_data'] ?? null) && null === $status && ($operation instanceof Put && ($operation->getAllowCreate() ?? false))) {
} elseif ('PUT' === $method && !($attributes['previous_data'] ?? null) && null === $status && ($operation instanceof Put && ($operation->getAllowCreate() ?? false))) {
$status = Response::HTTP_CREATED;
}

Expand All @@ -100,7 +99,7 @@ public function onKernelView(ViewEvent $event): void
if ($request->attributes->has('_api_write_item_iri')) {
$headers['Content-Location'] = $request->attributes->get('_api_write_item_iri');

if ((Response::HTTP_CREATED === $status || (300 <= $status && $status < 400)) && HttpOperation::METHOD_POST === $method) {
if ((Response::HTTP_CREATED === $status || (300 <= $status && $status < 400)) && 'POST' === $method) {
$headers['Location'] = $request->attributes->get('_api_write_item_iri');
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/Symfony/Routing/ApiLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
namespace ApiPlatform\Symfony\Routing;

use ApiPlatform\Exception\RuntimeException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use Symfony\Component\Config\FileLocator;
Expand Down Expand Up @@ -97,7 +96,7 @@ public function load(mixed $data, string $type = null): RouteCollection
$operation->getOptions() ?? [],
$operation->getHost() ?? '',
$operation->getSchemes() ?? [],
[$operation->getMethod() ?? HttpOperation::METHOD_GET],
[$operation->getMethod() ?? 'GET'],
$operation->getCondition() ?? ''
);

Expand Down
Loading

0 comments on commit 26cd25c

Please sign in to comment.