From ba37844a9992bb5717f4e0fc61950ce391e544bc Mon Sep 17 00:00:00 2001 From: Yuri Gaidoba Date: Wed, 15 Nov 2023 10:06:25 +0100 Subject: [PATCH] SUPPORT-86535 - add symfony 6 support --- .github/workflows/ci.yml | 2 + .gitignore | 2 + CHANGELOG.md | 8 ++ composer.json | 18 ++-- phpunit.xml.dist | 2 +- src/Annotation/Body.php | 22 +--- src/Annotation/BodyContentType.php | 8 -- src/Annotation/PathAttribute.php | 20 +--- src/Annotation/Query.php | 22 +--- src/Annotation/RequiredPermissions.php | 4 - src/Annotation/ResponseNormalization.php | 12 +-- src/DependencyInjection/Configuration.php | 2 +- src/Entity/Error.php | 73 +++---------- src/Entity/PathAttributeResolverOptions.php | 7 -- src/Entity/QueryResolverOptions.php | 17 +-- src/Entity/RestRequestOptions.php | 41 ++----- src/Entity/Violation.php | 38 ++----- src/Exception/ApiException.php | 42 ++------ src/Listener/LocaleListener.php | 2 +- src/Listener/RestExceptionListener.php | 4 +- src/Listener/RestRequestListener.php | 4 +- src/Listener/RestResponseListener.php | 2 +- src/Normalizer/ErrorNormalizer.php | 17 +-- .../Pagination/PagedQueryNormalizer.php | 16 ++- .../Pagination/ResultNormalizer.php | 11 +- src/Normalizer/ViolationNormalizer.php | 11 +- .../Annotation/ReflectionMethodWrapper.php | 2 +- src/Service/ResponseBuilder.php | 8 +- src/Service/RestRequestHelper.php | 9 +- src/Service/RestRequestOptionsRegistry.php | 8 +- .../CamelCaseToSnakeCaseConverter.php | 2 +- src/Service/Validation/EntityValidator.php | 7 +- .../PropertyPathConverterInterface.php | 7 +- .../PayseraFixtureTestExtension.php | 4 +- .../Resources/config/legacy_routing.xml | 43 ++++++++ .../Resources/config/legacy_services.xml | 102 ++++++++++++++++++ .../Resources/config/routing.xml | 34 +++--- .../Resources/config/services.xml | 6 +- .../Service/CustomPropertyPathConverter.php | 2 +- tests/Functional/Fixtures/TestKernel.php | 2 +- tests/Functional/Fixtures/config/common.yml | 11 +- .../Fixtures/config/legacy_common.yml | 46 ++++++++ .../Fixtures/config/legacy_routing.yml | 3 + tests/Functional/FunctionalRestBundleTest.php | 2 +- tests/Functional/FunctionalTestCase.php | 8 +- tests/Unit/Helper/HttpKernelHelper.php | 19 ++++ tests/Unit/Listener/LocaleListenerTest.php | 7 +- .../Listener/RestExceptionListenerTest.php | 23 ++-- .../Normalizer/PagedQueryNormalizerTest.php | 26 ++--- .../RestRequestOptionsBuilderTest.php | 10 +- tests/Unit/Service/RestRequestHelperTest.php | 13 +-- .../RestRequestOptionsValidatorTest.php | 27 +++-- .../Validation/EntityValidatorTest.php | 15 +-- tests/bootstrap.php | 7 ++ 54 files changed, 445 insertions(+), 415 deletions(-) create mode 100644 tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_routing.xml create mode 100644 tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_services.xml create mode 100644 tests/Functional/Fixtures/config/legacy_common.yml create mode 100644 tests/Functional/Fixtures/config/legacy_routing.yml create mode 100644 tests/Unit/Helper/HttpKernelHelper.php create mode 100644 tests/bootstrap.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 61910b3..c74f547 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,6 +42,8 @@ jobs: # { php-version: '8.0', symfony-version: '5.4.*', dependency-versions: 'latest' }, # { php-version: '8.1', symfony-version: '5.4.*', dependency-versions: 'lowest' }, # { php-version: '8.1', symfony-version: '5.4.*', dependency-versions: 'latest' }, + { php-version: '8.1', symfony-version: '6.4.*', dependency-versions: 'lowest' }, + { php-version: '8.1', symfony-version: '6.4.*', dependency-versions: 'latest' }, ] steps: - name: Checkout diff --git a/.gitignore b/.gitignore index 27210ae..fcd145e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ composer.lock bin/ var/ !bin/update-constraints-to-lowest.php + +.phpunit.result.cache diff --git a/CHANGELOG.md b/CHANGELOG.md index 081cd95..e134d17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.7.0] +### Added +- Support for Symfony 6.4 + +### Changed +- Fixed code style +- Fixed tests + ## [1.6.0] ### Added - Allow library to work with various version of `paysera/lib-object-wrapper` from `0.1.0` diff --git a/composer.json b/composer.json index 34d1132..a26d7a0 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,6 @@ { "name": "paysera/lib-api-bundle", + "version": "1.7.0", "description": "Symfony bundle that allows easy configuration for your REST endpoints.", "keywords": ["REST", "RESTful", "API"], "type": "symfony-bundle", @@ -17,9 +18,9 @@ "require": { "php": "^7.1 || ^8.0", "ext-json": "*", - "symfony/framework-bundle": "^3.4.34|^4.3|^5.4", - "symfony/security-bundle": "^3.4.34|^4.3|^5.4", - "symfony/validator": "^3.4.34|^4.3|^5.4", + "symfony/framework-bundle": "^3.4.34|^4.3|^5.4|^6.4", + "symfony/security-bundle": "^3.4.34|^4.3|^5.4|^6.4", + "symfony/validator": "^3.4.34|^4.3|^5.4|^6.4", "paysera/lib-normalization-bundle": "^1.1.0", "paysera/lib-normalization": "^1.2", "paysera/lib-object-wrapper": "~0.1", @@ -31,13 +32,16 @@ "require-dev": { "phpunit/phpunit": "^6.5 || ^9.0", "mockery/mockery": "^1.2.4", - "symfony/yaml": "^3.4.34|^4.3|^5.4", - "doctrine/doctrine-bundle": "^1.7.2|^2.0", + "symfony/yaml": "^3.4.34|^4.3|^5.4|^6.4", + "doctrine/doctrine-bundle": "^1.12.0|^2.1", "doctrine/orm": "~2.5.14|^2.6.3", - "doctrine/annotations": "^v1.7" + "doctrine/annotations": "^v1.14" }, "config": { - "bin-dir": "bin" + "bin-dir": "bin", + "allow-plugins": { + "ocramius/package-versions": false + } }, "scripts": { "phpunit": "phpunit", diff --git a/phpunit.xml.dist b/phpunit.xml.dist index bde7395..38b68e6 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -10,7 +10,7 @@ convertWarningsToExceptions = "true" processIsolation = "false" stopOnFailure = "false" - bootstrap = "vendor/autoload.php" > + bootstrap = "tests/bootstrap.php" > diff --git a/src/Annotation/Body.php b/src/Annotation/Body.php index 157545c..861fbea 100644 --- a/src/Annotation/Body.php +++ b/src/Annotation/Body.php @@ -41,41 +41,25 @@ public function __construct(array $options) $this->setOptional($options['optional'] ?? null); } - /** - * @param string|null $denormalizationType - * @return $this - */ - private function setDenormalizationType($denormalizationType): self + private function setDenormalizationType(?string $denormalizationType): self { $this->denormalizationType = $denormalizationType; return $this; } - /** - * @param string|null $denormalizationGroup - * @return $this - */ - public function setDenormalizationGroup($denormalizationGroup): self + public function setDenormalizationGroup(?string $denormalizationGroup): self { $this->denormalizationGroup = $denormalizationGroup; return $this; } - /** - * @param string $parameterName - * @return $this - */ private function setParameterName(string $parameterName): self { $this->parameterName = $parameterName; return $this; } - /** - * @param bool|null $optional - * @return $this - */ - private function setOptional($optional): self + private function setOptional(?bool $optional): self { $this->optional = $optional; return $this; diff --git a/src/Annotation/BodyContentType.php b/src/Annotation/BodyContentType.php index 1f0189b..0b5664f 100644 --- a/src/Annotation/BodyContentType.php +++ b/src/Annotation/BodyContentType.php @@ -28,20 +28,12 @@ public function __construct(array $options) $this->setJsonEncodedBody($options['jsonEncodedBody'] ?? false); } - /** - * @param array $supportedContentTypes - * @return $this - */ private function setSupportedContentTypes(array $supportedContentTypes): self { $this->supportedContentTypes = $supportedContentTypes; return $this; } - /** - * @param bool $jsonEncodedBody - * @return $this - */ private function setJsonEncodedBody(bool $jsonEncodedBody): self { $this->jsonEncodedBody = $jsonEncodedBody; diff --git a/src/Annotation/PathAttribute.php b/src/Annotation/PathAttribute.php index b78d3de..fe8e8de 100644 --- a/src/Annotation/PathAttribute.php +++ b/src/Annotation/PathAttribute.php @@ -42,41 +42,25 @@ public function __construct(array $options) $this->setResolutionMandatory($options['resolutionMandatory'] ?? null); } - /** - * @param string $parameterName - * @return $this - */ private function setParameterName(string $parameterName): self { $this->parameterName = $parameterName; return $this; } - /** - * @param string $pathPartName - * @return $this - */ private function setPathPartName(string $pathPartName): self { $this->pathPartName = $pathPartName; return $this; } - /** - * @param string|null $resolverType - * @return $this - */ - private function setResolverType($resolverType): self + private function setResolverType(?string $resolverType): self { $this->resolverType = $resolverType; return $this; } - /** - * @param bool|null $resolutionMandatory - * @return $this - */ - private function setResolutionMandatory($resolutionMandatory): self + private function setResolutionMandatory(?bool $resolutionMandatory): self { $this->resolutionMandatory = $resolutionMandatory; return $this; diff --git a/src/Annotation/Query.php b/src/Annotation/Query.php index c09e3e9..783250e 100644 --- a/src/Annotation/Query.php +++ b/src/Annotation/Query.php @@ -42,41 +42,25 @@ public function __construct(array $options) $this->setValidation($options['validation'] ?? null); } - /** - * @param string $parameterName - * @return $this - */ private function setParameterName(string $parameterName): self { $this->parameterName = $parameterName; return $this; } - /** - * @param string|null $denormalizationType - * @return $this - */ - private function setDenormalizationType($denormalizationType): self + private function setDenormalizationType(?string $denormalizationType): self { $this->denormalizationType = $denormalizationType; return $this; } - /** - * @param string|null $denormalizationGroup - * @return $this - */ - public function setDenormalizationGroup($denormalizationGroup): self + public function setDenormalizationGroup(?string $denormalizationGroup): self { $this->denormalizationGroup = $denormalizationGroup; return $this; } - /** - * @param Validation|null $validation - * @return $this - */ - private function setValidation($validation): self + private function setValidation(?Validation $validation): self { $this->validation = $validation; return $this; diff --git a/src/Annotation/RequiredPermissions.php b/src/Annotation/RequiredPermissions.php index 16424e5..b6fa285 100644 --- a/src/Annotation/RequiredPermissions.php +++ b/src/Annotation/RequiredPermissions.php @@ -22,10 +22,6 @@ public function __construct(array $options) $this->setPermissions($options['permissions']); } - /** - * @param array $permissions - * @return $this - */ private function setPermissions(array $permissions): self { $this->permissions = $permissions; diff --git a/src/Annotation/ResponseNormalization.php b/src/Annotation/ResponseNormalization.php index 01eac36..f639435 100644 --- a/src/Annotation/ResponseNormalization.php +++ b/src/Annotation/ResponseNormalization.php @@ -28,21 +28,13 @@ public function __construct(array $options) $this->setNormalizationGroup($options['normalizationGroup'] ?? null); } - /** - * @param string|null $normalizationType - * @return $this - */ - private function setNormalizationType($normalizationType): self + private function setNormalizationType(?string $normalizationType): self { $this->normalizationType = $normalizationType; return $this; } - /** - * @param string|null $normalizationGroup - * @return $this - */ - public function setNormalizationGroup($normalizationGroup): self + public function setNormalizationGroup(?string $normalizationGroup): self { $this->normalizationGroup = $normalizationGroup; return $this; diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 99b4c98..8faa5a7 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -10,7 +10,7 @@ class Configuration implements ConfigurationInterface { - public function getConfigTreeBuilder() + public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('paysera_api'); $rootNode = method_exists($treeBuilder, 'getRootNode') diff --git a/src/Entity/Error.php b/src/Entity/Error.php index 05ee66a..5bc9fef 100644 --- a/src/Entity/Error.php +++ b/src/Entity/Error.php @@ -45,115 +45,68 @@ public function __construct() $this->violations = []; } - /** - * @param string|null $code - * - * @return $this - */ - public function setCode($code) + public function setCode(?string $code): self { $this->code = $code; return $this; } - /** - * @return string|null - */ - public function getCode() + public function getCode(): ?string { return $this->code; } - /** - * @param int|null $statusCode - * @return $this - */ - public function setStatusCode($statusCode) + public function setStatusCode(?int $statusCode): self { $this->statusCode = $statusCode; return $this; } - /** - * @return int|null - */ - public function getStatusCode() + public function getStatusCode(): ?int { return $this->statusCode; } - /** - * @param string|null $uri - * - * @return $this - */ - public function setUri($uri) + public function setUri(?string $uri): self { $this->uri = $uri; return $this; } - /** - * @return string|null - */ - public function getUri() + public function getUri(): ?string { return $this->uri; } - /** - * @param string|null $message - * - * @return $this - */ - public function setMessage($message) + public function setMessage(?string $message): self { $this->message = $message; return $this; } - /** - * @return string|null - */ - public function getMessage() + public function getMessage(): ?string { return $this->message; } - /** - * @param array|null $properties - * - * @return $this - */ - public function setProperties($properties) + public function setProperties(?array $properties): self { $this->properties = $properties; return $this; } - /** - * @return array|null - */ - public function getProperties() + public function getProperties(): ?array { return $this->properties; } - /** - * @param array|null $data - * - * @return $this - */ - public function setData($data) + public function setData(?array $data): self { $this->data = $data; return $this; } - /** - * @return array|null - */ - public function getData() + public function getData(): ?array { return $this->data; } @@ -171,7 +124,7 @@ public function getViolations(): array * * @return $this */ - public function setViolations(array $violations) + public function setViolations(array $violations): self { $this->violations = $violations; return $this; diff --git a/src/Entity/PathAttributeResolverOptions.php b/src/Entity/PathAttributeResolverOptions.php index ab5708a..3f0e487 100644 --- a/src/Entity/PathAttributeResolverOptions.php +++ b/src/Entity/PathAttributeResolverOptions.php @@ -74,18 +74,11 @@ public function getPathAttributeResolverType(): string return $this->pathAttributeResolverType; } - /** - * @return bool - */ public function isResolutionMandatory(): bool { return $this->resolutionMandatory; } - /** - * @param bool $resolutionMandatory - * @return $this - */ public function setResolutionMandatory(bool $resolutionMandatory): self { $this->resolutionMandatory = $resolutionMandatory; diff --git a/src/Entity/QueryResolverOptions.php b/src/Entity/QueryResolverOptions.php index b898a53..7247673 100644 --- a/src/Entity/QueryResolverOptions.php +++ b/src/Entity/QueryResolverOptions.php @@ -44,21 +44,13 @@ public function setDenormalizationType(string $denormalizationType): self return $this; } - /** - * @param string|null $denormalizationGroup - * @return QueryResolverOptions - */ - public function setDenormalizationGroup($denormalizationGroup): self + public function setDenormalizationGroup(?string $denormalizationGroup): self { $this->denormalizationGroup = $denormalizationGroup; return $this; } - /** - * @param ValidationOptions|null $validationOptions - * @return $this - */ - public function setValidationOptions(ValidationOptions $validationOptions = null): self + public function setValidationOptions(?ValidationOptions $validationOptions = null): self { $this->validationOptions = $validationOptions; return $this; @@ -86,10 +78,7 @@ public function getDenormalizationType(): string return $this->denormalizationType; } - /** - * return string|null - */ - public function getDenormalizationGroup() + public function getDenormalizationGroup(): ?string { return $this->denormalizationGroup; } diff --git a/src/Entity/RestRequestOptions.php b/src/Entity/RestRequestOptions.php index 823b88b..92565af 100644 --- a/src/Entity/RestRequestOptions.php +++ b/src/Entity/RestRequestOptions.php @@ -84,11 +84,7 @@ public function setBodyDenormalizationType(string $bodyDenormalizationType): sel return $this; } - /** - * @param string|null $bodyDenormalizationGroup - * @return $this - */ - public function setBodyDenormalizationGroup($bodyDenormalizationGroup): self + public function setBodyDenormalizationGroup(?string $bodyDenormalizationGroup): self { $this->bodyDenormalizationGroup = $bodyDenormalizationGroup; return $this; @@ -113,30 +109,18 @@ public function setBodyOptional(bool $bodyOptional): self return $this; } - /** - * @param string|null $responseNormalizationType - * @return $this - */ - public function setResponseNormalizationType($responseNormalizationType): self + public function setResponseNormalizationType(?string $responseNormalizationType): self { $this->responseNormalizationType = $responseNormalizationType; return $this; } - /** - * @param string|null $responseNormalizationGroup - * @return $this - */ - public function setResponseNormalizationGroup($responseNormalizationGroup): self + public function setResponseNormalizationGroup(?string $responseNormalizationGroup): self { $this->responseNormalizationGroup = $responseNormalizationGroup; return $this; } - /** - * @param array $requiredPermissions array of string - * @return $this - */ public function setRequiredPermissions(array $requiredPermissions): self { $this->requiredPermissions = $requiredPermissions; @@ -176,10 +160,7 @@ public function getBodyDenormalizationType(): string return $this->bodyDenormalizationType; } - /** - * @return string|null - */ - public function getBodyDenormalizationGroup() + public function getBodyDenormalizationGroup(): ?string { return $this->bodyDenormalizationGroup; } @@ -209,18 +190,12 @@ public function isBodyOptional(): bool return $this->bodyOptional; } - /** - * @return string|null - */ - public function getResponseNormalizationType() + public function getResponseNormalizationType(): ?string { return $this->responseNormalizationType; } - /** - * @return string|null - */ - public function getResponseNormalizationGroup() + public function getResponseNormalizationGroup(): ?string { return $this->responseNormalizationGroup; } @@ -231,7 +206,7 @@ public function getRequiredPermissions(): array } /** - * @return array|PathAttributeResolverOptions[] + * @return PathAttributeResolverOptions[] */ public function getPathAttributeResolverOptionsList(): array { @@ -239,7 +214,7 @@ public function getPathAttributeResolverOptionsList(): array } /** - * @return array|QueryResolverOptions[] + * @return QueryResolverOptions[] */ public function getQueryResolverOptionsList(): array { diff --git a/src/Entity/Violation.php b/src/Entity/Violation.php index 529736c..67a9473 100644 --- a/src/Entity/Violation.php +++ b/src/Entity/Violation.php @@ -11,7 +11,7 @@ class Violation private $field; /** - * @var string + * @var string|null */ private $code; @@ -20,60 +20,36 @@ class Violation */ private $message; - /** - * @return null|string - */ - public function getField() + public function getField(): ?string { return $this->field; } - /** - * @param string $field - * - * @return $this - */ - public function setField($field) + public function setField(string $field): self { $this->field = $field; return $this; } - /** - * @return null|string - */ - public function getCode() + public function getCode(): ?string { return $this->code; } - /** - * @param string $code - * - * @return $this - */ - public function setCode($code) + public function setCode(?string $code): self { $this->code = $code; return $this; } - /** - * @return null|string - */ - public function getMessage() + public function getMessage(): ?string { return $this->message; } - /** - * @param string $message - * - * @return $this - */ - public function setMessage($message) + public function setMessage(string $message): self { $this->message = $message; diff --git a/src/Exception/ApiException.php b/src/Exception/ApiException.php index ae8d096..d8ba3a2 100644 --- a/src/Exception/ApiException.php +++ b/src/Exception/ApiException.php @@ -61,8 +61,8 @@ public function __construct( $message = null, $statusCode = null, Exception $previous = null, - $properties = null, - $data = null, + ?array $properties = null, + ?array $data = null, array $violations = [] ) { parent::__construct($message ?: '', 0, $previous); @@ -74,56 +74,34 @@ public function __construct( $this->violations = $violations; } - /** - * @return string - */ - public function getErrorCode() + public function getErrorCode(): string { return $this->errorCode; } - /** - * @return int|null - */ - public function getStatusCode() + public function getStatusCode(): ?int { return $this->statusCode; } - /** - * @param array|null $properties - * - * @return $this - */ - public function setProperties($properties) + public function setProperties(?array $properties): self { $this->properties = $properties; return $this; } - /** - * @return array|null - */ - public function getProperties() + public function getProperties(): ?array { return $this->properties; } - /** - * @param array|null $data - * - * @return $this - */ - public function setData($data) + public function setData(?array $data): self { $this->data = $data; return $this; } - /** - * @return array|null - */ - public function getData() + public function getData(): ?array { return $this->data; } @@ -131,7 +109,7 @@ public function getData() /** * @return Violation[] */ - public function getViolations() + public function getViolations(): array { return $this->violations; } @@ -141,7 +119,7 @@ public function getViolations() * * @return $this */ - public function setViolations($violations) + public function setViolations(array $violations): self { $this->violations = $violations; return $this; diff --git a/src/Listener/LocaleListener.php b/src/Listener/LocaleListener.php index 241101f..a3c2b49 100644 --- a/src/Listener/LocaleListener.php +++ b/src/Listener/LocaleListener.php @@ -42,7 +42,7 @@ public function onKernelRequest($event) } } - private function resolveFromHeaders(Request $request) + private function resolveFromHeaders(Request $request): ?string { $defaultLocale = 'default'; $preferredLanguage = $request->getPreferredLanguage(array_merge([$defaultLocale], $this->locales)); diff --git a/src/Listener/RestExceptionListener.php b/src/Listener/RestExceptionListener.php index 3d71a9b..972bdbc 100644 --- a/src/Listener/RestExceptionListener.php +++ b/src/Listener/RestExceptionListener.php @@ -45,8 +45,10 @@ public function __construct( * Ran on kernel.exception event * * Both events are typecasted as one is deprecated from 4.3, but another not available before this version + * * @param GetResponseForExceptionEvent|ExceptionEvent $event - * @throws Exception + * + * @throws Exception|Throwable */ public function onKernelException($event) { diff --git a/src/Listener/RestRequestListener.php b/src/Listener/RestRequestListener.php index 6466587..a9ee76b 100644 --- a/src/Listener/RestRequestListener.php +++ b/src/Listener/RestRequestListener.php @@ -105,7 +105,7 @@ public function onKernelController($event) * * @return RestRequestOptions|null */ - private function resolveOptionsForController(Request $request, callable $controller) + private function resolveOptionsForController(Request $request, callable $controller): ?RestRequestOptions { if ($this->requestHelper->isRestRequest($request)) { return $this->requestHelper->getOptionsFromRequest($request); @@ -174,7 +174,6 @@ private function addAttributesFromURL(Request $request, RestRequestOptions $opti * @param RestRequestOptions $options * * @throws ApiException - * @throws InvalidItemException */ private function addAttributesFromQuery(Request $request, RestRequestOptions $options) { @@ -212,7 +211,6 @@ private function convertToObject(array $query): stdClass * @param RestRequestOptions $options * * @throws ApiException - * @throws InvalidItemException */ private function addAttributesFromBody(Request $request, RestRequestOptions $options) { diff --git a/src/Listener/RestResponseListener.php b/src/Listener/RestResponseListener.php index 9aca71e..bd5239e 100644 --- a/src/Listener/RestResponseListener.php +++ b/src/Listener/RestResponseListener.php @@ -65,7 +65,7 @@ private function normalizeResult(Request $request, RestRequestOptions $options, { $includedFields = []; $fields = $request->query->get('fields'); - if ($fields !== null && is_string($fields) && $fields !== '') { + if (is_string($fields) && $fields !== '') { $includedFields = explode(',', $fields); } diff --git a/src/Normalizer/ErrorNormalizer.php b/src/Normalizer/ErrorNormalizer.php index e136820..cecaab3 100644 --- a/src/Normalizer/ErrorNormalizer.php +++ b/src/Normalizer/ErrorNormalizer.php @@ -11,20 +11,21 @@ class ErrorNormalizer implements NormalizerInterface, TypeAwareInterface { /** - * @param Error $result + * @param Error $entity * @param NormalizationContext $normalizationContext + * * @return array */ - public function normalize($result, NormalizationContext $normalizationContext) + public function normalize($entity, NormalizationContext $normalizationContext): array { $normalizationContext->markNullValuesForRemoval(); return [ - 'error' => $result->getCode(), - 'error_description' => $result->getMessage(), - 'error_uri' => $result->getUri(), - 'error_properties' => $result->getProperties(), - 'error_data' => $result->getData(), - 'errors' => $result->getViolations() !== [] ? $result->getViolations() : null, + 'error' => $entity->getCode(), + 'error_description' => $entity->getMessage(), + 'error_uri' => $entity->getUri(), + 'error_properties' => $entity->getProperties(), + 'error_data' => $entity->getData(), + 'errors' => $entity->getViolations() !== [] ? $entity->getViolations() : null, ]; } diff --git a/src/Normalizer/Pagination/PagedQueryNormalizer.php b/src/Normalizer/Pagination/PagedQueryNormalizer.php index 07b38c0..25d5724 100644 --- a/src/Normalizer/Pagination/PagedQueryNormalizer.php +++ b/src/Normalizer/Pagination/PagedQueryNormalizer.php @@ -20,12 +20,7 @@ class PagedQueryNormalizer implements NormalizerInterface, TypeAwareInterface private $defaultTotalCountStrategy; private $maximumOffset; - /** - * @param ResultProvider $resultProvider - * @param string $defaultTotalCountStrategy - * @param int|null $maximumOffset - */ - public function __construct(ResultProvider $resultProvider, string $defaultTotalCountStrategy, $maximumOffset) + public function __construct(ResultProvider $resultProvider, string $defaultTotalCountStrategy, ?int $maximumOffset) { $this->resultProvider = $resultProvider; $this->defaultTotalCountStrategy = $defaultTotalCountStrategy; @@ -33,17 +28,18 @@ public function __construct(ResultProvider $resultProvider, string $defaultTotal } /** - * @param PagedQuery $pagedQuery + * @param PagedQuery $entity * @param NormalizationContext $normalizationContext + * * @return array */ - public function normalize($pagedQuery, NormalizationContext $normalizationContext) + public function normalize($entity, NormalizationContext $normalizationContext) { - $result = $this->fetchResultByPagedQuery($pagedQuery, $normalizationContext); + $result = $this->fetchResultByPagedQuery($entity, $normalizationContext); return $normalizationContext->normalize($result, ''); } - private function fetchResultByPagedQuery(PagedQuery $pagedQuery, NormalizationContext $normalizationContext) + private function fetchResultByPagedQuery(PagedQuery $pagedQuery, NormalizationContext $normalizationContext): Result { $configuredQuery = clone $pagedQuery->getConfiguredQuery(); diff --git a/src/Normalizer/Pagination/ResultNormalizer.php b/src/Normalizer/Pagination/ResultNormalizer.php index 8e7b143..eaf6df4 100644 --- a/src/Normalizer/Pagination/ResultNormalizer.php +++ b/src/Normalizer/Pagination/ResultNormalizer.php @@ -14,19 +14,20 @@ class ResultNormalizer implements NormalizerInterface, TypeAwareInterface { /** - * @param Result $result + * @param Result $entity * @param NormalizationContext $normalizationContext + * * @return array */ - public function normalize($result, NormalizationContext $normalizationContext) + public function normalize($entity, NormalizationContext $normalizationContext): array { return [ - 'items' => $result->getItems(), - '_metadata' => $this->mapMetadataFromEntity($result), + 'items' => $entity->getItems(), + '_metadata' => $this->mapMetadataFromEntity($entity), ]; } - private function mapMetadataFromEntity(Result $result) + private function mapMetadataFromEntity(Result $result): array { $data = [ 'total' => $result->getTotalCount(), diff --git a/src/Normalizer/ViolationNormalizer.php b/src/Normalizer/ViolationNormalizer.php index 8c63be9..3dcc482 100644 --- a/src/Normalizer/ViolationNormalizer.php +++ b/src/Normalizer/ViolationNormalizer.php @@ -11,16 +11,17 @@ class ViolationNormalizer implements NormalizerInterface, TypeAwareInterface { /** - * @param Violation $result + * @param Violation $entity * @param NormalizationContext $normalizationContext + * * @return array */ - public function normalize($result, NormalizationContext $normalizationContext) + public function normalize($entity, NormalizationContext $normalizationContext): array { return [ - 'code' => $result->getCode(), - 'message' => $result->getMessage(), - 'field' => $result->getField(), + 'code' => $entity->getCode(), + 'message' => $entity->getMessage(), + 'field' => $entity->getField(), ]; } diff --git a/src/Service/Annotation/ReflectionMethodWrapper.php b/src/Service/Annotation/ReflectionMethodWrapper.php index 9e22eb2..099b7c2 100644 --- a/src/Service/Annotation/ReflectionMethodWrapper.php +++ b/src/Service/Annotation/ReflectionMethodWrapper.php @@ -50,7 +50,7 @@ public function getNonBuiltInTypeForParameter(string $name): string return version_compare(PHP_VERSION, '7.1.0') >= 0 ? $type->getName() : (string)$type; } - public function getFriendlyName() + public function getFriendlyName(): string { return sprintf( '%s::%s', diff --git a/src/Service/ResponseBuilder.php b/src/Service/ResponseBuilder.php index 4a36402..1752025 100644 --- a/src/Service/ResponseBuilder.php +++ b/src/Service/ResponseBuilder.php @@ -7,6 +7,7 @@ use Exception; use InvalidArgumentException; use Symfony\Component\HttpFoundation\Response; +use Throwable; /** * @internal @@ -18,8 +19,9 @@ class ResponseBuilder * * @param mixed $data * @param int $statusCode + * * @return Response - * @throws Exception + * @throws Exception|Throwable */ public function buildResponse($data, int $statusCode = Response::HTTP_OK): Response { @@ -35,7 +37,7 @@ public function buildEmptyResponse(): Response return new Response('', Response::HTTP_NO_CONTENT, $this->getDefaultHeaders()); } - private function getDefaultHeaders() + private function getDefaultHeaders(): array { return [ 'X-Frame-Options' => 'DENY', @@ -43,7 +45,7 @@ private function getDefaultHeaders() ]; } - private function buildJsonResponse($data, int $statusCode, array $headers) + private function buildJsonResponse($data, int $statusCode, array $headers): Response { try { $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); diff --git a/src/Service/RestRequestHelper.php b/src/Service/RestRequestHelper.php index 5a2c307..967aa09 100644 --- a/src/Service/RestRequestHelper.php +++ b/src/Service/RestRequestHelper.php @@ -37,7 +37,7 @@ public function __construct(RestRequestOptionsRegistry $restRequestOptionsRegist * * @internal */ - public function resolveRestRequestOptionsForRequest(Request $request) + public function resolveRestRequestOptionsForRequest(Request $request): ?RestRequestOptions { $serialized = $request->attributes->get(self::SERIALIZED_REST_OPTIONS_KEY); if ($serialized !== null) { @@ -58,7 +58,7 @@ public function resolveRestRequestOptionsForRequest(Request $request) * * @internal */ - public function resolveRestRequestOptionsForController(Request $request, callable $controller) + public function resolveRestRequestOptionsForController(Request $request, callable $controller): ?RestRequestOptions { $controllerIdentifier = $request->attributes->get('_controller'); $options = $controllerIdentifier !== null @@ -74,11 +74,10 @@ public function resolveRestRequestOptionsForController(Request $request, callabl if (is_object($controller[0])) { $controllerAsArray[0] = get_class($controller[0]); } - $options = $this->restRequestOptionsRegistry->getRestRequestOptionsForController( + + return $this->restRequestOptionsRegistry->getRestRequestOptionsForController( implode('::', $controllerAsArray) ); - - return $options; } return null; diff --git a/src/Service/RestRequestOptionsRegistry.php b/src/Service/RestRequestOptionsRegistry.php index d0d0e02..e5f137b 100644 --- a/src/Service/RestRequestOptionsRegistry.php +++ b/src/Service/RestRequestOptionsRegistry.php @@ -11,7 +11,7 @@ class RestRequestOptionsRegistry { /** - * @var array|RestRequestOptions[] associative array + * @var RestRequestOptions[] associative array */ private $restRequestOptionsByController; @@ -25,11 +25,7 @@ public function registerRestRequestOptions(RestRequestOptions $options, string $ $this->restRequestOptionsByController[$controller] = $options; } - /** - * @param string $controller - * @return RestRequestOptions|null - */ - public function getRestRequestOptionsForController(string $controller) + public function getRestRequestOptionsForController(string $controller): ?RestRequestOptions { return $this->restRequestOptionsByController[$controller] ?? null; } diff --git a/src/Service/Validation/CamelCaseToSnakeCaseConverter.php b/src/Service/Validation/CamelCaseToSnakeCaseConverter.php index 71262f1..5a5af34 100644 --- a/src/Service/Validation/CamelCaseToSnakeCaseConverter.php +++ b/src/Service/Validation/CamelCaseToSnakeCaseConverter.php @@ -5,7 +5,7 @@ class CamelCaseToSnakeCaseConverter implements PropertyPathConverterInterface { - public function convert($path) + public function convert(string $path): string { return ltrim( mb_strtolower( diff --git a/src/Service/Validation/EntityValidator.php b/src/Service/Validation/EntityValidator.php index 830d215..aa4c4a0 100644 --- a/src/Service/Validation/EntityValidator.php +++ b/src/Service/Validation/EntityValidator.php @@ -82,12 +82,7 @@ public function validate($entity, ValidationOptions $options) throw $exception; } - /** - * @param ConstraintViolation $violation - * - * @return null|string - */ - private function getErrorCode(ConstraintViolation $violation) + private function getErrorCode(ConstraintViolation $violation): ?string { $constraint = $violation->getConstraint(); diff --git a/src/Service/Validation/PropertyPathConverterInterface.php b/src/Service/Validation/PropertyPathConverterInterface.php index aa15c48..4e93f45 100644 --- a/src/Service/Validation/PropertyPathConverterInterface.php +++ b/src/Service/Validation/PropertyPathConverterInterface.php @@ -5,10 +5,5 @@ interface PropertyPathConverterInterface { - /** - * @param string $path - * - * @return string - */ - public function convert($path); + public function convert(string $path): string; } diff --git a/tests/Functional/Fixtures/FixtureTestBundle/DependencyInjection/PayseraFixtureTestExtension.php b/tests/Functional/Fixtures/FixtureTestBundle/DependencyInjection/PayseraFixtureTestExtension.php index f1e4612..0fd5676 100644 --- a/tests/Functional/Fixtures/FixtureTestBundle/DependencyInjection/PayseraFixtureTestExtension.php +++ b/tests/Functional/Fixtures/FixtureTestBundle/DependencyInjection/PayseraFixtureTestExtension.php @@ -7,6 +7,7 @@ use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\Kernel; /** * This is the class that loads and manages your bundle configuration. @@ -24,7 +25,8 @@ public function load(array $configs, ContainerBuilder $container) $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); - $loader->load('services.xml'); + $prefix = Kernel::MAJOR_VERSION <= 4 ? 'legacy_' : ''; + $loader->load($prefix . 'services.xml'); } } diff --git a/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_routing.xml b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_routing.xml new file mode 100644 index 0000000..60c538f --- /dev/null +++ b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_routing.xml @@ -0,0 +1,43 @@ + + + + + + + + PayseraFixtureTestBundle:Default:action1 + + + PayseraFixtureTestBundle:Default:action1b + + + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action2 + + + paysera_fixture_test.controller.default_controller:action3 + + + paysera_fixture_test.controller.default_controller:action4 + + + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action5 + + + + paysera_fixture_test.controller.default_controller:action + + + paysera_fixture_test.controller.default_controller:actionWithReturn + + + paysera_fixture_test.controller.default_controller:action + + + paysera_fixture_test.controller.default_controller:actionWithMultipleParameters + + + paysera_fixture_test.controller.default_controller:actionWithMultipleParameters + + diff --git a/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_services.xml b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_services.xml new file mode 100644 index 0000000..33b3915 --- /dev/null +++ b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/legacy_services.xml @@ -0,0 +1,102 @@ + + + + + + + + + + parameter + + + + parameter_custom + + + + key + + + + key_custom + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + extract:parameter + + + parameter + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/routing.xml b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/routing.xml index fbd3eae..705905f 100644 --- a/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/routing.xml +++ b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/routing.xml @@ -1,43 +1,51 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd"> - PayseraFixtureTestBundle:Default:action1 + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action1Action - PayseraFixtureTestBundle:Default:action1b + + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action1bAction + - Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action2 + + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action2 + - paysera_fixture_test.controller.default_controller:action3 + paysera_fixture_test.controller.default_controller::action3 - paysera_fixture_test.controller.default_controller:action4 + paysera_fixture_test.controller.default_controller::action4 - Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action5 + + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action5 + - paysera_fixture_test.controller.default_controller:action + paysera_fixture_test.controller.default_controller::action - paysera_fixture_test.controller.default_controller:actionWithReturn + paysera_fixture_test.controller.default_controller::actionWithReturn - paysera_fixture_test.controller.default_controller:action + + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action + - paysera_fixture_test.controller.default_controller:actionWithMultipleParameters + paysera_fixture_test.controller.default_controller::actionWithMultipleParameters - paysera_fixture_test.controller.default_controller:actionWithMultipleParameters + paysera_fixture_test.controller.default_controller::actionWithMultipleParameters diff --git a/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/services.xml b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/services.xml index a31e7de..48c04aa 100644 --- a/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/services.xml +++ b/tests/Functional/Fixtures/FixtureTestBundle/Resources/config/services.xml @@ -54,13 +54,13 @@ class="Paysera\Bundle\ApiBundle\Entity\RestRequestOptions"> + controller="Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Controller\DefaultController::action1b"/> - + - + diff --git a/tests/Functional/Fixtures/FixtureTestBundle/Service/CustomPropertyPathConverter.php b/tests/Functional/Fixtures/FixtureTestBundle/Service/CustomPropertyPathConverter.php index 0da04ae..f5caf79 100644 --- a/tests/Functional/Fixtures/FixtureTestBundle/Service/CustomPropertyPathConverter.php +++ b/tests/Functional/Fixtures/FixtureTestBundle/Service/CustomPropertyPathConverter.php @@ -7,7 +7,7 @@ class CustomPropertyPathConverter implements PropertyPathConverterInterface { - public function convert($path) + public function convert(string $path): string { return 'prefixed:' . $path; } diff --git a/tests/Functional/Fixtures/TestKernel.php b/tests/Functional/Fixtures/TestKernel.php index a793fb4..38d8b90 100644 --- a/tests/Functional/Fixtures/TestKernel.php +++ b/tests/Functional/Fixtures/TestKernel.php @@ -24,7 +24,7 @@ public function __construct($testCase, $commonFile = 'common.yml') $this->commonFile = $commonFile; } - public function registerBundles() + public function registerBundles(): iterable { return [ new FrameworkBundle(), diff --git a/tests/Functional/Fixtures/config/common.yml b/tests/Functional/Fixtures/config/common.yml index 846a706..5b83375 100644 --- a/tests/Functional/Fixtures/config/common.yml +++ b/tests/Functional/Fixtures/config/common.yml @@ -16,12 +16,15 @@ security: password: pass roles: ['ROLE_USER', 'ROLE_ADMIN'] firewalls: + config: + pattern: ^/(config)/ + security: false main: - anonymous: true http_basic: ~ stateless: true - encoders: - Symfony\Component\Security\Core\User\User: plaintext + password_hashers: + Symfony\Component\Security\Core\User\InMemoryUser: + algorithm: plaintext doctrine: orm: @@ -33,7 +36,7 @@ doctrine: services: logger: - class: Symfony\Component\Debug\BufferingLogger + class: Symfony\Component\ErrorHandler\BufferingLogger public: true rest_registry: alias: paysera_api.rest_request_options_registry diff --git a/tests/Functional/Fixtures/config/legacy_common.yml b/tests/Functional/Fixtures/config/legacy_common.yml new file mode 100644 index 0000000..e684ada --- /dev/null +++ b/tests/Functional/Fixtures/config/legacy_common.yml @@ -0,0 +1,46 @@ +framework: + secret: 'secret' + router: + resource: '%kernel.root_dir%/config/legacy_routing.yml' + validation: ~ + +security: + providers: + in_memory: + memory: + users: + user: + password: pass + roles: 'ROLE_USER' + admin: + password: pass + roles: ['ROLE_USER', 'ROLE_ADMIN'] + firewalls: + main: + anonymous: true + http_basic: ~ + stateless: true + encoders: + Symfony\Component\Security\Core\User\User: plaintext + +doctrine: + orm: + auto_mapping: true + dbal: + driver: pdo_sqlite + memory: true + charset: UTF8 + +services: + logger: + class: Symfony\Component\Debug\BufferingLogger + public: true + rest_registry: + alias: paysera_api.rest_request_options_registry + public: true + +paysera_api: + path_attribute_resolvers: + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Entity\PersistedEntity: + field: someField + Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\FixtureTestBundle\Entity\SimplePersistedEntity: ~ diff --git a/tests/Functional/Fixtures/config/legacy_routing.yml b/tests/Functional/Fixtures/config/legacy_routing.yml new file mode 100644 index 0000000..0df4919 --- /dev/null +++ b/tests/Functional/Fixtures/config/legacy_routing.yml @@ -0,0 +1,3 @@ +paysera_fixture_test: + resource: "@PayseraFixtureTestBundle/Resources/config/legacy_routing.xml" + prefix: / diff --git a/tests/Functional/FunctionalRestBundleTest.php b/tests/Functional/FunctionalRestBundleTest.php index 86bfe27..c5ab1d3 100644 --- a/tests/Functional/FunctionalRestBundleTest.php +++ b/tests/Functional/FunctionalRestBundleTest.php @@ -47,7 +47,7 @@ public function restRequestsConfigurationProvider() new Response('default'), $this->createRequest('GET', '/config/by-full-controller?parameter=works'), ], - 'config works by full class name when using bundle notation routing (Bundle:Controller:action)' => [ + 'config works by full class name' => [ new Response('works'), $this->createRequest('GET', '/config/by-full-controller-and-class-name?parameter=works'), ], diff --git a/tests/Functional/FunctionalTestCase.php b/tests/Functional/FunctionalTestCase.php index d11436f..e660edc 100644 --- a/tests/Functional/FunctionalTestCase.php +++ b/tests/Functional/FunctionalTestCase.php @@ -8,7 +8,8 @@ use Paysera\Bundle\ApiBundle\Tests\Functional\Fixtures\TestKernel; use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\DependencyInjection\ResettableContainerInterface; +use Symfony\Component\HttpKernel\Kernel; +use Symfony\Contracts\Service\ResetInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -28,7 +29,8 @@ abstract class FunctionalTestCase extends TestCase */ protected function setUpContainer($testCase, $commonFile = 'common.yml') { - $this->kernel = new TestKernel($testCase, $commonFile); + $prefix = Kernel::MAJOR_VERSION <= 4 ? 'legacy_' : ''; + $this->kernel = new TestKernel($testCase, $prefix . $commonFile); $this->kernel->boot(); return $this->kernel->getContainer(); } @@ -37,7 +39,7 @@ protected function tearDown(): void { $container = $this->kernel->getContainer(); $this->kernel->shutdown(); - if ($container instanceof ResettableContainerInterface) { + if ($container instanceof ResetInterface) { $container->reset(); } diff --git a/tests/Unit/Helper/HttpKernelHelper.php b/tests/Unit/Helper/HttpKernelHelper.php new file mode 100644 index 0000000..67a50b0 --- /dev/null +++ b/tests/Unit/Helper/HttpKernelHelper.php @@ -0,0 +1,19 @@ +setLocale('unchanged'); $request->headers->set('Accept-Language', $acceptLanguage); - $helper->shouldReceive('isRestRequest')->with($request)->andReturn($rest); + $helper->allows('isRestRequest')->with($request)->andReturns($rest); if (class_exists('Symfony\Component\HttpKernel\Event\RequestEvent')) { - $event = new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($kernel, $request, HttpKernelHelper::getMainRequestConstValue()); } else { - $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); + $event = new GetResponseEvent($kernel, $request, HttpKernelHelper::getMainRequestConstValue()); } $listener->onKernelRequest($event); diff --git a/tests/Unit/Listener/RestExceptionListenerTest.php b/tests/Unit/Listener/RestExceptionListenerTest.php index 1c5b20d..03f0ff9 100644 --- a/tests/Unit/Listener/RestExceptionListenerTest.php +++ b/tests/Unit/Listener/RestExceptionListenerTest.php @@ -11,6 +11,7 @@ use Paysera\Bundle\ApiBundle\Service\ErrorBuilderInterface; use Paysera\Bundle\ApiBundle\Service\ResponseBuilder; use Paysera\Bundle\ApiBundle\Service\RestRequestHelper; +use Paysera\Bundle\ApiBundle\Tests\Unit\Helper\HttpKernelHelper; use Paysera\Component\Normalization\CoreNormalizer; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; @@ -51,41 +52,41 @@ public function testOnKernelException(bool $restRequest, int $statusCode = 400, $event = new ExceptionEvent( $kernel, $request, - HttpKernelInterface::MASTER_REQUEST, + HttpKernelHelper::getMainRequestConstValue(), $exception ); } else { $event = new GetResponseForExceptionEvent( $kernel, $request, - HttpKernelInterface::MASTER_REQUEST, + HttpKernelHelper::getMainRequestConstValue(), $exception ); } - $helper->shouldReceive('isRestRequest')->with($request)->andReturn($restRequest); + $helper->allows('isRestRequest')->with($request)->andReturns($restRequest); $error = (new Error())->setCode('custom'); $response = new Response('custom error', $statusCode); $errorBuilder - ->shouldReceive('createErrorFromException') + ->allows('createErrorFromException') ->with($exception) - ->andReturn($error) + ->andReturns($error) ; $coreNormalizer - ->shouldReceive('normalize') + ->allows('normalize') ->with($error) - ->andReturn(['error' => 'custom']) + ->andReturns(['error' => 'custom']) ; $responseBuilder - ->shouldReceive('buildResponse') + ->allows('buildResponse') ->with(['error' => 'custom'], Response::HTTP_BAD_REQUEST) - ->andReturn($response) + ->andReturns($response) ; - $logger->shouldReceive('debug'); + $logger->allows('debug'); if ($logLevel !== null) { - $logger->shouldReceive('log')->once()->withSomeOfArgs($logLevel); + $logger->expects('log')->withSomeOfArgs($logLevel); } $listener->onKernelException($event); diff --git a/tests/Unit/Normalizer/PagedQueryNormalizerTest.php b/tests/Unit/Normalizer/PagedQueryNormalizerTest.php index 9cf702a..26d6c38 100644 --- a/tests/Unit/Normalizer/PagedQueryNormalizerTest.php +++ b/tests/Unit/Normalizer/PagedQueryNormalizerTest.php @@ -22,7 +22,7 @@ public function testNormalizeWithTotalCountOnly() $normalizationContext = Mockery::mock(NormalizationContext::class); $normalizationContext - ->shouldReceive('isFieldIncluded') + ->allows('isFieldIncluded') ->andReturnUsing(function (string $key) { return $key === '_metadata.total'; }) @@ -34,24 +34,22 @@ public function testNormalizeWithTotalCountOnly() $pager = Mockery::mock(Pager::class); $resultProvider - ->shouldReceive('getTotalCountForQuery') + ->expects('getTotalCountForQuery') ->withArgs(function ($givenQuery) use ($configuredQuery) { $this->assertEquals($configuredQuery, $givenQuery); return true; }) - ->once() - ->andReturn(123) + ->andReturns(123) ; $finalResult = new stdClass(); $normalizationContext - ->shouldReceive('normalize') + ->expects('normalize') ->withArgs(function (Result $result) { $this->assertEquals(123, $result->getTotalCount()); return true; }) - ->once() - ->andReturn($finalResult) + ->andReturns($finalResult) ; $normalizer = new PagedQueryNormalizer( @@ -90,13 +88,13 @@ public function testNormalize( $normalizationContext = Mockery::mock(NormalizationContext::class); $normalizationContext - ->shouldReceive('isFieldIncluded') + ->allows('isFieldIncluded') ->andReturnUsing(function (string $key) use ($included) { return in_array($key, $included, true); }) ; $normalizationContext - ->shouldReceive('isFieldExplicitlyIncluded') + ->allows('isFieldExplicitlyIncluded') ->andReturnUsing(function (string $key) use ($explicitlyIncluded) { return in_array($key, $explicitlyIncluded, true); }) @@ -108,7 +106,7 @@ public function testNormalize( $result = Mockery::mock(Result::class); $resultProvider - ->shouldReceive('getResultForQuery') + ->expects('getResultForQuery') ->withArgs(function (ConfiguredQuery $givenQuery, $givenPager) use ($expectedQuery, $pager) { $this->assertEquals($expectedQuery->isTotalCountNeeded(), $givenQuery->isTotalCountNeeded()); if ($expectedQuery->hasMaximumOffset()) { @@ -117,16 +115,14 @@ public function testNormalize( $this->assertSame($pager, $givenPager); return true; }) - ->once() - ->andReturn($result) + ->andReturns($result) ; $finalResult = new stdClass(); $normalizationContext - ->shouldReceive('normalize') + ->expects('normalize') ->with($result, '') - ->once() - ->andReturn($finalResult) + ->andReturns($finalResult) ; $normalizer = new PagedQueryNormalizer($resultProvider, $defaultStrategy, $maximumOffset); diff --git a/tests/Unit/Service/Annotation/RestRequestOptionsBuilderTest.php b/tests/Unit/Service/Annotation/RestRequestOptionsBuilderTest.php index d5b93f8..97b62df 100644 --- a/tests/Unit/Service/Annotation/RestRequestOptionsBuilderTest.php +++ b/tests/Unit/Service/Annotation/RestRequestOptionsBuilderTest.php @@ -24,14 +24,14 @@ public function testBuildOptions() $reflectionMethod = new ReflectionMethod(self::class, 'fixtureMethod'); $annotationMock1 = Mockery::mock(RestAnnotationInterface::class); - $annotationMock1->shouldReceive('isSeveralSupported')->andReturn(true); - $annotationMock1->shouldReceive('apply')->andReturnUsing(function (RestRequestOptions $options) { + $annotationMock1->allows('isSeveralSupported')->andReturns(true); + $annotationMock1->allows('apply')->andReturnUsing(function (RestRequestOptions $options) { $options->setRequiredPermissions(['modified1']); }); $annotationMock2 = Mockery::mock(RestAnnotationInterface::class); - $annotationMock2->shouldReceive('isSeveralSupported')->andReturn(true); - $annotationMock2->shouldReceive('apply')->andReturnUsing(function (RestRequestOptions $options) { + $annotationMock2->allows('isSeveralSupported')->andReturns(true); + $annotationMock2->allows('apply')->andReturnUsing(function (RestRequestOptions $options) { $options->setResponseNormalizationType('modified2'); }); @@ -41,7 +41,7 @@ public function testBuildOptions() ; $optionsValidator - ->shouldReceive('validateRestRequestOptions') + ->allows('validateRestRequestOptions') ->andReturnUsing(function (RestRequestOptions $options, string $fieldlyName) use ($expectedOptions) { $this->assertEquals($expectedOptions, $options); $this->assertEquals( diff --git a/tests/Unit/Service/RestRequestHelperTest.php b/tests/Unit/Service/RestRequestHelperTest.php index 6da258c..94539e4 100644 --- a/tests/Unit/Service/RestRequestHelperTest.php +++ b/tests/Unit/Service/RestRequestHelperTest.php @@ -74,10 +74,9 @@ public function testResolveRestRequestOptionsWithRegisteredOptionsAndCustomContr $options = new RestRequestOptions(); $registry - ->shouldReceive('getRestRequestOptionsForController') + ->expects('getRestRequestOptionsForController') ->with('my custom controller') - ->once() - ->andReturn($options) + ->andReturns($options) ; $this->assertSame($options, $helper->resolveRestRequestOptionsForController($request, function () {})); @@ -94,16 +93,14 @@ public function testResolveRestRequestOptionsWithRegisteredOptionsAndClassContro $options = new RestRequestOptions(); $registry - ->shouldReceive('getRestRequestOptionsForController') + ->expects('getRestRequestOptionsForController') ->with('my custom controller') - ->once() ->andReturnNull() ; $registry - ->shouldReceive('getRestRequestOptionsForController') + ->expects('getRestRequestOptionsForController') ->with('DateTimeImmutable::createFromFormat') - ->once() - ->andReturn($options) + ->andReturns($options) ; $this->assertSame($options, $helper->resolveRestRequestOptionsForController( diff --git a/tests/Unit/Service/RestRequestOptionsValidatorTest.php b/tests/Unit/Service/RestRequestOptionsValidatorTest.php index 0dbf320..4cfd5d1 100644 --- a/tests/Unit/Service/RestRequestOptionsValidatorTest.php +++ b/tests/Unit/Service/RestRequestOptionsValidatorTest.php @@ -1,5 +1,4 @@ shouldReceive('hasNormalizer') + ->allows('hasNormalizer') ->with('non_existing_normalizer') - ->andReturn(false) + ->andReturns(false) ; $normalizerRegistryMock - ->shouldReceive('hasNormalizer') + ->allows('hasNormalizer') ->with('existing_normalizer') - ->andReturn(true) + ->andReturns(true) ; $normalizerRegistryMock - ->shouldReceive('getDenormalizerType') + ->allows('getDenormalizerType') ->with('non_existing_denormalizer') - ->andReturn(NormalizerRegistryInterface::DENORMALIZER_TYPE_NONE) + ->andReturns(NormalizerRegistryInterface::DENORMALIZER_TYPE_NONE) ; $normalizerRegistryMock - ->shouldReceive('getDenormalizerType') + ->allows('getDenormalizerType') ->with('object_denormalizer') - ->andReturn(NormalizerRegistryInterface::DENORMALIZER_TYPE_OBJECT) + ->andReturns(NormalizerRegistryInterface::DENORMALIZER_TYPE_OBJECT) ; $normalizerRegistryMock - ->shouldReceive('getDenormalizerType') + ->allows('getDenormalizerType') ->with('mixed_type_denormalizer') - ->andReturn(NormalizerRegistryInterface::DENORMALIZER_TYPE_MIXED) + ->andReturns(NormalizerRegistryInterface::DENORMALIZER_TYPE_MIXED) ; $pathAttributeRegistryMock - ->shouldReceive('getResolverByType') + ->allows('getResolverByType') ->with('non_existing_path_attribute_resolver') ->andThrow(new InvalidArgumentException()) ; $pathAttributeRegistryMock - ->shouldReceive('getResolverByType') + ->allows('getResolverByType') ->with('existing_path_attribute_resolver') - ->andReturn(Mockery::mock(PathAttributeResolverInterface::class)) + ->andReturns(Mockery::mock(PathAttributeResolverInterface::class)) ; if ($expectException) { diff --git a/tests/Unit/Service/Validation/EntityValidatorTest.php b/tests/Unit/Service/Validation/EntityValidatorTest.php index 55ed763..06a5002 100644 --- a/tests/Unit/Service/Validation/EntityValidatorTest.php +++ b/tests/Unit/Service/Validation/EntityValidatorTest.php @@ -24,7 +24,7 @@ public function testValidateDoesNotFailWithNonObject() $validator = Mockery::mock(ValidatorInterface::class); $propertyPathConverter = Mockery::mock(PropertyPathConverterInterface::class); - $validator->shouldNotReceive('validate'); + $validator->allows('validate')->never(); $entityValidator = new EntityValidator($validator, $propertyPathConverter); $entityValidator->validate('string', new ValidationOptions()); @@ -45,17 +45,17 @@ public function testValidate($expectedException, ValidationOptions $validationOp $entity = new stdClass(); $validator - ->shouldReceive('validate') + ->allows('validate') ->with($entity, null, $groups) - ->andReturn(new ConstraintViolationList($violationList)) + ->andReturns(new ConstraintViolationList($violationList)) ; $propertyPathConverter - ->shouldReceive('convert') + ->allows('convert') ->with('pathToConvert') - ->andReturn('convertedPath') + ->andReturns('convertedPath') ; $propertyPathConverter - ->shouldReceive('convert') + ->allows('convert') ->andReturnUsing(function ($path) { return $path; }) @@ -67,6 +67,9 @@ public function testValidate($expectedException, ValidationOptions $validationOp if ($expectedException !== null) { $this->fail('Expected exception'); } + if (method_exists($this, 'expectNotToPerformAssertions')) { + $this->expectNotToPerformAssertions(); + } } catch (ApiException $exception) { $this->assertEquals($expectedException, $exception); } diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..500279c --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,7 @@ +