diff --git a/.code-quality/ecs.php b/.code-quality/ecs.php index e326d80..df1dc61 100644 --- a/.code-quality/ecs.php +++ b/.code-quality/ecs.php @@ -2,70 +2,51 @@ declare(strict_types=1); -use PhpCsFixer\Fixer\ClassNotation\ClassAttributesSeparationFixer; -use PhpCsFixer\Fixer\Import\OrderedImportsFixer; +use PhpCsFixer\Fixer\FunctionNotation\FunctionTypehintSpaceFixer; use PhpCsFixer\Fixer\Operator\NotOperatorWithSuccessorSpaceFixer; -use PhpCsFixer\Fixer\Phpdoc\NoSuperfluousPhpdocTagsFixer; +use PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocAnnotationRemoveFixer; use PhpCsFixer\Fixer\Strict\DeclareStrictTypesFixer; -use PhpCsFixer\Fixer\Strict\StrictComparisonFixer; -use PhpCsFixer\Fixer\Strict\StrictParamFixer; -use PhpCsFixer\Fixer\StringNotation\ExplicitStringVariableFixer; -use PhpCsFixer\Fixer\Whitespace\ArrayIndentationFixer; -use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; +use Rector\Naming\Rector\ClassMethod\RenameParamToMatchTypeRector; use Symplify\CodingStandard\Fixer\ArrayNotation\ArrayListItemNewlineFixer; use Symplify\CodingStandard\Fixer\ArrayNotation\ArrayOpenerAndCloserNewlineFixer; use Symplify\CodingStandard\Fixer\LineLength\DocBlockLineLengthFixer; use Symplify\CodingStandard\Fixer\LineLength\LineLengthFixer; +use Symplify\EasyCodingStandard\Config\ECSConfig; use Symplify\EasyCodingStandard\ValueObject\Option; use Symplify\EasyCodingStandard\ValueObject\Set\SetList; -return static function (ContainerConfigurator $containerConfigurator): void { - $parameters = $containerConfigurator->parameters(); - $parameters->set( - Option::PATHS, +return ECSConfig::configure() + ->withPaths([ + __DIR__ . '/../Classes', + __DIR__ . '/../Tests', + __DIR__ . '/ecs.php', + ]) + ->withSets([ + SetList::PSR_12, + SetList::COMMON, + SetList::SYMPLIFY, + SetList::CLEAN_CODE, + ]) + ->withConfiguredRule( + LineLengthFixer::class, [ - __DIR__ . '/../Classes', - __DIR__ . '/ecs.php', - ] - ); - - $containerConfigurator->import(SetList::COMMON); - $containerConfigurator->import(SetList::CLEAN_CODE); - $containerConfigurator->import(SetList::PSR_12); - $containerConfigurator->import(SetList::SYMPLIFY); - - $containerConfigurator->services() - ->set(LineLengthFixer::class) - ->call('configure', [[ LineLengthFixer::LINE_LENGTH => 140, LineLengthFixer::INLINE_SHORT_LINES => false, - ]]); - - // Skip Rules and Sniffer - $parameters->set( - Option::SKIP, - [ - // Default Skips - Symplify\CodingStandard\Fixer\LineLength\LineLengthFixer::class => [ - __DIR__ . '/ecs.php', - ], - ArrayListItemNewlineFixer::class => null, - ArrayOpenerAndCloserNewlineFixer::class => null, - ClassAttributesSeparationFixer::class => null, - OrderedImportsFixer::class => null, - NotOperatorWithSuccessorSpaceFixer::class => null, - ExplicitStringVariableFixer::class => null, - ArrayIndentationFixer::class => null, - DocBlockLineLengthFixer::class => null, - '\SlevomatCodingStandard\Sniffs\Whitespaces\DuplicateSpacesSniff.DuplicateSpaces' => null, - '\SlevomatCodingStandard\Sniffs\Namespaces\ReferenceUsedNamesOnlySniff.PartialUse' => null, - - // @todo for next upgrade - NoSuperfluousPhpdocTagsFixer::class => null, - // @todo strict php - DeclareStrictTypesFixer::class => null, - StrictComparisonFixer::class => null, - StrictParamFixer::class => null, ] - ); -}; + ) + ->withSkip([ + NotOperatorWithSuccessorSpaceFixer::class => null, + DocBlockLineLengthFixer::class => null, + ArrayListItemNewlineFixer::class => null, + ArrayOpenerAndCloserNewlineFixer::class => null, + FunctionTypehintSpaceFixer::class => [ + __DIR__ . '/../Tests/Unit/TYPO3/AdditionalResponseHeadersTest.php', + __DIR__ . '/../Classes/TYPO3/Hooks/ClearCacheMenuHook.php', + __DIR__ . '/../Classes/TYPO3/Configuration/ExtensionConfiguration.php', + ], + DeclareStrictTypesFixer::class => null, + GeneralPhpdocAnnotationRemoveFixer::class => null, + RenameParamToMatchTypeRector::class => null, + + ]) + ->withSpacing(OPTION::INDENTATION_SPACES, "\n"); diff --git a/.code-quality/ecs_old.php b/.code-quality/ecs_old.php new file mode 100644 index 0000000..cc92a28 --- /dev/null +++ b/.code-quality/ecs_old.php @@ -0,0 +1,60 @@ +withPaths([ + __DIR__ . '/../Classes', + __DIR__ . '/ecs.php', + ]) + ->withSets([ + SetList::COMMON, + SetList::CLEAN_CODE, + SetList::PSR_12, + SetList::SYMPLIFY, + ]) + ->withConfiguredRule( + LineLengthFixer::class, + [ + LineLengthFixer::LINE_LENGTH => 140, + LineLengthFixer::INLINE_SHORT_LINES => false, + ] + ) + ->withSkip([ + // Default Skips + Symplify\CodingStandard\Fixer\LineLength\LineLengthFixer::class => [ + __DIR__ . '/ecs.php', + ], + ArrayListItemNewlineFixer::class => null, + ArrayOpenerAndCloserNewlineFixer::class => null, + ClassAttributesSeparationFixer::class => null, + GeneralPhpdocAnnotationRemoveFixer::class => null, + OrderedImportsFixer::class => null, + NotOperatorWithSuccessorSpaceFixer::class => null, + ExplicitStringVariableFixer::class => null, + ArrayIndentationFixer::class => null, + + // @todo for next upgrade + NoSuperfluousPhpdocTagsFixer::class => null, + + // @todo strict php + DeclareStrictTypesFixer::class => null, + StrictComparisonFixer::class => null, + StrictParamFixer::class => null, + ]); diff --git a/.code-quality/rector.php b/.code-quality/rector.php index 2b88641..0e40027 100644 --- a/.code-quality/rector.php +++ b/.code-quality/rector.php @@ -2,142 +2,44 @@ declare(strict_types=1); -use Rector\Arguments\Rector\ClassMethod\ArgumentAdderRector; -use Rector\Arguments\Rector\FuncCall\FunctionArgumentDefaultValueReplacerRector; -use Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector; use Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector; -use Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector; -use Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector; -use Rector\CodeQualityStrict\Rector\If_\MoveOutMethodCallInsideIfConditionRector; -use Rector\CodingStyle\Rector\ClassMethod\RemoveDoubleUnderscoreInMethodNameRector; -use Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector; -use Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector; -use Rector\CodingStyle\Rector\Encapsed\WrapEncapsedVariableInCurlyBracesRector; -use Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector; -use Rector\CodingStyle\Rector\PostInc\PostIncDecToPreIncDecRector; -use Rector\CodingStyle\Rector\Property\AddFalseDefaultToBoolPropertyRector; -use Rector\Core\Configuration\Option; -use Rector\DeadCode\Rector\Cast\RecastingRemovalRector; -use Rector\DeadCode\Rector\ClassMethod\RemoveDelegatingParentCallRector; -use Rector\DeadCode\Rector\If_\RemoveDeadInstanceOfRector; +use Rector\Config\RectorConfig; use Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector; -use Rector\Defluent\Rector\Return_\ReturnFluentChainMethodCallToNormalMethodCallRector; use Rector\EarlyReturn\Rector\If_\ChangeAndIfToEarlyReturnRector; -use Rector\EarlyReturn\Rector\If_\ChangeOrIfReturnToEarlyReturnRector; -use Rector\EarlyReturn\Rector\Return_\ReturnBinaryAndToEarlyReturnRector; -use Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector; -use Rector\Naming\Rector\Foreach_\RenameForeachValueVariableToMatchMethodCallReturnTypeRector; -use Rector\Naming\Rector\Property\MakeBoolPropertyRespectIsHasWasMethodNamingRector; -use Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector; -use Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector; -use Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector; -use Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector; +use Rector\PHPUnit\CodeQuality\Rector\Class_\YieldDataProviderRector; +use Rector\Set\ValueObject\SetList; use Rector\PHPUnit\Set\PHPUnitSetList; -use Rector\Privatization\Rector\Class_\ChangeReadOnlyVariableWithDefaultValueToConstantRector; use Rector\Privatization\Rector\Class_\FinalizeClassesWithoutChildrenRector; -use Rector\Privatization\Rector\Class_\RepeatedLiteralToClassConstantRector; -use Rector\Privatization\Rector\Property\PrivatizeLocalPropertyToPrivatePropertyRector; -use Rector\Set\ValueObject\SetList; -use Rector\TypeDeclaration\Rector\ClassMethod\AddArrayParamDocTypeRector; -use Rector\TypeDeclaration\Rector\ClassMethod\AddArrayReturnDocTypeRector; -use Rector\TypeDeclaration\Rector\FunctionLike\ParamTypeDeclarationRector; -use Rector\TypeDeclaration\Rector\FunctionLike\ReturnTypeDeclarationRector; -use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; - -return static function (ContainerConfigurator $containerConfigurator): void { - - $containerConfigurator->import(SetList::CODE_QUALITY); - $containerConfigurator->import(SetList::CODE_QUALITY_STRICT); - $containerConfigurator->import(SetList::CODING_STYLE); - $containerConfigurator->import(SetList::DEAD_CODE); - $containerConfigurator->import(SetList::EARLY_RETURN); - $containerConfigurator->import(SetList::PRIVATIZATION); - $containerConfigurator->import(SetList::TYPE_DECLARATION); - $containerConfigurator->import(SetList::PSR_4); - $containerConfigurator->import(SetList::MYSQL_TO_MYSQLI); - $containerConfigurator->import(SetList::TYPE_DECLARATION_STRICT); - $containerConfigurator->import(SetList::UNWRAP_COMPAT); - - $containerConfigurator->import(SetList::PHP_72); - $containerConfigurator->import(SetList::PHP_73); - $containerConfigurator->import(SetList::PHP_74); - $containerConfigurator->import(SetList::PHP_80); - - $containerConfigurator->import(PHPUnitSetList::PHPUNIT_CODE_QUALITY); - - $parameters = $containerConfigurator->parameters(); - $parameters->set( - Option::PATHS, - [ - __DIR__ . '/../Classes', - __DIR__ . '/rector.php', - ] - ); - - $parameters->set(Option::AUTO_IMPORT_NAMES, false); - $parameters->set(Option::AUTOLOAD_PATHS, [__DIR__ . '/../Classes']); - $parameters->set( - Option::SKIP, - [ - RecastingRemovalRector::class, - ConsistentPregDelimiterRector::class, - PostIncDecToPreIncDecRector::class, - FinalizeClassesWithoutChildrenRector::class, - ChangeOrIfReturnToEarlyReturnRector::class, - ChangeAndIfToEarlyReturnRector::class, - ReturnBinaryAndToEarlyReturnRector::class, - MakeBoolPropertyRespectIsHasWasMethodNamingRector::class, - MoveOutMethodCallInsideIfConditionRector::class, - ReturnArrayClassMethodToYieldRector::class, - AddArrayParamDocTypeRector::class, - AddArrayReturnDocTypeRector::class, - ReturnFluentChainMethodCallToNormalMethodCallRector::class, - IssetOnPropertyObjectToPropertyExistsRector::class, - FlipTypeControlToUseExclusiveTypeRector::class, - RepeatedLiteralToClassConstantRector::class, - RenameVariableToMatchNewTypeRector::class, - AddLiteralSeparatorToNumberRector::class, - RenameForeachValueVariableToMatchMethodCallReturnTypeRector::class, - ChangeReadOnlyVariableWithDefaultValueToConstantRector::class, - PrivatizeLocalPropertyToPrivatePropertyRector::class, - RemoveDelegatingParentCallRector::class, - ReturnTypeDeclarationRector::class => [ - __DIR__ . '/../Classes/System/Restler/Builder.php', - ], - SimplifyIfReturnBoolRector::class => [ - __DIR__ . '/../Classes/System/TYPO3/Cache.php', - ], - RemoveDeadInstanceOfRector::class => [ - __DIR__ . '/../Classes/System/Restler/Builder.php', - __DIR__ . '/../Classes/System/RestApi/RestApiRequest.php' - ], - ClosureToArrowFunctionRector::class => [ - __DIR__ . '/../Classes/System/Restler/Builder.php' - ], - FunctionArgumentDefaultValueReplacerRector::class => [ - __DIR__ . '/../Classes/System/RestApi/RestApiRequest.php' - ], - JsonThrowOnErrorRector::class => [ - __DIR__ . '/../Classes/System/RestApi/RestApiRequest.php', - __DIR__ . '/../Classes/System/RestApi/RestApiJsonFormat.php', - __DIR__ . '/../Classes/System/Restler/Format/HalJsonFormat.php' - ], - RemoveDoubleUnderscoreInMethodNameRector::class => [ - __DIR__ . '/../Classes/Controller/FeUserAuthenticationController.php', - __DIR__ . '/../Classes/Controller/ExplorerAuthenticationController.php', - __DIR__ . '/../Classes/Controller/BeUserAuthenticationController.php' - ], - // We can't fix this, because our code must support PHP v7.x - Rector\Php80\Rector\Catch_\RemoveUnusedVariableInCatchRector::class => [ - __DIR__ . '/../Classes/System/Restler/RestlerExtended.php', - ], - // We can't fix this, because our code must support PHP v7.x - Rector\CodingStyle\Rector\Catch_\CatchExceptionNameMatchingTypeRector::class => [ - __DIR__ . '/../Classes/System/Restler/RestlerExtended.php', - ], - ] - ); - - $services = $containerConfigurator->services(); - $services->set(RemoveUnusedPrivatePropertyRector::class); -}; +use Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector; +use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromStrictSetUpRector; + +return RectorConfig::configure() + ->withPaths([ + __DIR__ . '/../Classes', + __DIR__ . '/../Tests', + __DIR__ . '/rector.php', + ]) + ->withPhpSets( + true + ) + ->withSets([ + SetList::CODE_QUALITY, + SetList::STRICT_BOOLEANS, + SetList::CODING_STYLE, + SetList::DEAD_CODE, + SetList::EARLY_RETURN, + SetList::PRIVATIZATION, + SetList::TYPE_DECLARATION, + SetList::INSTANCEOF, + PHPUnitSetList::PHPUNIT_CODE_QUALITY + ]) + ->withSkip([ + FinalizeClassesWithoutChildrenRector::class, + ChangeAndIfToEarlyReturnRector::class, + TypedPropertyFromStrictSetUpRector::class, + AddMethodCallBasedStrictParamTypeRector::class, + FlipTypeControlToUseExclusiveTypeRector::class, + YieldDataProviderRector::class, + ]) + ->withAutoloadPaths([__DIR__ . '/../Classes']) + ->registerService(RemoveUnusedPrivatePropertyRector::class); diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index bd00665..19510c2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -63,16 +63,16 @@ jobs: run: find . -name \*.php ! -path "./.Build/*" ! -path "./scripts/*" ! -path "./typo3_src/*" | parallel --gnu php -d display_errors=stderr -l {} > /dev/null \; - name: Unit Tests without coverage - if: matrix.typo3 != '^11.5' || matrix.php != '7.4' + if: matrix.typo3 != '^11.5' || matrix.php != '8.3' run: | - export "UNIT_XML"=.Build/vendor/nimut/testing-framework/res/Configuration/UnitTests.xml + export "UNIT_XML"=..Build/vendor/typo3/testing-framework/Resources/Core/Build/UnitTests.xml .Build/bin/phpunit --colors -c $UNIT_XML Tests/Unit - name: Unit Tests with coverage - if: matrix.typo3 == '^11.5' && matrix.php == '7.4' + if: matrix.typo3 == '^11.5' && matrix.php == '8.3' run: | - export "UNIT_XML"=.Build/vendor/nimut/testing-framework/res/Configuration/UnitTests.xml - .Build/bin/phpunit --whitelist Classes --coverage-clover=unittest-coverage.clover --colors -c $UNIT_XML Tests/Unit/ + export "UNIT_XML"=.Build/vendor/typo3/testing-framework/Resources/Core/Build/UnitTests.xml + .Build/bin/phpunit --coverage-filter Classes --coverage-clover=unittest-coverage.clover --colors -c $UNIT_XML Tests/Unit/ - name: Upload coverage results to Scrutinizer if: matrix.typo3 == '^11.5' && matrix.php == '7.4' diff --git a/.gitignore b/.gitignore index 4500185..f52000a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ # Build folder .Build +Build/testing-docker/.env # PHP Dependencies + Dev /composer.lock diff --git a/Classes/Configuration/ExtensionConfiguration.php b/Classes/Configuration/ExtensionConfiguration.php index 1722370..2c6ca1e 100644 --- a/Classes/Configuration/ExtensionConfiguration.php +++ b/Classes/Configuration/ExtensionConfiguration.php @@ -30,9 +30,6 @@ use TYPO3\CMS\Core\SingletonInterface; use TYPO3\CMS\Core\Utility\GeneralUtility; -/** - * @package Restler - */ class ExtensionConfiguration implements SingletonInterface { /** diff --git a/Classes/Controller/ExplorerAuthenticationController.php b/Classes/Controller/ExplorerAuthenticationController.php index 98ac622..c7aa1f7 100644 --- a/Classes/Controller/ExplorerAuthenticationController.php +++ b/Classes/Controller/ExplorerAuthenticationController.php @@ -62,11 +62,8 @@ public function __construct() // phpcs:ignore public function __isAllowed() { - if ($this->restler->apiMethodInfo->className !== Explorer::class) { - // this controller is not responsible for the authentication - return false; - } - return true; + // this controller is not responsible for the authentication + return $this->restler->apiMethodInfo->className === Explorer::class; } /** diff --git a/Classes/Controller/FeUserAuthenticationController.php b/Classes/Controller/FeUserAuthenticationController.php index e82e541..61d1f7a 100644 --- a/Classes/Controller/FeUserAuthenticationController.php +++ b/Classes/Controller/FeUserAuthenticationController.php @@ -59,6 +59,7 @@ class FeUserAuthenticationController implements iAuthenticate * @see \Aoe\RestlerExamples\Controller\ContentController::getContentElementByUidForLoggedInFeUser */ public string $argumentNameOfPageId = ''; + /** * This property defines (when it's set), that this controller should check authentication * This property will be automatically set by restler, when in the API-class/controller this @@ -128,7 +129,7 @@ public function __getWWWAuthenticateString(): string */ private function determinePageId(): string { - if (!empty($this->argumentNameOfPageId)) { + if ($this->argumentNameOfPageId !== '' && $this->argumentNameOfPageId !== '0') { return $this->argumentNameOfPageId; } diff --git a/Classes/System/Dispatcher.php b/Classes/System/Dispatcher.php index 70296fa..4bd2fb0 100644 --- a/Classes/System/Dispatcher.php +++ b/Classes/System/Dispatcher.php @@ -26,8 +26,8 @@ * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ -use Aoe\Restler\System\TYPO3\Loader; use Aoe\Restler\System\Restler\Routes; +use Aoe\Restler\System\TYPO3\Loader; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; diff --git a/Classes/System/RestApi/RestApiClient.php b/Classes/System/RestApi/RestApiClient.php index 0d0511a..c8d0db4 100644 --- a/Classes/System/RestApi/RestApiClient.php +++ b/Classes/System/RestApi/RestApiClient.php @@ -30,14 +30,11 @@ use Aoe\Restler\System\Restler\Builder as RestlerBuilder; use Aoe\Restler\System\TYPO3\Cache; use Luracast\Restler\RestException; +use stdClass; +use TYPO3\CMS\Core\Http\ServerRequest; use TYPO3\CMS\Core\SingletonInterface; use TYPO3\CMS\Core\Utility\GeneralUtility; -use TYPO3\CMS\Core\Http\ServerRequest; -use stdClass; -/** - * @package Restler - */ class RestApiClient implements SingletonInterface { private Cache $typo3Cache; @@ -74,7 +71,6 @@ public function isProductionContextSet(): bool * @param array|stdClass $getData * @param array|stdClass $postData * @return mixed can be a primitive or array or object - * @throws RestApiRequestException */ public function executeRequest(string $requestMethod, string $requestUri, $getData = null, $postData = null) { @@ -109,6 +105,7 @@ protected function createRequestException(RestException $e, string $requestMetho if (!$this->isProductionContextSet()) { $errorMessage .= ' (message: ' . $e->getMessage() . ', details: ' . json_encode($e->getDetails(), JSON_THROW_ON_ERROR) . ')'; } + return new RestApiRequestException( $errorMessage, RestApiRequestException::EXCEPTION_CODE_REQUEST_COULD_NOT_PROCESSED, diff --git a/Classes/System/RestApi/RestApiJsonFormat.php b/Classes/System/RestApi/RestApiJsonFormat.php index fe4c4d0..aab8538 100644 --- a/Classes/System/RestApi/RestApiJsonFormat.php +++ b/Classes/System/RestApi/RestApiJsonFormat.php @@ -26,18 +26,14 @@ * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ -use Luracast\Restler\RestException; use Luracast\Restler\Format\JsonFormat; +use Luracast\Restler\RestException; use TYPO3\CMS\Core\SingletonInterface; -/** - * @package Restler - */ class RestApiJsonFormat extends JsonFormat implements SingletonInterface { /** * @param string $data - * @throws RestException */ public function decode($data) { diff --git a/Classes/System/RestApi/RestApiRequest.php b/Classes/System/RestApi/RestApiRequest.php index 95aab96..bf39437 100644 --- a/Classes/System/RestApi/RestApiRequest.php +++ b/Classes/System/RestApi/RestApiRequest.php @@ -27,13 +27,13 @@ ***************************************************************/ use Aoe\Restler\System\TYPO3\Cache; -use Luracast\Restler\Restler; -use Luracast\Restler\RestException; +use Exception; use Luracast\Restler\Defaults; use Luracast\Restler\Format\JsonFormat; -use TYPO3\CMS\Core\Utility\GeneralUtility; -use Exception; +use Luracast\Restler\RestException; +use Luracast\Restler\Restler; use stdClass; +use TYPO3\CMS\Core\Utility\GeneralUtility; /** * This class represents a single REST-API-request, which can be called from PHP. @@ -55,6 +55,7 @@ class RestApiRequest extends Restler * will be called recursive, so we MUST store the 'really original' data */ private static array $originalGetVars; + /** * store data from $_POST in this property * @@ -63,6 +64,7 @@ class RestApiRequest extends Restler * will be called recursive, so we MUST store the 'really original' data */ private static array $originalPostVars; + /** * store data from $_SERVER in this property * @@ -73,11 +75,14 @@ class RestApiRequest extends Restler private static array $originalServerSettings; private array $restApiGetData; + private array $restApiPostData; + /** * This property defines the request-uri (without GET-params, e.g. '/api/products/320'), which should be called */ private string $restApiRequestUri; + /** * This property defines the request-method (e.g. 'GET', 'POST', 'PUT' or 'DELETE'), which should be used while calling the rest-api */ @@ -87,8 +92,6 @@ class RestApiRequest extends Restler private Cache $typo3Cache; - - /***************************************************************************************************************************/ /***************************************************************************************************************************/ /* Block of methods, which MUST be overridden from parent-class (otherwise this class can not work) *************************/ @@ -111,8 +114,6 @@ public function __destruct() { } - - /***************************************************************************************************************************/ /***************************************************************************************************************************/ /* Block of methods, which does NOT override logic from parent-class *******************************************************/ @@ -122,7 +123,6 @@ public function __destruct() * @param array|stdClass $getData * @param array|stdClass $postData * @return mixed can be a primitive or array or object - * @throws RestException */ public function executeRestApiRequest(string $requestMethod, string $requestUri, $getData = null, $postData = null) { @@ -170,6 +170,7 @@ public function getRequestData($includeQueryParameters = true): array if ($includeQueryParameters) { return $requestData + $this->restApiGetData; } + return $requestData; } @@ -191,6 +192,7 @@ public function handle() if (Defaults::$useVendorMIMEVersioning) { $this->responseFormat = $this->negotiateResponseFormat(); } + $this->route(); $this->negotiate(); $this->preAuthFilter(); @@ -207,6 +209,7 @@ public function handle() return $this->getRestApiJsonFormat() ->decode($this->responseData); } + return $this->responseFormat->decode($this->responseData); } @@ -241,16 +244,17 @@ protected function postCall() /** * @param array|stdClass $data * @return array - * @throws RestException */ private function convertDataToArray($data) { if (!$data) { return []; } + if (is_array($data)) { return $data; } + if ($data instanceof stdClass) { return json_decode(json_encode($data), true); // convert stdClass to array } @@ -258,7 +262,6 @@ private function convertDataToArray($data) /** * @return mixed - * @throws RestException */ private function handleRequestByTypo3Cache() { @@ -273,6 +276,7 @@ private function handleRequestByTypo3Cache() return $this->getRestApiJsonFormat() ->decode($this->responseData); } + return $this->responseFormat->decode($this->responseData); } @@ -280,7 +284,7 @@ private function handleRequestByTypo3Cache() * Override (the stored) data of $_GET, $_POST and $_SERVER (which are used in several restler-PHP-classes) and the original * REST-API-Request-object, because this data/object 'defines' the REST-API-request, which we want to call */ - private function overrideOriginalRestApiRequest() + private function overrideOriginalRestApiRequest(): void { $_GET = $this->restApiGetData; $_POST = $this->restApiPostData; @@ -293,9 +297,11 @@ private function overrideOriginalRestApiRequest() if (array_key_exists('CONTENT_TYPE', $_SERVER)) { unset($_SERVER['CONTENT_TYPE']); } + if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) { unset($_SERVER['HTTP_CONTENT_TYPE']); } + if (array_key_exists('CONTENT_LENGTH', $_SERVER)) { unset($_SERVER['CONTENT_LENGTH']); } @@ -316,7 +322,7 @@ private function overrideOriginalRestApiRequest() /** * Restore (the overridden) data of $_GET, $_POST and $_SERVER and the original REST-API-request-object */ - private function restoreOriginalRestApiRequest() + private function restoreOriginalRestApiRequest(): void { $_GET = self::$originalGetVars; $_POST = self::$originalPostVars; @@ -328,7 +334,7 @@ private function restoreOriginalRestApiRequest() /** * Store (the original) data of $_GET, $_POST and $_SERVER and the original REST-API-request-object */ - private function storeOriginalRestApiRequest() + private function storeOriginalRestApiRequest(): void { if (!isset(self::$originalServerSettings)) { self::$originalGetVars = $_GET; diff --git a/Classes/System/RestApi/RestApiRequestScope.php b/Classes/System/RestApi/RestApiRequestScope.php index dc346de..5849cde 100644 --- a/Classes/System/RestApi/RestApiRequestScope.php +++ b/Classes/System/RestApi/RestApiRequestScope.php @@ -40,6 +40,7 @@ class RestApiRequestScope extends Scope implements SingletonInterface * @var Scope */ private $originalRestApiRequest; + /** * This array contains all instanciated REST-API-authentication-objects, which * where already initialized before we call the REST-API-request via PHP @@ -51,16 +52,13 @@ class RestApiRequestScope extends Scope implements SingletonInterface */ public function getOriginalRestApiRequest() { - if (isset($this->originalRestApiRequest)) { - return $this->originalRestApiRequest; - } - return static::get('Restler'); + return $this->originalRestApiRequest ?? static::get('Restler'); } /** * Override (the stored) restler-object, because this restler-object 'defines' the REST-API-request, which we want to call */ - public function overrideOriginalRestApiRequest(RestApiRequest $restApiRequest) + public function overrideOriginalRestApiRequest(RestApiRequest $restApiRequest): void { static::set('Restler', $restApiRequest); } @@ -73,7 +71,7 @@ public function overrideOriginalRestApiRequest(RestApiRequest $restApiRequest) * @class [authentication-class] {@[property-of-authentication-class] [property-value]} * @class Aoe\MyRestApiExtension\Controller\MyAuthenticationController {@checkAuthentication true} */ - public function removeRestApiAuthenticationObjects() + public function removeRestApiAuthenticationObjects(): void { foreach ($this->getOriginalRestApiRequest()->_authClasses as $className) { if (array_key_exists($className, static::$instances)) { @@ -85,7 +83,7 @@ public function removeRestApiAuthenticationObjects() /** * Restore (the overridden) restler-object */ - public function restoreOriginalRestApiRequest() + public function restoreOriginalRestApiRequest(): void { static::set('Restler', $this->originalRestApiRequest); } @@ -94,7 +92,7 @@ public function restoreOriginalRestApiRequest() * Restore all initialized REST-API-authentication-objects, which * were already initialized before we call the REST-API-request via PHP */ - public function restoreOriginalRestApiAuthenticationObjects() + public function restoreOriginalRestApiAuthenticationObjects(): void { $this->removeRestApiAuthenticationObjects(); @@ -108,18 +106,19 @@ public function restoreOriginalRestApiAuthenticationObjects() * * @param Restler $originalRestApiRequest optional, default is null (normally, the object already exists in the 'Scope-Repository') */ - public function storeOriginalRestApiRequest(Restler $originalRestApiRequest = null) + public function storeOriginalRestApiRequest(Restler $originalRestApiRequest = null): void { if ($originalRestApiRequest instanceof Restler) { static::set('Restler', $originalRestApiRequest); } + $this->originalRestApiRequest = static::get('Restler'); } /** * store all REST-API-authentication-objects, which where already initialized before we call the REST-API-request via PHP */ - public function storeOriginalRestApiAuthenticationObjects() + public function storeOriginalRestApiAuthenticationObjects(): void { foreach ($this->getOriginalRestApiRequest()->_authClasses as $className) { if (array_key_exists($className, static::$instances)) { diff --git a/Classes/System/Restler/AbstractExceptionHandler.php b/Classes/System/Restler/AbstractExceptionHandler.php index 4c880de..632b346 100644 --- a/Classes/System/Restler/AbstractExceptionHandler.php +++ b/Classes/System/Restler/AbstractExceptionHandler.php @@ -34,8 +34,6 @@ /** * This abstract class can be used to call ONE central method, * which handles ALL exceptions (the current HTTP-Status-Code doesn't matter)! - * - * @package Restler */ abstract class AbstractExceptionHandler { @@ -46,7 +44,6 @@ public function __construct(ExtensionConfiguration $extensionConfiguration) $this->extensionConfiguration = $extensionConfiguration; } - /** * handle HTTP-Status-Codes of type 1xx */ @@ -54,16 +51,17 @@ public function handle100(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle101(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle102(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } - /** * handle HTTP-Status-Codes of type 2xx */ @@ -71,44 +69,52 @@ public function handle200(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle201(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle202(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle203(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle204(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle205(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle206(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle207(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle208(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle226(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } - /** * handle HTTP-Status-Codes of type 3xx */ @@ -116,40 +122,47 @@ public function handle300(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle301(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle302(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle303(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle304(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle305(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle306(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle307(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle308(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } - /** * handle HTTP-Status-Codes of type 4xx */ @@ -157,130 +170,162 @@ public function handle400(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle401(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle402(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle403(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle404(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle405(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle406(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle407(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle408(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle409(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle410(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle411(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle412(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle413(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle414(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle415(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle416(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle417(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle418(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle420(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle421(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle422(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle423(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle424(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle425(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle426(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle428(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle429(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle430(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle431(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle444(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle449(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle451(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); @@ -293,48 +338,57 @@ public function handle500(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle501(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle502(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle503(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle504(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle505(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle506(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle507(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle508(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle509(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle510(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } - /** * handle HTTP-Status-Codes of type 9xx */ @@ -342,34 +396,42 @@ public function handle900(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle901(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle902(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle903(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle904(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle905(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle906(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle907(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); } + public function handle950(): bool { return $this->handleException($this->getRestlerException(func_get_args()), $this->getRestler()); @@ -400,6 +462,7 @@ protected function getRestlerException(array $exceptionHandlerArgs = []): RestEx if ($exceptionHandlerArgs !== [] && $exceptionHandlerArgs[0] instanceof RestException) { return $exceptionHandlerArgs[0]; } + return $this->getRestler() ->exception; } diff --git a/Classes/System/Restler/Builder.php b/Classes/System/Restler/Builder.php index deadb65..b66634a 100644 --- a/Classes/System/Restler/Builder.php +++ b/Classes/System/Restler/Builder.php @@ -35,14 +35,10 @@ use Psr\Http\Message\ServerRequestInterface; use TYPO3\CMS\Core\Cache\Backend\SimpleFileBackend; use TYPO3\CMS\Core\Cache\CacheManager; -use TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException; use TYPO3\CMS\Core\SingletonInterface; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; -/** - * @package Restler - */ class Builder implements SingletonInterface { private ExtensionConfiguration $extensionConfiguration; @@ -89,14 +85,14 @@ protected function createRestlerObject(ServerRequestInterface $request = null): * - add authentication-classes * - configure/set properties of several classes inside the restler-framework * - configure overwriting of several classes inside the restler-framework - * - * @throws InvalidArgumentException */ - private function configureRestler(RestlerExtended $restler) + private function configureRestler(RestlerExtended $restler): void { $restlerConfigurationClasses = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['restler']['restlerConfigurationClasses']; - if (!is_array($restlerConfigurationClasses) || $restlerConfigurationClasses === []) { + if (isset($GLOBALS['TYPO3_Restler']['restlerConfigurationClasses']) && is_array( + $GLOBALS['TYPO3_Restler']['restlerConfigurationClasses'] + )) { $message = 'No restler-configuration-class found (at least one restler-configuration-class is required)! '; $message .= 'The configuration-class must be registered in ext_localconf.php of your TYPO3-extension like this: '; $message .= '$GLOBALS[\'TYPO3_CONF_VARS\'][\'SC_OPTIONS\'][\'restler\'][\'restlerConfigurationClasses\'][] = @@ -106,7 +102,9 @@ private function configureRestler(RestlerExtended $restler) } // append configuration classes from external GLOBAL registration - if (isset($GLOBALS['TYPO3_Restler']['restlerConfigurationClasses']) && is_array($GLOBALS['TYPO3_Restler']['restlerConfigurationClasses'])) { + if (isset($GLOBALS['TYPO3_Restler']['restlerConfigurationClasses']) && is_array( + $GLOBALS['TYPO3_Restler']['restlerConfigurationClasses'] + )) { $externalRestlerConfigurationClasses = array_unique($GLOBALS['TYPO3_Restler']['restlerConfigurationClasses']); $restlerConfigurationClasses = array_merge( $restlerConfigurationClasses, @@ -131,7 +129,7 @@ private function configureRestler(RestlerExtended $restler) /** * Add API-Controller-Classes that are registered by global array */ - private function addApiClassesByGlobalArray(RestlerExtended $restler) + private function addApiClassesByGlobalArray(RestlerExtended $restler): void { if (array_key_exists('TYPO3_Restler', $GLOBALS) && is_array($GLOBALS['TYPO3_Restler']) && @@ -149,10 +147,10 @@ private function addApiClassesByGlobalArray(RestlerExtended $restler) /** * use auto-loading for PHP-classes of restler-framework and Extbase/TYPO3 (use dependency-injection of Extbase) */ - private function setAutoLoading() + private function setAutoLoading(): void { // set auto-loading for Extbase/TYPO3-classes - Scope::$resolver = function ($className) { + Scope::$resolver = static function ($className) { try { return GeneralUtility::makeInstance($className); } catch (Error $error) { @@ -178,7 +176,7 @@ private function setAutoLoading() /** * configure cache-directory (where restler can write cache-files) */ - private function setCacheDirectory() + private function setCacheDirectory(): void { Defaults::$cacheDirectory = $this->getCache()->getCacheDirectory(); } @@ -186,7 +184,7 @@ private function setCacheDirectory() /** * fix server-port (if not correct set) */ - private function setServerConfiguration() + private function setServerConfiguration(): void { if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' && $_SERVER['SERVER_PORT'] === '80') { // Fix port for HTTPS @@ -197,7 +195,6 @@ private function setServerConfiguration() /** * @return SimpleFileBackend - * @throws NoSuchCacheException */ private function getCache() { diff --git a/Classes/System/Restler/Configuration.php b/Classes/System/Restler/Configuration.php index 795ec20..b5b422d 100644 --- a/Classes/System/Restler/Configuration.php +++ b/Classes/System/Restler/Configuration.php @@ -38,8 +38,6 @@ * - add API- and authentication-class, when online-documentation is enabled * (this can be configured via extension-manager) * - add authentication-class, which can be used to check, if FE-user is logged in - * - * @package Restler */ class Configuration implements ConfigurationInterface { diff --git a/Classes/System/Restler/ConfigurationInterface.php b/Classes/System/Restler/ConfigurationInterface.php index 9547817..ce9abdf 100644 --- a/Classes/System/Restler/ConfigurationInterface.php +++ b/Classes/System/Restler/ConfigurationInterface.php @@ -29,9 +29,6 @@ use Luracast\Restler\Restler; use TYPO3\CMS\Core\SingletonInterface; -/** - * @package Restler - */ interface ConfigurationInterface extends SingletonInterface { /** diff --git a/Classes/System/Restler/Format/HalJsonFormat.php b/Classes/System/Restler/Format/HalJsonFormat.php index caed2fe..36f2418 100644 --- a/Classes/System/Restler/Format/HalJsonFormat.php +++ b/Classes/System/Restler/Format/HalJsonFormat.php @@ -9,10 +9,7 @@ /** * Javascript Object Notation Format * - * @category Framework - * @package Restler * @subpackage format - * @author R.Arul Kumaran * @copyright 2010 Luracast * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link http://luracast.com/products/restler/ @@ -67,9 +64,11 @@ public function encode($data, $humanReadable = false) if (self::$prettyPrint !== null) { $humanReadable = self::$prettyPrint; } + if (self::$unEscapedSlashes === null) { self::$unEscapedSlashes = $humanReadable; } + if (self::$unEscapedUnicode === null) { self::$unEscapedUnicode = $this->charset == 'utf-8'; } @@ -87,7 +86,7 @@ public function encode($data, $humanReadable = false) $options |= JSON_UNESCAPED_SLASHES; } - if (self::$bigIntAsString) { + if (self::$bigIntAsString === true) { $options |= JSON_BIGINT_AS_STRING; } @@ -95,7 +94,7 @@ public function encode($data, $humanReadable = false) $options |= JSON_UNESCAPED_UNICODE; } - if (self::$numbersAsNumbers) { + if (self::$numbersAsNumbers === true) { $options |= JSON_NUMERIC_CHECK; } @@ -115,10 +114,11 @@ public function encode($data, $humanReadable = false) if (self::$unEscapedUnicode) { $result = preg_replace_callback( '/\\\u(\w\w\w\w)/', - function ($matches) { + static function (array $matches) { if (function_exists('mb_convert_encoding')) { return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UTF-16BE'); } + return iconv('UTF-16BE', 'UTF-8', pack('H*', $matches[1])); }, $result @@ -126,7 +126,7 @@ function ($matches) { } if (self::$unEscapedSlashes) { - $result = str_replace('\/', '/', $result); + return str_replace('\/', '/', $result); } return $result; @@ -139,7 +139,7 @@ public function decode($data): ?array } $options = 0; - if (self::$bigIntAsString) { + if (self::$bigIntAsString === true) { if ((PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 4) // PHP >= 5.4 || PHP_MAJOR_VERSION > 5 // PHP >= 6.0 ) { @@ -169,8 +169,6 @@ public function decode($data): ?array /** * Throws an exception if an error occurred during the last JSON encoding/decoding - * - * @throws \RuntimeException */ protected function handleJsonError() { @@ -218,7 +216,7 @@ private function formatJson(string $json): string $indentLevel = 0; $inString = false; $len = strlen($json); - for ($c = 0; $c < $len; $c++) { + for ($c = 0; $c < $len; ++$c) { $char = $json[$c]; switch ($char) { case '{': @@ -226,20 +224,22 @@ private function formatJson(string $json): string if (!$inString) { $newJson .= $char . "\n" . str_repeat($tab, $indentLevel + 1); - $indentLevel++; + ++$indentLevel; } else { $newJson .= $char; } + break; case '}': case ']': if (!$inString) { - $indentLevel--; + --$indentLevel; $newJson .= "\n" . str_repeat($tab, $indentLevel) . $char; } else { $newJson .= $char; } + break; case ',': if (!$inString) { @@ -248,6 +248,7 @@ private function formatJson(string $json): string } else { $newJson .= $char; } + break; case ':': if (!$inString) { @@ -255,6 +256,7 @@ private function formatJson(string $json): string } else { $newJson .= $char; } + break; case '"': if ($c == 0) { diff --git a/Classes/System/Restler/RestlerExtended.php b/Classes/System/Restler/RestlerExtended.php index 32e0a63..6278c79 100644 --- a/Classes/System/Restler/RestlerExtended.php +++ b/Classes/System/Restler/RestlerExtended.php @@ -85,16 +85,13 @@ public function __construct( /** * Main function for processing the api request * and return the response - * - * @throws Exception when the api service class is missing - * @throws RestException to send error response */ public function handle() { try { // get information about the REST-request (this is required to check, if we can handle the REST-request by TYPO3-cache) $this->get(); - } catch (RestException $exception) { + } catch (RestException $restException) { // Exception occurred (e.g. 'Error encoding/decoding JSON') during getting information about REST-request: // Let restler handle the error (e.g. that JSON could not be read) - and NOT the TYPO3-exception-handling! return parent::handle(); @@ -140,6 +137,7 @@ protected function getPath(): string } else { $siteBasePath = '/'; } + $this->baseUrl = (string) $this->request->getUri() ->withQuery('') ->withPath($siteBasePath); @@ -147,6 +145,7 @@ protected function getPath(): string // set url with base path removed return rtrim(preg_replace('%^' . preg_quote($siteBasePath, '%') . '%', '', $this->request->getUri()->getPath()), '/'); } + return parent::getPath(); } @@ -187,12 +186,14 @@ private function handleRequestByTypo3Cache(): string } else { $expires = gmdate('D, d M Y H:i:s \G\M\T', time() + $cacheEntry['frontendCacheExpires']); } + @header('Expires: ' . $expires); } else { @header($responseHeader); } } } + @header('X-Cached-By-Typo3: 1'); // send data to client diff --git a/Classes/System/Restler/Routes.php b/Classes/System/Restler/Routes.php index a5daa2e..2aa03bd 100644 --- a/Classes/System/Restler/Routes.php +++ b/Classes/System/Restler/Routes.php @@ -36,6 +36,7 @@ public static function containsUrl(string $uri): bool ); } } + if (preg_match($routeMatcher, $uri) === 1) { return true; } diff --git a/Classes/System/RestlerBuilderAware.php b/Classes/System/RestlerBuilderAware.php index 4e6282b..75b7705 100644 --- a/Classes/System/RestlerBuilderAware.php +++ b/Classes/System/RestlerBuilderAware.php @@ -54,6 +54,7 @@ protected function getRestlerBuilder(): Builder if ($this->restlerBuilder === null) { $this->restlerBuilder = GeneralUtility::makeInstance(Builder::class); } + return $this->restlerBuilder; } @@ -62,6 +63,7 @@ protected function isRestlerPrefix(string $prefixedUrlPath): bool if ($this->isRestlerApiUrl($prefixedUrlPath)) { return true; } + return $this->isRestlerApiExplorerUrl($prefixedUrlPath); } diff --git a/Classes/System/TYPO3/Cache.php b/Classes/System/TYPO3/Cache.php index 339288c..0ce8120 100644 --- a/Classes/System/TYPO3/Cache.php +++ b/Classes/System/TYPO3/Cache.php @@ -30,9 +30,6 @@ use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface; use TYPO3\CMS\Core\SingletonInterface; -/** - * @package Restler - */ class Cache implements SingletonInterface { /** @@ -76,12 +73,9 @@ public function __construct(CacheManager $cacheManager) public function isResponseCacheableByTypo3Cache(string $requestMethod, array $apiMethodInfoMetadata): bool { - if ($requestMethod === 'GET' && + return $requestMethod === 'GET' && array_key_exists(self::API_METHOD_TYPO3CACHE_EXPIRES, $apiMethodInfoMetadata) && - array_key_exists(self::API_METHOD_TYPO3CACHE_TAGS, $apiMethodInfoMetadata)) { - return true; - } - return false; + array_key_exists(self::API_METHOD_TYPO3CACHE_TAGS, $apiMethodInfoMetadata); } /** @@ -95,7 +89,7 @@ public function cacheResponseByTypo3Cache( string $responseData, string $responseFormatClass, array $responseHeaders - ) { + ): void { $identifier = $this->buildIdentifier($requestUri, $requestGetData); $frontendCacheExpires = (int) ($apiMethodInfoMetadata['expires'] ?? 0); $typo3CacheExpires = (int) $apiMethodInfoMetadata[self::API_METHOD_TYPO3CACHE_EXPIRES]; @@ -125,7 +119,7 @@ public function hasCacheEntry(string $requestUri, array $getData): bool return $this->cache->has($identifier); } - public function flushByTag(string $tag) + public function flushByTag(string $tag): void { $this->cache->flushByTag($tag); } diff --git a/Classes/System/TYPO3/Loader.php b/Classes/System/TYPO3/Loader.php index bd9e42b..4eb8527 100644 --- a/Classes/System/TYPO3/Loader.php +++ b/Classes/System/TYPO3/Loader.php @@ -47,11 +47,7 @@ use TYPO3\CMS\Frontend\Middleware\FrontendUserAuthenticator; use TYPO3\CMS\Frontend\Middleware\PrepareTypoScriptFrontendRendering; use TYPO3\CMS\Frontend\Middleware\TypoScriptFrontendInitialization; -use LogicException; -/** - * @package Restler - */ class Loader implements SingletonInterface { protected TimeTracker $timeTracker; @@ -86,7 +82,7 @@ public function __construct( * Initialize backend-user with BackendUserAuthenticator middleware. * @see \TYPO3\CMS\Frontend\Middleware\BackendUserAuthenticator */ - public function initializeBackendUser() + public function initializeBackendUser(): void { if ($this->hasActiveBackendUser()) { // Backend-User is already initialized - this can happen when we use/call internal REST-endpoints inside of a normal TYPO3-page @@ -106,14 +102,12 @@ public function hasActiveBackendUser(): bool $GLOBALS['BE_USER']->user['uid'] > 0; } - /** - * @throws LogicException - */ public function getBackendUser(): BackendUserAuthentication { if (!$this->hasActiveBackendUser()) { throw new LogicException("be-user is not initialized - initialize with BE-user with method 'initializeBackendUser'"); } + return $GLOBALS['BE_USER']; } @@ -122,7 +116,7 @@ public function getBackendUser(): BackendUserAuthentication * @param string|int $pid List of page IDs (comma separated) or page ID where to look for frontend user records * @see \TYPO3\CMS\Frontend\Middleware\FrontendUserAuthenticator */ - public function initializeFrontendUser($pid = 0) + public function initializeFrontendUser($pid = 0): void { if ($this->hasActiveFrontendUser()) { // Frontend-User is already initialized - this can happen when we use/call internal REST-endpoints inside of a normal TYPO3-page @@ -148,19 +142,17 @@ public function hasActiveFrontendUser(): bool return $frontendUser instanceof FrontendUserAuthentication && is_array($frontendUser->user) && isset($frontendUser->user['uid']); } - /** - * @throws LogicException - */ public function getFrontendUser(): FrontendUserAuthentication { if (!$this->hasActiveFrontendUser()) { throw new LogicException('fe-user is not initialized'); } + return $this->getRequest() ->getAttribute('frontend.user'); } - public function initializeFrontendRendering(int $pageId = 0, int $type = 0, bool $forcedTemplateParsing = true) + public function initializeFrontendRendering(int $pageId = 0, int $type = 0, bool $forcedTemplateParsing = true): void { if ($this->isFrontendInitialized()) { // FE is already initialized - this can happen when we use/call internal REST-endpoints inside of a normal TYPO3-page @@ -195,8 +187,10 @@ public function initializeFrontendRendering(int $pageId = 0, int $type = 0, bool // Force TemplateParsing (will slow down the called REST-endpoint a little bit): // Otherwise we can't render TYPO3-content in REST-endpoints, when TYPO3-cache 'pages' already exists /** @var TypoScriptFrontendController $controller */ - $controller = $this->getRequest()->getAttribute('frontend.controller'); - $controller->getContext()->setAspect('typoscript', new TypoScriptAspect($forcedTemplateParsing)); + $controller = $this->getRequest() + ->getAttribute('frontend.controller'); + $controller->getContext() + ->setAspect('typoscript', new TypoScriptAspect($forcedTemplateParsing)); } if (VersionNumberUtility::convertVersionNumberToInteger(VersionNumberUtility::getNumericTypo3Version()) > 11005000) { @@ -206,13 +200,11 @@ public function initializeFrontendRendering(int $pageId = 0, int $type = 0, bool // it's TYPO3v10 or lower $prepareTypoScriptFrontendRendering = new PrepareTypoScriptFrontendRendering($GLOBALS['TSFE']); } + $prepareTypoScriptFrontendRendering->process($this->getRequest(), $this->mockRequestHandler); self::setRequest($this->mockRequestHandler->getRequest()); } - /** - * @throws LogicException - */ public function renderPageContent(): string { if (!$this->isFrontendInitialized()) { @@ -225,7 +217,7 @@ public function renderPageContent(): string ->__toString(); } - public static function setRequest(ServerRequestInterface $request) + public static function setRequest(ServerRequestInterface $request): void { $GLOBALS['TYPO3_REQUEST'] = $request; } diff --git a/Classes/System/TYPO3/MockRequestHandler.php b/Classes/System/TYPO3/MockRequestHandler.php index f8624c8..66f3691 100644 --- a/Classes/System/TYPO3/MockRequestHandler.php +++ b/Classes/System/TYPO3/MockRequestHandler.php @@ -31,9 +31,6 @@ use Psr\Http\Server\RequestHandlerInterface; use TYPO3\CMS\Core\Http\NullResponse; -/** - * @package Restler - */ class MockRequestHandler implements RequestHandlerInterface { private ServerRequestInterface $request; diff --git a/Classes/System/TYPO3/RestlerEnhancer.php b/Classes/System/TYPO3/RestlerEnhancer.php index 4bec779..b56e2e8 100644 --- a/Classes/System/TYPO3/RestlerEnhancer.php +++ b/Classes/System/TYPO3/RestlerEnhancer.php @@ -24,7 +24,7 @@ class RestlerEnhancer extends RestlerBuilderAware implements DecoratingEnhancerI /** * @var string|mixed */ - private $default; + private string $default; public function __construct(array $configuration) { diff --git a/README.md b/README.md index c695cbf..e32c376 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ To render the documentation locally, please use the official TYPO3 Documentation ## Copyright / License -Copyright: (c) 2015 - 2022, AOE GmbH +Copyright: (c) 2015 - 2024, AOE GmbH License: GPLv3, [1]: https://extensions.typo3.org/extension/restler diff --git a/Tests/Unit/.phpunit.result.cache b/Tests/Unit/.phpunit.result.cache new file mode 100644 index 0000000..9954878 --- /dev/null +++ b/Tests/Unit/.phpunit.result.cache @@ -0,0 +1 @@ +{"version":1,"defects":[],"times":{"Aoe\\Restler\\Tests\\Unit\\Configuration\\ExtensionConfigurationTest::canCheckThatCacheRefreshingIsNotEnabled":0.007,"Aoe\\Restler\\Tests\\Unit\\Configuration\\ExtensionConfigurationTest::canCheckThatProductionContextIsSet":0.001,"Aoe\\Restler\\Tests\\Unit\\Configuration\\ExtensionConfigurationTest::canCheckThatOnlineDocumentationIsEnabled":0.001,"Aoe\\Restler\\Tests\\Unit\\Configuration\\ExtensionConfigurationTest::canGetPathOfOnlineDocumentation":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\BeUserAuthenticationControllerTest::checkThatAuthenticationWillFailWhenControllerIsNotResponsibleForAuthenticationCheck":0.005,"Aoe\\Restler\\Tests\\Unit\\Controller\\BeUserAuthenticationControllerTest::checkThatAuthenticationWillFailWhenBackendUserIsNotLoggedIn":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\BeUserAuthenticationControllerTest::checkThatAuthenticationWillBeSuccessful":0.006,"Aoe\\Restler\\Tests\\Unit\\Controller\\BeUserAuthenticationControllerTest::checkForCorrectAuthenticationString":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\ExplorerAuthenticationControllerTest::checkThatAuthenticationWillFail":0.002,"Aoe\\Restler\\Tests\\Unit\\Controller\\ExplorerAuthenticationControllerTest::checkThatAuthenticationWillBeSuccessful":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\ExplorerAuthenticationControllerTest::checkForCorrectAuthenticationString":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\FeUserAuthenticationControllerTest::checkThatAuthenticationWillFailWhenControllerIsNotResponsibleForAuthenticationCheck":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\FeUserAuthenticationControllerTest::checkThatAuthenticationWillFailWhenFeUserIsNotLoggedIn":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\FeUserAuthenticationControllerTest::checkThatAuthenticationWillBeSuccessful":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\FeUserAuthenticationControllerTest::shouldSetPageIdZeroIfArgumentDoesNotExist":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\FeUserAuthenticationControllerTest::shouldSetPageIdIfArgumentDoesExist":0.001,"Aoe\\Restler\\Tests\\Unit\\Controller\\FeUserAuthenticationControllerTest::checkForCorrectAuthenticationString":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\DispatcherTest::canProcessToTypo3":0.004,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiClientTest::canCheckIfProductionContextIsSet":0.003,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiClientTest::canCheckIfRequestIsBeingExecuted":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiClientTest::canExecuteRequestInRestApiContext":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiClientTest::canExecuteRequestInTypo3Context":0.002,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiClientTest::shouldThrowExceptionWhenExecutionOfRequestFails":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiRequestTest::canExecuteRestApiRequest":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiRequestTest::shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestIsDone":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiRequestTest::shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestFailsWithException":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiRequestTest::shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestFailsWithRestException":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiRequestTest::shouldThrowRestExceptionWhenExecutionOfRestApiRequestFailsWithException":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\RestApi\\RestApiRequestTest::shouldThrowRestExceptionWhenExecutionOfRestApiRequestFailsWithRestException":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canCreateRestlerObject":0.003,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canConfigureRestlerObject":0.002,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canConfigureRestlerWithExternalConfigurationClassObject":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsNoArray":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsEmptyArray":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canSetAutoLoading":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canSetCacheDirectory":0.002,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::canSetServerConfiguration":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\BuilderTest::addApiControllerClassesFromLocalConf":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ConfigurationTest::checkThatCorrectClassesWillAddedWhenOnlineDocumentationIsEnabled":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ConfigurationTest::checkThatCorrectClassesWillAddedWhenOnlineDocumentationIsNotEnabled":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #0":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #1":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #2":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #3":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #4":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #5":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #6":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #7":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #8":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #9":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #10":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #11":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #12":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #13":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #14":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #15":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #16":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #17":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #18":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #19":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #20":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #21":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #22":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #23":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #24":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #25":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #26":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #27":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #28":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #29":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #30":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #31":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #32":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #33":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #34":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #35":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #36":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #37":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #38":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #39":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #40":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #41":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #42":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #43":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #44":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #45":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #46":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #47":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #48":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #49":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #50":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #51":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #52":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #53":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #54":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #55":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #56":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #57":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #58":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #59":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #60":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #61":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #62":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #63":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #64":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #65":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #66":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #67":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #68":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #69":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #70":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #71":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #72":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #73":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\Restler\\ExceptionHandlerTest::canHandleAllExceptions with data set #74":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::responseShouldBeCacheableWhenRestEndpointUseGetMethodAndTypo3CacheIsConfigured":0.002,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::responseShouldNotBeCacheableWhenRestEndpointUseNoGetMethod":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::responseShouldNotBeCacheableWhenTypo3CacheIsNotConfigured":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::responseShouldBeCached":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::shouldGetCacheEntry":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::shouldHaveCacheEntry":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::shouldHaveNoCacheEntry":0.001,"Aoe\\Restler\\Tests\\Unit\\System\\TYPO3\\CacheTest::shouldFlushCacheByTag":0.001}} \ No newline at end of file diff --git a/Tests/Unit/BaseTest.php b/Tests/Unit/BaseTest.php index 724ecea..0c14b60 100644 --- a/Tests/Unit/BaseTest.php +++ b/Tests/Unit/BaseTest.php @@ -1,4 +1,5 @@ invokeArgs($object, $methodParams); } - - /** - * Initialization. - */ - protected function setUp(): void - { - parent::setUp(); - - $this->setAutoLoadingForRestler(); - } - - /** - * use auto-loading for PHP-classes of restler-framework - */ - private function setAutoLoadingForRestler() - { - // set auto-loading for restler - if (class_exists('\TYPO3\CMS\Core\Core\Environment')) { - $autoload = Environment::getPublicPath() . 'typo3conf/ext/restler/vendor/autoload.php'; - } else { - $autoload = PATH_site . 'typo3conf/ext/restler/vendor/autoload.php'; - } - if (file_exists($autoload)) { - require_once $autoload; - } - } } diff --git a/Tests/Unit/Configuration/ExtensionConfigurationTest.php b/Tests/Unit/Configuration/ExtensionConfigurationTest.php index 3f570a6..f053299 100644 --- a/Tests/Unit/Configuration/ExtensionConfigurationTest.php +++ b/Tests/Unit/Configuration/ExtensionConfigurationTest.php @@ -1,4 +1,5 @@ '0', 'productionContext' => '1', 'enableOnlineDocumentation' => '1', - 'pathToOnlineDocumentation' => 'api_explorer' + 'pathToOnlineDocumentation' => 'api_explorer', ]; $typo3ExtensionConfiguration = $this->getMockBuilder(\TYPO3\CMS\Core\Configuration\ExtensionConfiguration::class) @@ -61,35 +59,23 @@ protected function setUp(): void $this->configuration = new ExtensionConfiguration($typo3ExtensionConfiguration); } - /** - * @test - */ - public function canCheckThatCacheRefreshingIsNotEnabled() + public function testCanCheckThatCacheRefreshingIsNotEnabled(): void { - self::assertFalse($this->configuration->isCacheRefreshingEnabled()); + $this->assertFalse($this->configuration->isCacheRefreshingEnabled()); } - /** - * @test - */ - public function canCheckThatProductionContextIsSet() + public function testCanCheckThatProductionContextIsSet(): void { - self::assertTrue($this->configuration->isProductionContextSet()); + $this->assertTrue($this->configuration->isProductionContextSet()); } - /** - * @test - */ - public function canCheckThatOnlineDocumentationIsEnabled() + public function canCheckThatOnlineDocumentationIsEnabled(): void { - self::assertTrue($this->configuration->isOnlineDocumentationEnabled()); + $this->assertTrue($this->configuration->isOnlineDocumentationEnabled()); } - /** - * @test - */ - public function canGetPathOfOnlineDocumentation() + public function testCanGetPathOfOnlineDocumentation(): void { - self::assertEquals('api_explorer', $this->configuration->getPathOfOnlineDocumentation()); + $this->assertSame('api_explorer', $this->configuration->getPathOfOnlineDocumentation()); } } diff --git a/Tests/Unit/Controller/BeUserAuthenticationControllerTest.php b/Tests/Unit/Controller/BeUserAuthenticationControllerTest.php index ee4e2c1..6bd06c4 100644 --- a/Tests/Unit/Controller/BeUserAuthenticationControllerTest.php +++ b/Tests/Unit/Controller/BeUserAuthenticationControllerTest.php @@ -1,4 +1,5 @@ typo3LoaderMock->expects(self::never())->method('initializeBackendUser'); $this->typo3LoaderMock->expects(self::never())->method('hasActiveBackendUser'); - self::assertFalse($this->controller->__isAllowed()); + $this->assertFalse($this->controller->__isAllowed()); } - /** - * @test - */ - public function checkThatAuthenticationWillFailWhenBackendUserIsNotLoggedIn() + public function testCheckThatAuthenticationWillFailWhenBackendUserIsNotLoggedIn(): void { $this->controller->checkAuthentication = true; $this->typo3LoaderMock->expects(self::once())->method('initializeBackendUser'); $this->typo3LoaderMock->expects(self::once())->method('hasActiveBackendUser')->willReturn(false); - self::assertFalse($this->controller->__isAllowed()); + $this->assertFalse($this->controller->__isAllowed()); } - /** - * @test - */ - public function checkThatAuthenticationWillBeSuccessful() + public function testCheckThatAuthenticationWillBeSuccessful(): void { $this->controller->checkAuthentication = true; $beUser = $this->getMockBuilder(BackendUserAuthentication::class)->disableOriginalConstructor()->getMock(); $beUser->user = [ - 'uid' => 1 + 'uid' => 1, ]; $this->typo3LoaderMock->expects(self::once())->method('initializeBackendUser'); $this->typo3LoaderMock->expects(self::once())->method('hasActiveBackendUser')->willReturn(true); - self::assertTrue($this->controller->__isAllowed()); + $this->assertTrue($this->controller->__isAllowed()); } - /** - * @test - */ - public function checkForCorrectAuthenticationString() + public function testCheckForCorrectAuthenticationString(): void { - self::assertEquals('', $this->controller->__getWWWAuthenticateString()); + $this->assertSame('', $this->controller->__getWWWAuthenticateString()); } } diff --git a/Tests/Unit/Controller/ExplorerAuthenticationControllerTest.php b/Tests/Unit/Controller/ExplorerAuthenticationControllerTest.php index a7de8dd..988f2e5 100644 --- a/Tests/Unit/Controller/ExplorerAuthenticationControllerTest.php +++ b/Tests/Unit/Controller/ExplorerAuthenticationControllerTest.php @@ -1,4 +1,5 @@ disableOriginalConstructor() ->getMock(); - /* @var $restlerMock \Luracast\Restler\Restler */ + /** @var \Luracast\Restler\Restler $restlerMock */ $restlerMock = $this->getMockBuilder(Restler::class)->disableOriginalConstructor()->getMock(); $restlerMock->apiMethodInfo = $this->apiMethodInfoMock; @@ -67,30 +69,21 @@ protected function setUp(): void $this->inject($this->controller, 'restler', $restlerMock); } - /** - * @test - */ - public function checkThatAuthenticationWillFail() + public function testCheckThatAuthenticationWillFail(): void { $this->apiMethodInfoMock->className = 'NoneExplorerClass'; - self::assertFalse($this->controller->__isAllowed()); + $this->assertFalse($this->controller->__isAllowed()); } - /** - * @test - */ - public function checkThatAuthenticationWillBeSuccessful() + public function testCheckThatAuthenticationWillBeSuccessful(): void { $this->apiMethodInfoMock->className = Explorer::class; - self::assertTrue($this->controller->__isAllowed()); + $this->assertTrue($this->controller->__isAllowed()); } - /** - * @test - */ - public function checkForCorrectAuthenticationString() + public function testCheckForCorrectAuthenticationString(): void { $this->apiMethodInfoMock->className = Explorer::class; - self::assertEquals('Query name="api_key"', $this->controller->__getWWWAuthenticateString()); + $this->assertSame('Query name="api_key"', $this->controller->__getWWWAuthenticateString()); } } diff --git a/Tests/Unit/Controller/FeUserAuthenticationControllerTest.php b/Tests/Unit/Controller/FeUserAuthenticationControllerTest.php index 93ade81..28d8e94 100644 --- a/Tests/Unit/Controller/FeUserAuthenticationControllerTest.php +++ b/Tests/Unit/Controller/FeUserAuthenticationControllerTest.php @@ -1,4 +1,5 @@ typo3LoaderMock->expects(self::never())->method('initializeFrontendUser'); $this->typo3LoaderMock->expects(self::never())->method('hasActiveFrontendUser'); - self::assertFalse($this->controller->__isAllowed()); + $this->assertFalse($this->controller->__isAllowed()); } - /** - * @test - */ - public function checkThatAuthenticationWillFailWhenFeUserIsNotLoggedIn() + public function testCheckThatAuthenticationWillFailWhenFeUserIsNotLoggedIn(): void { $this->controller->argumentNameOfPageId = '5'; $this->controller->checkAuthentication = true; @@ -90,13 +86,10 @@ public function checkThatAuthenticationWillFailWhenFeUserIsNotLoggedIn() $this->typo3LoaderMock->expects(self::once())->method('initializeFrontendUser')->with('5'); $this->typo3LoaderMock->expects(self::once())->method('hasActiveFrontendUser')->willReturn(false); - self::assertFalse($this->controller->__isAllowed()); + $this->assertFalse($this->controller->__isAllowed()); } - /** - * @test - */ - public function checkThatAuthenticationWillBeSuccessful() + public function testCheckThatAuthenticationWillBeSuccessful(): void { $this->controller->argumentNameOfPageId = '5'; $this->controller->checkAuthentication = true; @@ -105,18 +98,15 @@ public function checkThatAuthenticationWillBeSuccessful() $this->typo3LoaderMock->expects(self::once())->method('initializeFrontendUser')->with('5'); $this->typo3LoaderMock->expects(self::once())->method('hasActiveFrontendUser')->willReturn(true); - self::assertTrue($this->controller->__isAllowed()); + $this->assertTrue($this->controller->__isAllowed()); } - /** - * @test - */ - public function shouldSetPageIdZeroIfArgumentDoesNotExist() + public function testShouldSetPageIdZeroIfArgumentDoesNotExist(): void { /** @var ApiMethodInfo $apiMethodInfoMock */ $apiMethodInfoMock = $this->getMockBuilder(ApiMethodInfo::class)->disableOriginalConstructor()->getMock(); - /* @var Restler $restlerMock */ + /** @var Restler $restlerMock */ $restlerMock = $this->getMockBuilder(Restler::class)->disableOriginalConstructor()->getMock(); $restlerMock->apiMethodInfo = $apiMethodInfoMock; $this->inject($this->controller, 'restler', $restlerMock); @@ -128,13 +118,10 @@ public function shouldSetPageIdZeroIfArgumentDoesNotExist() $method = $reflection->getMethod('determinePageIdFromArguments'); $method->setAccessible(true); - self::assertEquals(0, $method->invoke($this->controller)); + $this->assertSame(0, $method->invoke($this->controller)); } - /** - * @test - */ - public function shouldSetPageIdIfArgumentDoesExist() + public function testShouldSetPageIdIfArgumentDoesExist(): void { /** @var \Luracast\Restler\Data\ApiMethodInfo $apiMethodInfoMock */ $apiMethodInfoMock = $this->getMockBuilder(ApiMethodInfo::class)->disableOriginalConstructor()->getMock(); @@ -147,7 +134,7 @@ public function shouldSetPageIdIfArgumentDoesExist() [0 => 4711] ); - /* @var Restler $restlerMock */ + /** @var Restler $restlerMock */ $restlerMock = $this->getMockBuilder(Restler::class)->disableOriginalConstructor()->getMock(); $restlerMock->apiMethodInfo = $apiMethodInfoMock; $this->inject($this->controller, 'restler', $restlerMock); @@ -159,14 +146,11 @@ public function shouldSetPageIdIfArgumentDoesExist() $method = $reflection->getMethod('determinePageIdFromArguments'); $method->setAccessible(true); - self::assertEquals(4711, $method->invoke($this->controller)); + $this->assertSame(4711, $method->invoke($this->controller)); } - /** - * @test - */ - public function checkForCorrectAuthenticationString() + public function testCheckForCorrectAuthenticationString(): void { - self::assertEquals('', $this->controller->__getWWWAuthenticateString()); + $this->assertSame('', $this->controller->__getWWWAuthenticateString()); } } diff --git a/Tests/Unit/System/DispatcherTest.php b/Tests/Unit/System/DispatcherTest.php index 4dd5db2..9dee6d7 100644 --- a/Tests/Unit/System/DispatcherTest.php +++ b/Tests/Unit/System/DispatcherTest.php @@ -60,17 +60,20 @@ protected function setUp(): void { parent::setUp(); - $this->restlerBuilder = $this->getMockBuilder(Builder::class)->disableOriginalConstructor()->setMethods(['build'])->getMock(); + $this->restlerBuilder = $this->getMockBuilder(Builder::class)->disableOriginalConstructor()->onlyMethods(['build'])->getMock(); GeneralUtility::setSingletonInstance(Builder::class, $this->restlerBuilder); $configurationMock = self::getMockBuilder(ExtensionConfiguration::class)->disableOriginalConstructor()->getMock(); $this->dispatcher = new Dispatcher($configurationMock); } - /** - * @test - */ - public function canProcessToTypo3() + protected function tearDown(): void + { + $this->resetSingletonInstances = true; + parent::tearDown(); + } + + public function testCanProcessToTypo3(): void { /** @var Restler|MockObject $restlerMock */ $restlerMock = $this->createMock(Restler::class); @@ -78,15 +81,22 @@ public function canProcessToTypo3() $this->restlerBuilder->expects(self::any())->method('build')->willReturn($restlerMock); $requestUri = $this->getMockBuilder(Uri::class)->getMock(); - $requestUri->method('getPath')->willReturn("/no/api/url"); - $requestUri->method('withQuery')->willReturn($requestUri); - $requestUri->method('withPath')->willReturn($requestUri); + $requestUri->method('getPath') + ->willReturn('/no/api/url'); + $requestUri->method('withQuery') + ->willReturn($requestUri); + $requestUri->method('withPath') + ->willReturn($requestUri); - $request = $this->getMockBuilder('Psr\\Http\\Message\\ServerRequestInterface')->getMock(); - $request->method('getUri')->willReturn($requestUri); + $request = $this->getMockBuilder(\Psr\Http\Message\ServerRequestInterface::class) + ->getMock(); + $request->method('getUri') + ->willReturn($requestUri); - $handler = $this->getMockBuilder('Psr\\Http\\Server\\RequestHandlerInterface')->getMock(); - $handler->expects(self::once())->method('handle'); + $handler = $this->getMockBuilder(\Psr\Http\Server\RequestHandlerInterface::class) + ->getMock(); + $handler->expects(self::once()) + ->method('handle'); $this->dispatcher->process($request, $handler); } diff --git a/Tests/Unit/System/RestApi/RestApiClientTest.php b/Tests/Unit/System/RestApi/RestApiClientTest.php index 42dd649..b079ff8 100644 --- a/Tests/Unit/System/RestApi/RestApiClientTest.php +++ b/Tests/Unit/System/RestApi/RestApiClientTest.php @@ -1,4 +1,5 @@ extensionConfigurationMock = $this->getMockBuilder(ExtensionConfiguration::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->restApiRequestMock = $this->getMockBuilder(RestApiRequest::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->restApiRequestScopeMock = $this->getMockBuilder(RestApiRequestScope::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->restlerBuilderMock = $this->getMockBuilder(RestlerBuilder::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->typo3CacheMock = $this->getMockBuilder(Typo3Cache::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->restApiClient = $this->getMockBuilder(RestApiClient::class) ->setConstructorArgs([$this->extensionConfigurationMock, $this->restApiRequestScopeMock, $this->typo3CacheMock]) - ->setMethods(['createRequest', 'getRestlerBuilder', 'isRequestPreparationRequired']) + ->onlyMethods(['createRequest', 'getRestlerBuilder', 'isRequestPreparationRequired']) ->getMock(); $this->restApiClient->expects(self::any())->method('createRequest')->willReturn($this->restApiRequestMock); $this->restApiClient->expects(self::any())->method('getRestlerBuilder')->willReturn($this->restlerBuilderMock); } - /** - * @test - */ - public function canCheckIfProductionContextIsSet() + public function testCanCheckIfProductionContextIsSet(): void { $this->extensionConfigurationMock->expects(self::once())->method('isProductionContextSet')->willReturn(true); - self::assertTrue($this->restApiClient->isProductionContextSet()); + $this->assertTrue($this->restApiClient->isProductionContextSet()); } - /** - * @test - */ - public function canCheckIfRequestIsBeingExecuted() + public function testCanCheckIfRequestIsBeingExecuted(): void { - self::assertFalse($this->restApiClient->isExecutingRequest()); + $this->assertFalse($this->restApiClient->isExecutingRequest()); } /** * Test, that we don't must create the 'original' REST-API-Request (aka Restler-object) before we can execute the REST-API-request - * - * @test */ - public function canExecuteRequestInRestApiContext() + public function testCanExecuteRequestInRestApiContext(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; - $getData = ['context' => 'mobile']; + $getData = ['context' => 'mobile']; $postData = []; $result = ['id' => 1, 'name' => 'Test-Product']; @@ -131,56 +134,62 @@ public function canExecuteRequestInRestApiContext() $this->restApiRequestScopeMock->expects(self::never())->method('storeOriginalRestApiRequest'); // Test, that we get an result when we execute the REST-API-request - $this->restApiRequestMock->expects($this->once())->method('executeRestApiRequest') + $this->restApiRequestMock->expects($this->once()) + ->method('executeRestApiRequest') ->with($requestMethod, $requestUri, $getData, $postData) ->willReturn($result); - self::assertEquals($result, $this->restApiClient->executeRequest($requestMethod, $requestUri, $getData, $postData)); + $this->assertSame($result, $this->restApiClient->executeRequest($requestMethod, $requestUri, $getData, $postData)); } /** * Test, that we must create the 'original' REST-API-Request (aka Restler-object) before we can execute the REST-API-request - * - * @test */ - public function canExecuteRequestInTypo3Context() + public function testCanExecuteRequestInTypo3Context(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; - $getData = ['context' => 'mobile']; + $getData = ['context' => 'mobile']; $postData = []; $result = ['id' => 1, 'name' => 'Test-Product']; // Test, that we must create the 'original' REST-API-Request (aka Restler-object) before we can execute the REST-API-request $originalRestApiRequestMock = $this->getMockBuilder(Restler::class)->disableOriginalConstructor()->getMock(); - $this->restApiClient->expects($this->once())->method('isRequestPreparationRequired')->willReturn(true); - $this->restlerBuilderMock->expects($this->once())->method('build')->willReturn($originalRestApiRequestMock); - $this->restApiRequestScopeMock->expects($this->once())->method('storeOriginalRestApiRequest')->with($originalRestApiRequestMock); + $this->restApiClient->expects($this->once()) + ->method('isRequestPreparationRequired') + ->willReturn(true); + $this->restlerBuilderMock->expects($this->once()) + ->method('build') + ->willReturn($originalRestApiRequestMock); + $this->restApiRequestScopeMock->expects($this->once()) + ->method('storeOriginalRestApiRequest') + ->with($originalRestApiRequestMock); // Test, that we get an result when we execute the REST-API-request - $this->restApiRequestMock->expects($this->once())->method('executeRestApiRequest') + $this->restApiRequestMock->expects($this->once()) + ->method('executeRestApiRequest') ->with($requestMethod, $requestUri, $getData, $postData) ->willReturn($result); - self::assertEquals($result, $this->restApiClient->executeRequest($requestMethod, $requestUri, $getData, $postData)); + $this->assertSame($result, $this->restApiClient->executeRequest($requestMethod, $requestUri, $getData, $postData)); } - /** - * @test - */ - public function shouldThrowExceptionWhenExecutionOfRequestFails() + public function testShouldThrowExceptionWhenExecutionOfRequestFails(): void { $this->expectException(RestApiRequestException::class); $this->expectExceptionCode(1446475601); $requestMethod = 'GET'; $requestUri = '/api/products/1'; - $getData = ['context' => 'mobile']; + $getData = ['context' => 'mobile']; $postData = []; $exception = new RestException(400, 'message'); - $this->restApiClient->expects($this->once())->method('isRequestPreparationRequired')->willReturn(false); - $this->restApiRequestMock->expects($this->once())->method('executeRestApiRequest') + $this->restApiClient->expects($this->once()) + ->method('isRequestPreparationRequired') + ->willReturn(false); + $this->restApiRequestMock->expects($this->once()) + ->method('executeRestApiRequest') ->with($requestMethod, $requestUri, $getData, $postData) - ->will($this->throwException($exception)); + ->willThrowException($exception); $this->restApiClient->executeRequest($requestMethod, $requestUri, $getData, $postData); } diff --git a/Tests/Unit/System/RestApi/RestApiRequestTest.php b/Tests/Unit/System/RestApi/RestApiRequestTest.php index ecd6a0d..7867d41 100644 --- a/Tests/Unit/System/RestApi/RestApiRequestTest.php +++ b/Tests/Unit/System/RestApi/RestApiRequestTest.php @@ -1,4 +1,5 @@ originalServerSettings = $_SERVER; $this->restApiRequestScopeMock = $this->getMockBuilder(RestApiRequestScope::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->typo3CacheMock = $this->getMockBuilder(Typo3Cache::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->restApiRequest = $this->getMockBuilder(RestApiRequest::class) ->setConstructorArgs([$this->restApiRequestScopeMock, $this->typo3CacheMock]) - ->setMethods(['handle']) + ->onlyMethods(['handle']) ->getMock(); } @@ -102,14 +110,11 @@ protected function tearDown(): void parent::tearDown(); } - /** - * @test - */ - public function canExecuteRestApiRequest() + public function testCanExecuteRestApiRequest(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; - $getData = ['context' => 'mobile']; + $getData = ['context' => 'mobile']; $postData = []; $result = ['id' => 1, 'name' => 'Test-Product']; @@ -122,15 +127,13 @@ public function canExecuteRestApiRequest() $this->restApiRequestScopeMock->expects(self::once())->method('restoreOriginalRestApiRequest'); $this->restApiRequestScopeMock->expects(self::once())->method('restoreOriginalRestApiAuthenticationObjects'); $this->restApiRequest->expects(self::once())->method('handle')->willReturn($result); - self::assertEquals($result, $this->restApiRequest->executeRestApiRequest($requestMethod, $requestUri, $getData, $postData)); + $this->assertSame($result, $this->restApiRequest->executeRestApiRequest($requestMethod, $requestUri, $getData, $postData)); } /** * Test, that the restApiRequest-object restore the original data of $_GET, $_POST and $_SERVER and the original restApiRequest-object - * - * @test */ - public function shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestIsDone() + public function testShouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestIsDone(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; @@ -147,17 +150,15 @@ public function shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequest $this->restApiRequest->expects(self::once())->method('handle')->willReturn($result); $this->restApiRequest->executeRestApiRequest($requestMethod, $requestUri); - self::assertEquals($this->originalGetVars, $_GET); - self::assertEquals($this->originalPostVars, $_POST); - self::assertEquals($this->originalServerSettings, $_SERVER); + $this->assertEquals($this->originalGetVars, $_GET); + $this->assertEquals($this->originalPostVars, $_POST); + $this->assertEquals($this->originalServerSettings, $_SERVER); } /** * Test, that the restApiRequest-object restore the original data of $_GET, $_POST and $_SERVER and the original restApiRequest-object - * - * @test */ - public function shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestFailsWithException() + public function testShouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestFailsWithException(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; @@ -178,17 +179,15 @@ public function shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequest } catch (Exception $e) { } - self::assertEquals($this->originalGetVars, $_GET); - self::assertEquals($this->originalPostVars, $_POST); - self::assertEquals($this->originalServerSettings, $_SERVER); + $this->assertEquals($this->originalGetVars, $_GET); + $this->assertEquals($this->originalPostVars, $_POST); + $this->assertEquals($this->originalServerSettings, $_SERVER); } /** * Test, that the restApiRequest-object restore the original data of $_GET, $_POST and $_SERVER and the original restApiRequest-object - * - * @test */ - public function shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestFailsWithRestException() + public function testShouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequestFailsWithRestException(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; @@ -209,19 +208,16 @@ public function shouldRestoreOriginalRestApiRequestWhenExecutionOfRestApiRequest } catch (Exception $e) { } - self::assertEquals($this->originalGetVars, $_GET); - self::assertEquals($this->originalPostVars, $_POST); - self::assertEquals($this->originalServerSettings, $_SERVER); + $this->assertEquals($this->originalGetVars, $_GET); + $this->assertEquals($this->originalPostVars, $_POST); + $this->assertEquals($this->originalServerSettings, $_SERVER); } - /** - * @test - */ - public function shouldThrowRestExceptionWhenExecutionOfRestApiRequestFailsWithException() + public function testShouldThrowRestExceptionWhenExecutionOfRestApiRequestFailsWithException(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; - $getData = ['context' => 'mobile']; + $getData = ['context' => 'mobile']; $postData = []; $exception = new Exception(); @@ -234,14 +230,11 @@ public function shouldThrowRestExceptionWhenExecutionOfRestApiRequestFailsWithEx $this->restApiRequest->executeRestApiRequest($requestMethod, $requestUri, $getData, $postData); } - /** - * @test - */ - public function shouldThrowRestExceptionWhenExecutionOfRestApiRequestFailsWithRestException() + public function testShouldThrowRestExceptionWhenExecutionOfRestApiRequestFailsWithRestException(): void { $requestMethod = 'GET'; $requestUri = '/api/products/1'; - $getData = ['context' => 'mobile']; + $getData = ['context' => 'mobile']; $postData = []; $exception = new RestException(400, 'message'); diff --git a/Tests/Unit/System/Restler/BuilderTest.php b/Tests/Unit/System/Restler/BuilderTest.php index 38fdf8d..7c4cb22 100644 --- a/Tests/Unit/System/Restler/BuilderTest.php +++ b/Tests/Unit/System/Restler/BuilderTest.php @@ -1,4 +1,5 @@ [ - 'restlerConfigurationClasses' => [] - ] + 'restlerConfigurationClasses' => [], + ], ]; $GLOBALS['TYPO3_Restler'] = [ 'restlerConfigurationClasses' => [], - 'addApiClass' => null + 'addApiClass' => null, ]; $this->originalRestlerConfigurationClasses = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['restler']['restlerConfigurationClasses']; $this->originalServerVars = $_SERVER; $this->extensionConfigurationMock = $this->getMockBuilder(ExtensionConfiguration::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->cacheManagerMock = $this->getMockBuilder(CacheManager::class) ->disableOriginalConstructor() - ->setMethods(['getCache']) + ->onlyMethods(['getCache']) ->getMock(); $this->builder = new Builder( @@ -114,13 +120,11 @@ protected function tearDown(): void { $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['restler']['restlerConfigurationClasses'] = $this->originalRestlerConfigurationClasses; $_SERVER = $this->originalServerVars; + $this->resetSingletonInstances = true; parent::tearDown(); } - /** - * @test - */ - public function canCreateRestlerObject() + public function testCanCreateRestlerObject(): void { $this->extensionConfigurationMock ->expects(self::once())->method('isProductionContextSet') @@ -135,25 +139,26 @@ public function canCreateRestlerObject() $typo3RequestMock = $this->getMockBuilder(ServerRequest::class)->disableOriginalConstructor()->getMock(); $requestUri = $this->getMockBuilder(Uri::class)->getMock(); - $requestUri->expects(self::atLeastOnce())->method('getPath')->willReturn("/api/device"); - $requestUri->method('withQuery')->willReturn($requestUri); - $requestUri->method('withPath')->willReturn($requestUri); + $requestUri->expects(self::atLeastOnce())->method('getPath')->willReturn('/api/device'); + $requestUri->method('withQuery') + ->willReturn($requestUri); + $requestUri->method('withPath') + ->willReturn($requestUri); $typo3RequestMock->expects(self::atLeastOnce())->method('getUri')->willReturn($requestUri); - $createdObj = $this->callUnaccessibleMethodOfObject($this->builder, 'createRestlerObject', [$typo3RequestMock] ); - self::assertInstanceOf(RestlerExtended::class, $createdObj); + $createdObj = $this->callUnaccessibleMethodOfObject($this->builder, 'createRestlerObject', [$typo3RequestMock]); + $this->assertInstanceOf(RestlerExtended::class, $createdObj); } - /** - * @test - */ - public function canConfigureRestlerObject() + public function testCanConfigureRestlerObject(): void { $restlerObj = $this->getMockBuilder(RestlerExtended::class)->disableOriginalConstructor()->getMock(); $configurationClass = ValidConfiguration::class; - $configurationMock = $this->getMockBuilder($configurationClass)->disableOriginalConstructor()->getMock(); + $configurationMock = $this->getMockBuilder($configurationClass) + ->disableOriginalConstructor() + ->getMock(); $configurationMock->expects(self::once())->method('configureRestler')->with($restlerObj); GeneralUtility::setSingletonInstance(ValidConfiguration::class, $configurationMock); @@ -165,15 +170,14 @@ public function canConfigureRestlerObject() $this->callUnaccessibleMethodOfObject($this->builder, 'configureRestler', [$restlerObj]); } - /** - * @test - */ - public function canConfigureRestlerWithExternalConfigurationClassObject() + public function testCanConfigureRestlerWithExternalConfigurationClassObject(): void { $restlerObj = $this->getMockBuilder(RestlerExtended::class)->disableOriginalConstructor()->getMock(); $configurationClass = ValidConfiguration::class; - $configurationMock = $this->getMockBuilder($configurationClass)->disableOriginalConstructor()->getMock(); + $configurationMock = $this->getMockBuilder($configurationClass) + ->disableOriginalConstructor() + ->getMock(); $configurationMock->expects(self::exactly(2))->method('configureRestler')->with($restlerObj); GeneralUtility::setSingletonInstance(ValidConfiguration::class, $configurationMock); @@ -185,10 +189,7 @@ public function canConfigureRestlerWithExternalConfigurationClassObject() $this->callUnaccessibleMethodOfObject($this->builder, 'configureRestler', [$restlerObj]); } - /** - * @test - */ - public function canNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsNoArray() + public function testCanNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsNoArray(): void { $this->expectException(InvalidArgumentException::class); @@ -199,10 +200,7 @@ public function canNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsN $this->callUnaccessibleMethodOfObject($this->builder, 'configureRestler', [$restlerObj]); } - /** - * @test - */ - public function canNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsEmptyArray() + public function testCanNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsEmptyArray(): void { $this->expectException(InvalidArgumentException::class); @@ -213,10 +211,7 @@ public function canNotConfigureRestlerObjectWhenConfigurationOfRestlerClassesIsE $this->callUnaccessibleMethodOfObject($this->builder, 'configureRestler', [$restlerObj]); } - /** - * @test - */ - public function canSetAutoLoading() + public function testCanSetAutoLoading(): void { // set object-property (which the builder should update) Scope::$resolver = null; @@ -227,15 +222,12 @@ public function canSetAutoLoading() $this->callUnaccessibleMethodOfObject($this->builder, 'setAutoLoading'); $closureToCreateObjectsViaTypo3GeneralUtilityMakeInstance = Scope::$resolver; - self::assertTrue(is_callable($closureToCreateObjectsViaTypo3GeneralUtilityMakeInstance)); + $this->assertTrue(is_callable($closureToCreateObjectsViaTypo3GeneralUtilityMakeInstance)); $createdObj = $closureToCreateObjectsViaTypo3GeneralUtilityMakeInstance($requestedClass); - self::assertEquals($createdObj, $this->extensionConfigurationMock); + $this->assertEquals($createdObj, $this->extensionConfigurationMock); } - /** - * @test - */ - public function canSetCacheDirectory() + public function testCanSetCacheDirectory(): void { // set object-property (which the builder should update) Defaults::$cacheDirectory = ''; @@ -243,42 +235,35 @@ public function canSetCacheDirectory() /** @var SimpleFileBackend|MockObject $simpleFileBackend */ $simpleFileBackend = $this->getMockBuilder(SimpleFileBackend::class) ->disableOriginalConstructor() - ->setMethods(['getCacheDirectory']) + ->onlyMethods(['getCacheDirectory']) ->getMock(); $simpleFileBackend->expects(self::once())->method('getCacheDirectory')->willReturn( 'typo3temp/Cache/Data/tx_restler_cache' ); - /** @var PhpFrontend|MockObject $simpleFileBackend */ $cacheFrontend = $this->getMockBuilder(PhpFrontend::class) ->disableOriginalConstructor() - ->setMethods(['getBackend']) + ->onlyMethods(['getBackend']) ->getMock(); $cacheFrontend->expects(self::once())->method('getBackend')->willReturn($simpleFileBackend); $this->cacheManagerMock->expects(self::once())->method('getCache')->willReturn($cacheFrontend); $this->callUnaccessibleMethodOfObject($this->builder, 'setCacheDirectory'); - self::assertEquals('typo3temp/Cache/Data/tx_restler_cache', Defaults::$cacheDirectory); + $this->assertSame('typo3temp/Cache/Data/tx_restler_cache', Defaults::$cacheDirectory); } - /** - * @test - */ - public function canSetServerConfiguration() + public function testCanSetServerConfiguration(): void { // set variables (which the builder should use/update) $_SERVER['HTTPS'] = 'on'; $_SERVER['SERVER_PORT'] = '80'; $this->callUnaccessibleMethodOfObject($this->builder, 'setServerConfiguration'); - self::assertEquals('443', $_SERVER['SERVER_PORT']); + $this->assertSame('443', $_SERVER['SERVER_PORT']); } - /** - * @test - */ - public function addApiControllerClassesFromLocalConf() + public function testAddApiControllerClassesFromLocalConf(): void { // setup $backupGlobals = $GLOBALS['TYPO3_Restler']['addApiClass']; @@ -289,7 +274,7 @@ public function addApiControllerClassesFromLocalConf() $restlerObj->expects(self::once())->method('addAPIClass')->with('BarController', 'foopath'); //verifiy - $this->callUnaccessibleMethodOfObject($this->builder, 'addApiClassesByGlobalArray', array($restlerObj)); + $this->callUnaccessibleMethodOfObject($this->builder, 'addApiClassesByGlobalArray', [$restlerObj]); //tear down $GLOBALS['TYPO3_Restler']['addApiClass'] = $backupGlobals; diff --git a/Tests/Unit/System/Restler/ConfigurationTest.php b/Tests/Unit/System/Restler/ConfigurationTest.php index 5be3103..5518d16 100644 --- a/Tests/Unit/System/Restler/ConfigurationTest.php +++ b/Tests/Unit/System/Restler/ConfigurationTest.php @@ -1,4 +1,5 @@ extensionConfigurationMock = $this->getMockBuilder(ExtensionConfiguration::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->restlerMock = $this->getMockBuilder(Restler::class)->disableOriginalConstructor()->getMock(); $this->configuration = new Configuration($this->extensionConfigurationMock); } - /** - * @test - */ - public function checkThatCorrectClassesWillAddedWhenOnlineDocumentationIsEnabled() + public function testCheckThatCorrectClassesWillAddedWhenOnlineDocumentationIsEnabled(): void { $this->extensionConfigurationMock->expects(self::once())->method('isOnlineDocumentationEnabled')->willReturn(true); $this->extensionConfigurationMock->expects(self::once())->method('getPathOfOnlineDocumentation')->willReturn('path'); @@ -84,7 +85,7 @@ public function checkThatCorrectClassesWillAddedWhenOnlineDocumentationIsEnabled $this->restlerMock ->expects(self::exactly(3)) ->method('addAuthenticationClass') - ->withConsecutive( + ->willReturnOnConsecutiveCalls( [ExplorerAuthenticationController::class], [BeUserAuthenticationController::class], [FeUserAuthenticationController::class] @@ -93,10 +94,7 @@ public function checkThatCorrectClassesWillAddedWhenOnlineDocumentationIsEnabled $this->configuration->configureRestler($this->restlerMock); } - /** - * @test - */ - public function checkThatCorrectClassesWillAddedWhenOnlineDocumentationIsNotEnabled() + public function testCheckThatCorrectClassesWillAddedWhenOnlineDocumentationIsNotEnabled(): void { $this->extensionConfigurationMock->expects(self::once())->method('isOnlineDocumentationEnabled')->willReturn(false); $this->extensionConfigurationMock->expects(self::never())->method('getPathOfOnlineDocumentation'); @@ -108,7 +106,7 @@ public function checkThatCorrectClassesWillAddedWhenOnlineDocumentationIsNotEnab $this->restlerMock ->expects(self::exactly(2)) ->method('addAuthenticationClass') - ->withConsecutive( + ->willReturnOnConsecutiveCalls( [BeUserAuthenticationController::class], [FeUserAuthenticationController::class] ); diff --git a/Tests/Unit/System/Restler/ExceptionHandlerTest.php b/Tests/Unit/System/Restler/ExceptionHandlerTest.php index 0976f85..a6fcfec 100644 --- a/Tests/Unit/System/Restler/ExceptionHandlerTest.php +++ b/Tests/Unit/System/Restler/ExceptionHandlerTest.php @@ -41,21 +41,16 @@ class ExceptionHandlerTest extends BaseTest { /** * @dataProvider statusCodes - * @test */ - public function canHandleAllExceptions($statusCode, $statusName) + public function testCanHandleAllExceptions(int $statusCode, string $statusName): void { - if ($statusName) { - $message = $statusName; - } else { - $message = 'dummy-message'; - } + $message = $statusName !== '' && $statusName !== '0' ? $statusName : 'dummy-message'; $restler = $this->getMockBuilder(Restler::class)->disableOriginalConstructor()->getMock(); $exceptionHandler = $this->getMockBuilder(ExceptionHandler::class) ->disableOriginalConstructor() - ->setMethods(['getRestler', 'getRestlerException']) + ->onlyMethods(['getRestler', 'getRestlerException']) ->getMock(); $exceptionHandler->expects(self::any())->method('getRestler')->willReturn($restler); @@ -64,10 +59,10 @@ public function canHandleAllExceptions($statusCode, $statusName) $exceptionHandler->expects(self::any())->method('getRestlerException')->willReturn($restlerException); $functionName = 'handle' . $statusCode; - self::assertEquals($message, $exceptionHandler->$functionName()); + $this->assertEquals($message, $exceptionHandler->$functionName()); } - public function statusCodes() + public static function statusCodes(): array { return [ [100, 'Continue'], @@ -110,7 +105,7 @@ public function statusCodes() [415, 'Unsupported Media Type'], [416, 'Requested Range Not Satisfiable'], [417, 'Expectation Failed'], - [418, 'I\'m a teapot'], + [418, "I'm a teapot"], [420, ''], [421, 'Misdirected Request'], [422, 'Unprocessable Entity'], diff --git a/Tests/Unit/System/Restler/Fixtures/ExceptionHandler.php b/Tests/Unit/System/Restler/Fixtures/ExceptionHandler.php index 3e2237e..586bf31 100644 --- a/Tests/Unit/System/Restler/Fixtures/ExceptionHandler.php +++ b/Tests/Unit/System/Restler/Fixtures/ExceptionHandler.php @@ -1,4 +1,5 @@ addAPIClass('Test-API-Class', 'Test-ResourcePath'); $restler->addAuthenticationClass('Test-Authentication-Class'); diff --git a/Tests/Unit/System/Restler/Fixtures/ValidConfiguration.php b/Tests/Unit/System/Restler/Fixtures/ValidConfiguration.php index e653835..aeaaa0a 100644 --- a/Tests/Unit/System/Restler/Fixtures/ValidConfiguration.php +++ b/Tests/Unit/System/Restler/Fixtures/ValidConfiguration.php @@ -1,4 +1,5 @@ addAPIClass('Test-API-Class', 'Test-ResourcePath'); $restler->addAuthenticationClass('Test-Authentication-Class'); diff --git a/Tests/Unit/System/TYPO3/CacheTest.php b/Tests/Unit/System/TYPO3/CacheTest.php index cc600a7..2f2ebeb 100644 --- a/Tests/Unit/System/TYPO3/CacheTest.php +++ b/Tests/Unit/System/TYPO3/CacheTest.php @@ -1,4 +1,5 @@ frontendCacheMock = $this->getMockBuilder(FrontendInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $cacheManagerMock = $this->getMockBuilder(CacheManager::class)->disableOriginalConstructor()->getMock(); $cacheManagerMock->expects(self::once())->method('getCache')->with('restler')->willReturn($this->frontendCacheMock); $this->cache = new Cache($cacheManagerMock); } - /** - * @test - */ - public function responseShouldBeCacheableWhenRestEndpointUseGetMethodAndTypo3CacheIsConfigured() + public function testResponseShouldBeCacheableWhenRestEndpointUseGetMethodAndTypo3CacheIsConfigured(): void { $requestMethod = 'GET'; $apiMethodInfoMetadata = []; $apiMethodInfoMetadata[Cache::API_METHOD_TYPO3CACHE_EXPIRES] = 0; $apiMethodInfoMetadata[Cache::API_METHOD_TYPO3CACHE_TAGS] = 'tag_a'; - self::assertTrue($this->cache->isResponseCacheableByTypo3Cache($requestMethod, $apiMethodInfoMetadata)); + $this->assertTrue($this->cache->isResponseCacheableByTypo3Cache($requestMethod, $apiMethodInfoMetadata)); } - /** - * @test - */ - public function responseShouldNotBeCacheableWhenRestEndpointUseNoGetMethod() + public function testResponseShouldNotBeCacheableWhenRestEndpointUseNoGetMethod(): void { $requestMethod = 'POST'; $apiMethodInfoMetadata = []; $apiMethodInfoMetadata[Cache::API_METHOD_TYPO3CACHE_EXPIRES] = 0; $apiMethodInfoMetadata[Cache::API_METHOD_TYPO3CACHE_TAGS] = 'tag_a'; - self::assertFalse($this->cache->isResponseCacheableByTypo3Cache($requestMethod, $apiMethodInfoMetadata)); + $this->assertFalse($this->cache->isResponseCacheableByTypo3Cache($requestMethod, $apiMethodInfoMetadata)); } - /** - * @test - */ - public function responseShouldNotBeCacheableWhenTypo3CacheIsNotConfigured() + public function testResponseShouldNotBeCacheableWhenTypo3CacheIsNotConfigured(): void { $requestMethod = 'GET'; $apiMethodInfoMetadata = []; - self::assertFalse($this->cache->isResponseCacheableByTypo3Cache($requestMethod, $apiMethodInfoMetadata)); + $this->assertFalse($this->cache->isResponseCacheableByTypo3Cache($requestMethod, $apiMethodInfoMetadata)); } - /** - * @test - */ - public function responseShouldBeCached() + public function testResponseShouldBeCached(): void { $responseCode = 123; $requestUri = 'api/shop/devices'; @@ -141,10 +131,7 @@ public function responseShouldBeCached() ); } - /** - * @test - */ - public function shouldGetCacheEntry() + public function testShouldGetCacheEntry(): void { $requestUri = 'api/shop/devices'; $requestGetData = ['limit' => 10]; @@ -152,52 +139,43 @@ public function shouldGetCacheEntry() $identifier = $this->buildIdentifier($requestUri, $requestGetData); $this->frontendCacheMock->expects(self::once())->method('get')->with($identifier)->willReturn($response); - self::assertEquals($response, $this->cache->getCacheEntry($requestUri, $requestGetData)); + $this->assertSame($response, $this->cache->getCacheEntry($requestUri, $requestGetData)); } - /** - * @test - */ - public function shouldHaveCacheEntry() + public function testShouldHaveCacheEntry(): void { $requestUri = 'api/shop/devices'; $requestGetData = ['limit' => 10]; $identifier = $this->buildIdentifier($requestUri, $requestGetData); $this->frontendCacheMock->expects(self::once())->method('has')->with($identifier)->willReturn(true); - self::assertTrue($this->cache->hasCacheEntry($requestUri, $requestGetData)); + $this->assertTrue($this->cache->hasCacheEntry($requestUri, $requestGetData)); } - /** - * @test - */ - public function shouldHaveNoCacheEntry() + public function testShouldHaveNoCacheEntry(): void { $requestUri = 'api/shop/devices'; $requestGetData = ['limit' => 10]; $identifier = $this->buildIdentifier($requestUri, $requestGetData); - $this->frontendCacheMock->expects($this->once())->method('has')->with($identifier)->willReturn(false); - self::assertFalse($this->cache->hasCacheEntry($requestUri, $requestGetData)); + $this->frontendCacheMock->expects($this->once()) + ->method('has') + ->with($identifier) + ->willReturn(false); + $this->assertFalse($this->cache->hasCacheEntry($requestUri, $requestGetData)); } - /** - * @test - */ - public function shouldFlushCacheByTag() + public function testShouldFlushCacheByTag(): void { $tag = 'tag_a'; - $this->frontendCacheMock->expects($this->once())->method('flushByTag')->with($tag); + $this->frontendCacheMock->expects($this->once()) + ->method('flushByTag') + ->with($tag); $this->cache->flushByTag($tag); } - /** - * @param string $requestUri - * @param array $getData - * @return string - */ - private function buildIdentifier($requestUri, array $getData) + private function buildIdentifier(string $requestUri, array $getData): string { return md5($requestUri . serialize($getData)); } diff --git a/composer.json b/composer.json index d766d4a..7104f4b 100644 --- a/composer.json +++ b/composer.json @@ -23,14 +23,14 @@ "cweagans/composer-patches": "^1.7" }, "require-dev": { - "nimut/testing-framework": "^6.0", + "typo3/testing-framework": "^7.0.4", "phpspec/prophecy-phpunit": "^2.0", "phpunit/phpcov": "*", "phpcompatibility/php-compatibility": "^9.3", - "phpstan/phpstan": "0.12.88", - "rector/rector": "0.11.20", - "symplify/easy-coding-standard": "9.3.26", - "symplify/phpstan-rules": "9.3.26" + "phpstan/phpstan": "^1.10", + "rector/rector": "^1.0", + "symplify/easy-coding-standard": "12.1.14", + "symplify/phpstan-rules": "12.4.8" }, "keywords": [ "TYPO3", @@ -65,7 +65,7 @@ ], "test:unit": [ "[ -e .Build/bin/phpunit ] || composer update", - "TYPO3_PATH_ROOT=.Build/Web .Build/bin/phpunit -c .Build/vendor/nimut/testing-framework/res/Configuration/UnitTests.xml Tests/Unit" + "TYPO3_PATH_ROOT=.Build/Web .Build/bin/phpunit -c .Build/vendor/typo3/testing-framework/Resources/Core/Build/UnitTests.xml Tests/Unit" ], "code-style": [ "[ -e ./.Build/bin/rector ] || composer install", @@ -80,14 +80,17 @@ "./.Build/bin/phpstan analyse -c .code-quality/phpstan.neon --memory-limit=1G" ], "code-analysis--baseline": [ - "./.Build/bin/phpstan analyse -c .code-quality/phpstan.neon --memory-limit=1G --generate-baseline" + "./.Build/bin/phpstan analyse -c .code-quality/phpstan.neon --memory-limit=1G --generate-baseline --allow-empty-baseline" ], "code-compatibility": [ "[ -e ./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs ] || composer install", "[ -d ./reports/php_checkstyle ] || mkdir -p reports/php_checkstyle/", "./.code-quality/configure-checkstyle.sh", - "./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs -d memory_limit=1G --standard=PHPCompatibility --colors --ignore=*/.Build/* -p . --runtime-set testVersion 7.4", - "./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs -d memory_limit=1G --standard=PHPCompatibility --colors --ignore=*/.Build/* -p . --runtime-set testVersion 8.0" + "./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs -d memory_limit=1G --standard=PHPCompatibility --colors --ignore=*/.Build/*,*.min.js -p . --runtime-set testVersion 7.4", + "./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs -d memory_limit=1G --standard=PHPCompatibility --colors --ignore=*/.Build/*,*.min.js -p . --runtime-set testVersion 8.0", + "./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs -d memory_limit=1G --standard=PHPCompatibility --colors --ignore=*/.Build/*,*.min.js -p . --runtime-set testVersion 8.1", + "./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs -d memory_limit=1G --standard=PHPCompatibility --colors --ignore=*/.Build/*,*.min.js -p . --runtime-set testVersion 8.2", + "./.Build/vendor/symplify/easy-coding-standard/vendor/squizlabs/php_codesniffer/bin/phpcs -d memory_limit=1G --standard=PHPCompatibility --colors --ignore=*/.Build/*,*.min.js -p . --runtime-set testVersion 8.3" ], "code-check-pipeline": [ "@composer code-style",