From f2ca0bb9dd58e11faa6a316c047ced7e045f71bc Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sat, 6 Apr 2024 17:49:56 +0200 Subject: [PATCH] setup phpstan and use php-cs-fixer * work around ConstraintValidatorTestCase --- .github/workflows/static.yml | 48 ++++++++++ .gitignore | 3 +- .php-cs-fixer.dist.php | 19 ++++ .styleci.yml | 31 ------ composer.json | 6 ++ phpstan.neon.dist | 15 +++ .../CmfRoutingExtension.php | 3 - src/Doctrine/Orm/ContentRepository.php | 2 - src/Doctrine/Orm/RedirectRoute.php | 9 -- src/Doctrine/Orm/Route.php | 3 - src/Doctrine/Orm/RouteProvider.php | 17 +--- src/Doctrine/Phpcr/ContentRepository.php | 20 ++-- src/Doctrine/Phpcr/PrefixCandidates.php | 7 +- src/Doctrine/Phpcr/RedirectRoute.php | 34 ------- src/Doctrine/Phpcr/Route.php | 28 ------ src/Doctrine/Phpcr/RouteProvider.php | 21 +++-- src/Form/Type/RouteTypeType.php | 9 -- src/Model/RedirectRoute.php | 28 +----- src/Model/Route.php | 15 +-- src/Routing/DynamicRouter.php | 2 +- src/Routing/RedirectableRequestMatcher.php | 7 +- .../RouteDefaultsTwigValidator.php | 5 +- .../App/DataFixtures/Phpcr/LoadRouteData.php | 4 + tests/Fixtures/App/Document/Content.php | 2 +- tests/Fixtures/App/Kernel.php | 7 +- tests/Functional/BaseTestCase.php | 19 +--- .../Controller/RedirectControllerTest.php | 2 +- tests/Functional/Doctrine/Orm/OrmTestCase.php | 9 +- .../Doctrine/Orm/RedirectRouteTest.php | 4 +- .../Doctrine/Orm/RouteProviderTest.php | 9 +- .../Doctrine/Phpcr/RedirectRouteTest.php | 12 +-- .../Doctrine/Phpcr/RouteProviderTest.php | 21 ++--- tests/Functional/Doctrine/Phpcr/RouteTest.php | 4 +- .../Functional/Routing/DynamicRouterTest.php | 49 +++++----- .../CmfRoutingExtensionTest.php | 20 ++-- .../Compiler/SetRouterPassTest.php | 4 +- .../Compiler/TemplatingValidatorPassTest.php | 75 --------------- .../Compiler/ValidationPassTest.php | 4 +- .../DependencyInjection/ConfigurationTest.php | 4 +- .../DependencyInjection/XmlSchemaTest.php | 13 ++- .../Doctrine/Orm/ContentRepositoryTest.php | 38 +++----- tests/Unit/Doctrine/Orm/RouteProviderTest.php | 42 ++------- .../Doctrine/Phpcr/ContentRepositoryTest.php | 17 ++-- .../Doctrine/Phpcr/IdPrefixListenerTest.php | 15 +-- .../Doctrine/Phpcr/LocaleListenerTest.php | 18 +--- .../Unit/Doctrine/Phpcr/RouteProviderTest.php | 44 ++------- tests/Unit/Doctrine/Phpcr/RouteTest.php | 6 +- tests/Unit/Form/Type/RouteTypeTypeTest.php | 11 +-- tests/Unit/Routing/DynamicRouterTest.php | 82 ++++------------ .../RedirectableRequestMatcherTest.php | 41 +++----- .../RouteDefaultsTemplatingValidatorTest.php | 38 -------- .../RouteDefaultsTwigValidatorTest.php | 70 +++++++++++++- .../RouteDefaultsValidatorTest.php | 94 ------------------- 53 files changed, 375 insertions(+), 735 deletions(-) create mode 100644 .github/workflows/static.yml create mode 100644 .php-cs-fixer.dist.php delete mode 100644 .styleci.yml create mode 100644 phpstan.neon.dist delete mode 100644 tests/Unit/DependencyInjection/Compiler/TemplatingValidatorPassTest.php delete mode 100644 tests/Unit/Validator/Constraints/RouteDefaultsTemplatingValidatorTest.php delete mode 100644 tests/Unit/Validator/Constraints/RouteDefaultsValidatorTest.php diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml new file mode 100644 index 00000000..4146017b --- /dev/null +++ b/.github/workflows/static.yml @@ -0,0 +1,48 @@ +name: Static analysis + +on: + push: + branches: + - '[0-9]+.x' + - '[0-9]+.[0-9]+' + - '[0-9]+.[0-9]+.x' + pull_request: + +jobs: + phpstan: + name: PHPStan + runs-on: ubuntu-latest + + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + extensions: "curl,dom,json,xml,dom" + coverage: none + + - name: Checkout code + uses: actions/checkout@v4 + + # have to install phpstan ourselves here, the phpstan-ga fails at composer install with weird errors + # composer require --no-update jackalope/jackalope-doctrine-dbal jackalope/jackalope-jackrabbit phpstan/phpstan + - name: Install phpstan + run: | + + composer update + + - name: PHPStan + run: vendor/bin/phpstan analyze --no-progress + + php-cs-fixer: + name: PHP-CS-Fixer + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: PHP-CS-Fixer + uses: docker://oskarstark/php-cs-fixer-ga + with: + args: --dry-run --diff diff --git a/.gitignore b/.gitignore index 6e7a8532..0b4c0b10 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ phpunit.xml composer.lock vendor tests/Fixtures/App/var/ -.phpunit.result.cache +.phpunit.result.cache +.php-cs-fixer.cache diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..a8e3ac3a --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,19 @@ +in(__DIR__.'/src') + ->in(__DIR__.'/tests') + ->exclude('tests/Fixtures/App/var/') + ->name('*.php') +; + +$config = new PhpCsFixer\Config(); + +return $config + ->setRiskyAllowed(true) + ->setRules([ + '@Symfony' => true, + 'single_line_throw' => false, + ]) + ->setFinder($finder) +; diff --git a/.styleci.yml b/.styleci.yml deleted file mode 100644 index 793ac737..00000000 --- a/.styleci.yml +++ /dev/null @@ -1,31 +0,0 @@ -####################################################### -# DO NOT EDIT THIS FILE! # -# # -# It's auto-generated by symfony-cmf/dev-kit package. # -####################################################### - -############################################################################ -# This file is part of the Symfony CMF package. # -# # -# (c) Symfony CMF i # -# # -# For the full copyright and license information, please view the LICENSE # -# file that was distributed with this source code. # -############################################################################ - - -preset: symfony - -risky: true - -enabled: - - combine_consecutive_unsets - - no_php4_constructor - - no_useless_else - - ordered_use - - strict - - php_unit_construct - -disabled: - - single_line_class_definition - - single_line_throw diff --git a/composer.json b/composer.json index 47bc78ef..94a8ad27 100644 --- a/composer.json +++ b/composer.json @@ -26,6 +26,11 @@ "doctrine/phpcr-bundle": "^3.0", "doctrine/phpcr-odm": "^2.0", "jackalope/jackalope-doctrine-dbal": "^2.0", + "phpstan/phpstan": "^1.10", + "phpstan/phpstan-doctrine": "^1.3", + "phpstan/phpstan-phpunit": "^1.3", + "phpstan/phpstan-symfony": "^1.3", + "phpunit/phpunit": "^9.5.28", "matthiasnoback/symfony-dependency-injection-test": "^4.1.0 || ^5.1.0", "matthiasnoback/symfony-config-test": "^4.1.0 || ^5.1.0", "symfony/phpunit-bridge": "^7.0.3", @@ -47,6 +52,7 @@ "conflict": { "doctrine/common": "<3.1.1", "doctrine/persistence": "<1.3.0", + "doctrine/phpcr-odm": "<2.0", "symfony/doctrine-bridge": "<6.4.0", "symfony/security-core": "<6.4.0" }, diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 00000000..22e66521 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,15 @@ +includes: + - vendor/phpstan/phpstan-doctrine/extension.neon + - vendor/phpstan/phpstan-doctrine/rules.neon + - vendor/phpstan/phpstan-phpunit/extension.neon + - vendor/phpstan/phpstan-symfony/extension.neon + - vendor/phpstan/phpstan-symfony/rules.neon +parameters: + level: 2 + paths: + - src/ + - tests/ + excludePaths: + - tests/Fixtures/App/var/ + - tests/Fixtures/App/config/ + - tests/Fixtures/fixtures/config/ diff --git a/src/DependencyInjection/CmfRoutingExtension.php b/src/DependencyInjection/CmfRoutingExtension.php index 5d015913..b03db9cb 100644 --- a/src/DependencyInjection/CmfRoutingExtension.php +++ b/src/DependencyInjection/CmfRoutingExtension.php @@ -27,9 +27,6 @@ */ final class CmfRoutingExtension extends Extension { - /** - * {@inheritdoc} - */ public function load(array $configs, ContainerBuilder $container): void { $config = $this->processConfiguration(new Configuration(), $configs); diff --git a/src/Doctrine/Orm/ContentRepository.php b/src/Doctrine/Orm/ContentRepository.php index ef629000..ba0b02c1 100644 --- a/src/Doctrine/Orm/ContentRepository.php +++ b/src/Doctrine/Orm/ContentRepository.php @@ -37,8 +37,6 @@ protected function getModelAndId(string $identifier): array } /** - * {@inheritdoc} - * * @param string $id The ID contains both model name and id, separated by a colon */ public function findById(mixed $id): ?object diff --git a/src/Doctrine/Orm/RedirectRoute.php b/src/Doctrine/Orm/RedirectRoute.php index 3bb5f210..7c5b07b4 100644 --- a/src/Doctrine/Orm/RedirectRoute.php +++ b/src/Doctrine/Orm/RedirectRoute.php @@ -52,9 +52,6 @@ public function setParameters(array $parameters): void $this->serialisedParameters = json_encode($parameters, \JSON_THROW_ON_ERROR); } - /** - * {@inheritdoc} - */ public function getParameters(): array { if (!isset($this->serialisedParameters)) { @@ -65,9 +62,6 @@ public function getParameters(): array return \is_array($params) ? $params : []; } - /** - * {@inheritdoc} - */ public function getPath(): string { $pattern = parent::getPath(); @@ -78,9 +72,6 @@ public function getPath(): string return $pattern; } - /** - * {@inheritdoc} - */ protected function isBooleanOption(string $name): bool { return 'add_trailing_slash' === $name || parent::isBooleanOption($name); diff --git a/src/Doctrine/Orm/Route.php b/src/Doctrine/Orm/Route.php index eb1a4e75..eb93dc73 100644 --- a/src/Doctrine/Orm/Route.php +++ b/src/Doctrine/Orm/Route.php @@ -58,9 +58,6 @@ public function getPosition(): int return $this->position; } - /** - * {@inheritdoc} - */ public function getRouteKey(): string { return $this->getName(); diff --git a/src/Doctrine/Orm/RouteProvider.php b/src/Doctrine/Orm/RouteProvider.php index e084857b..743970c8 100644 --- a/src/Doctrine/Orm/RouteProvider.php +++ b/src/Doctrine/Orm/RouteProvider.php @@ -41,9 +41,6 @@ public function __construct(ManagerRegistry $managerRegistry, CandidatesInterfac $this->candidatesStrategy = $candidatesStrategy; } - /** - * {@inheritdoc} - */ public function getRouteCollectionForRequest(Request $request): RouteCollection { $collection = new RouteCollection(); @@ -52,8 +49,8 @@ public function getRouteCollectionForRequest(Request $request): RouteCollection if (0 === \count($candidates)) { return $collection; } - $routes = $this->getRouteRepository()->findByStaticPrefix($candidates, ['position' => 'ASC']); - /** @var $route Route */ + $routes = $this->getRouteRepository()->findByStaticPrefix($candidates, ['position' => 'ASC']); /* @phpstan-ignore-line */ + /** @var Route $route */ foreach ($routes as $route) { $collection->add($route->getName(), $route); } @@ -61,9 +58,6 @@ public function getRouteCollectionForRequest(Request $request): RouteCollection return $collection; } - /** - * {@inheritdoc} - */ public function getRouteByName($name): SymfonyRoute { if (!$this->candidatesStrategy->isCandidate($name)) { @@ -78,9 +72,6 @@ public function getRouteByName($name): SymfonyRoute return $route; } - /** - * {@inheritdoc} - */ public function getRoutesByNames($names = null): array { if (null === $names) { @@ -90,7 +81,7 @@ public function getRoutesByNames($names = null): array try { return $this->getRouteRepository()->findBy([], null, $this->routeCollectionLimit ?: null); - } catch (TableNotFoundException $e) { + } catch (TableNotFoundException) { return []; } } @@ -100,7 +91,7 @@ public function getRoutesByNames($names = null): array // TODO: if we do findByName with multivalue, we need to filter with isCandidate afterwards try { $routes[] = $this->getRouteByName($name); - } catch (RouteNotFoundException $e) { + } catch (RouteNotFoundException) { // not found } } diff --git a/src/Doctrine/Phpcr/ContentRepository.php b/src/Doctrine/Phpcr/ContentRepository.php index 834cc6ed..02a712c4 100644 --- a/src/Doctrine/Phpcr/ContentRepository.php +++ b/src/Doctrine/Phpcr/ContentRepository.php @@ -11,6 +11,7 @@ namespace Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr; +use Doctrine\ODM\PHPCR\DocumentManagerInterface; use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\DoctrineProvider; use Symfony\Cmf\Component\Routing\ContentRepositoryInterface; @@ -25,17 +26,11 @@ */ class ContentRepository extends DoctrineProvider implements ContentRepositoryInterface { - /** - * {@inheritdoc} - */ public function findById($id): ?object { return $this->getObjectManager()->find(null, $id); } - /** - * {@inheritdoc} - */ public function getContentId($content): ?string { if (!\is_object($content)) { @@ -48,4 +43,17 @@ public function getContentId($content): ?string return null; } } + + /** + * Make sure the manager is a PHPCR-ODM manager. + */ + protected function getObjectManager(): DocumentManagerInterface + { + $dm = parent::getObjectManager(); + if (!$dm instanceof DocumentManagerInterface) { + throw new \LogicException(sprintf('Expected %s, got %s', DocumentManagerInterface::class, get_class($dm))); + } + + return $dm; + } } diff --git a/src/Doctrine/Phpcr/PrefixCandidates.php b/src/Doctrine/Phpcr/PrefixCandidates.php index 7b17f1bc..afd9303d 100644 --- a/src/Doctrine/Phpcr/PrefixCandidates.php +++ b/src/Doctrine/Phpcr/PrefixCandidates.php @@ -47,7 +47,7 @@ final class PrefixCandidates extends Candidates * is using * @param int $limit Limit to candidates generated per prefix */ - public function __construct(array $prefixes, array $locales = [], ManagerRegistry $doctrine = null, int $limit = 20) + public function __construct(array $prefixes, array $locales = [], ?ManagerRegistry $doctrine = null, int $limit = 20) { parent::__construct($locales, $limit); $this->setPrefixes($prefixes); @@ -74,8 +74,6 @@ public function isCandidate($name): bool } /** - * {@inheritdoc} - * * @param QueryBuilder $queryBuilder */ public function restrictQuery($queryBuilder): void @@ -91,9 +89,6 @@ public function restrictQuery($queryBuilder): void } } - /** - * {@inheritdoc} - */ public function getCandidates(Request $request): array { $candidates = []; diff --git a/src/Doctrine/Phpcr/RedirectRoute.php b/src/Doctrine/Phpcr/RedirectRoute.php index 64f08d15..c9ec3d0b 100644 --- a/src/Doctrine/Phpcr/RedirectRoute.php +++ b/src/Doctrine/Phpcr/RedirectRoute.php @@ -69,36 +69,11 @@ public function setParentDocument($parent): static return $this; } - /** - * {@inheritdoc} - */ public function getParentDocument(): ?object { return $this->parent; } - /** - * @deprecated For BC with the PHPCR-ODM 1.4 HierarchyInterface - * @see setParentDocument - */ - public function setParent($parent) - { - @trigger_error('The '.__METHOD__.'() method is deprecated and will be removed in version 4.0. Use setParentDocument() instead.', \E_USER_DEPRECATED); - - return $this->setParentDocument($parent); - } - - /** - * @deprecated For BC with the PHPCR-ODM 1.4 HierarchyInterface - * @see getParentDocument - */ - public function getParent() - { - @trigger_error('The '.__METHOD__.'() method is deprecated and will be removed in version 4.0. Use getParentDocument() instead.', \E_USER_DEPRECATED); - - return $this->getParentDocument(); - } - /** * Rename a route by setting its new name. * @@ -160,9 +135,6 @@ public function getPrefix(): string return $this->idPrefix; } - /** - * {@inheritdoc} - */ public function setPrefix(string $prefix): static { $this->idPrefix = $prefix; @@ -206,9 +178,6 @@ public function generateStaticPrefix(string $id, string $idPrefix): string return $url; } - /** - * {@inheritdoc} - */ public function getPath(): string { $pattern = parent::getPath(); @@ -240,9 +209,6 @@ public function getRouteChildren(): array return $children; } - /** - * {@inheritdoc} - */ protected function isBooleanOption(string $name): bool { return 'add_trailing_slash' === $name || parent::isBooleanOption($name); diff --git a/src/Doctrine/Phpcr/Route.php b/src/Doctrine/Phpcr/Route.php index 5a50ffa1..d01256ab 100644 --- a/src/Doctrine/Phpcr/Route.php +++ b/src/Doctrine/Phpcr/Route.php @@ -89,28 +89,6 @@ public function getParentDocument(): object return $this->parent; } - /** - * @deprecated For BC with the PHPCR-ODM 1.4 HierarchyInterface - * @see setParentDocument - */ - public function setParent($parent) - { - @trigger_error('The '.__METHOD__.'() method is deprecated and will be removed in version 4.0. Use setParentDocument() instead.', \E_USER_DEPRECATED); - - return $this->setParentDocument($parent); - } - - /** - * @deprecated For BC with the PHPCR-ODM 1.4 HierarchyInterface - * @see getParentDocument - */ - public function getParent() - { - @trigger_error('The '.__METHOD__.'() method is deprecated and will be removed in version 4.0. Use getParentDocument() instead.', \E_USER_DEPRECATED); - - return $this->getParentDocument(); - } - /** * Rename a route by setting its new name. * @@ -172,9 +150,6 @@ public function getPrefix(): ?string return $this->idPrefix; } - /** - * {@inheritdoc} - */ public function setPrefix(string $prefix): static { $this->idPrefix = $prefix; @@ -264,9 +239,6 @@ public function getChildren(): Collection return $this->children; } - /** - * {@inheritdoc} - */ protected function isBooleanOption(string $name): bool { return 'add_trailing_slash' === $name || parent::isBooleanOption($name); diff --git a/src/Doctrine/Phpcr/RouteProvider.php b/src/Doctrine/Phpcr/RouteProvider.php index 4cabdc87..e19099f7 100644 --- a/src/Doctrine/Phpcr/RouteProvider.php +++ b/src/Doctrine/Phpcr/RouteProvider.php @@ -13,6 +13,7 @@ use Doctrine\DBAL\Exception\TableNotFoundException; use Doctrine\ODM\PHPCR\DocumentManager; +use Doctrine\ODM\PHPCR\DocumentManagerInterface; use Doctrine\Persistence\ManagerRegistry; use PHPCR\RepositoryException; use PHPCR\Util\UUIDHelper; @@ -44,7 +45,7 @@ public function __construct( ManagerRegistry $managerRegistry, CandidatesInterface $candidatesStrategy, ?string $className = null, - LoggerInterface $logger = null + ?LoggerInterface $logger = null ) { parent::__construct($managerRegistry, $className); $this->candidatesStrategy = $candidatesStrategy; @@ -85,7 +86,6 @@ public function getRouteCollectionForRequest(Request $request): RouteCollection } try { - /** @var $dm DocumentManager */ $dm = $this->getObjectManager(); $routes = $dm->findMany($this->className, $candidates); // filter for valid route objects @@ -102,8 +102,6 @@ public function getRouteCollectionForRequest(Request $request): RouteCollection } /** - * {@inheritdoc} - * * @param string $name The absolute path or uuid of the Route document */ public function getRouteByName(string $name): SymfonyRoute @@ -151,7 +149,6 @@ private function getAllRoutes(): iterable } try { - /** @var $dm DocumentManager */ $dm = $this->getObjectManager(); } catch (RepositoryException $e) { // special case: there is not even a database existing. this means there are no routes. @@ -192,7 +189,6 @@ public function getRoutesByNames(?array $names = null): iterable return []; } - /** @var $dm DocumentManager */ $dm = $this->getObjectManager(); $documents = $dm->findMany($this->className, $candidates); foreach ($documents as $key => $document) { @@ -210,4 +206,17 @@ public function getRoutesByNames(?array $names = null): iterable return $documents; } + + /** + * Make sure the manager is a PHPCR-ODM manager. + */ + protected function getObjectManager(): DocumentManagerInterface + { + $dm = parent::getObjectManager(); + if (!$dm instanceof DocumentManagerInterface) { + throw new \LogicException(sprintf('Expected %s, got %s', DocumentManagerInterface::class, get_class($dm))); + } + + return $dm; + } } diff --git a/src/Form/Type/RouteTypeType.php b/src/Form/Type/RouteTypeType.php index 4ab01217..8cd09c8d 100644 --- a/src/Form/Type/RouteTypeType.php +++ b/src/Form/Type/RouteTypeType.php @@ -19,9 +19,6 @@ class RouteTypeType extends AbstractType { protected array $routeTypes = []; - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $choices = []; @@ -43,17 +40,11 @@ public function addRouteType(string $type): void $this->routeTypes[$type] = $type; } - /** - * {@inheritdoc} - */ public function getParent(): string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'cmf_routing_route_type'; diff --git a/src/Model/RedirectRoute.php b/src/Model/RedirectRoute.php index 41b1ab27..aa040106 100644 --- a/src/Model/RedirectRoute.php +++ b/src/Model/RedirectRoute.php @@ -11,13 +11,9 @@ namespace Symfony\Cmf\Bundle\RoutingBundle\Model; -use LogicException; use Symfony\Cmf\Component\Routing\RedirectRouteInterface; use Symfony\Component\Routing\Route as SymfonyRoute; -/** - * {@inheritdoc} - */ class RedirectRoute extends Route implements RedirectRouteInterface { /** @@ -47,16 +43,13 @@ class RedirectRoute extends Route implements RedirectRouteInterface * as route content for the redirection controller to have the redirect route * object as content. * - * @throws LogicException + * @throws \LogicException */ - public function setContent($document): static + public function setContent(object $document): static { - throw new LogicException('Do not set a content for the redirect route. It is its own content.'); + throw new \LogicException('Do not set a content for the redirect route. It is its own content.'); } - /** - * {@inheritdoc} - */ public function getContent(): static { return $this; @@ -71,9 +64,6 @@ public function setRouteTarget(?SymfonyRoute $document): void $this->routeTarget = $document; } - /** - * {@inheritdoc} - */ public function getRouteTarget(): ?SymfonyRoute { return $this->routeTarget; @@ -87,9 +77,6 @@ public function setRouteName(?string $routeName): void $this->routeName = $routeName; } - /** - * {@inheritdoc} - */ public function getRouteName(): ?string { return $this->routeName; @@ -104,9 +91,6 @@ public function setPermanent(bool $permanent): void $this->permanent = $permanent; } - /** - * {@inheritdoc} - */ public function isPermanent(): bool { return $this->permanent; @@ -123,9 +107,6 @@ public function setParameters(array $parameters): void $this->parameters = $parameters; } - /** - * {@inheritdoc} - */ public function getParameters(): array { return $this->parameters; @@ -139,9 +120,6 @@ public function setUri(?string $uri): void $this->uri = $uri; } - /** - * {@inheritdoc} - */ public function getUri(): ?string { return $this->uri; diff --git a/src/Model/Route.php b/src/Model/Route.php index cc7378f2..bc58932e 100644 --- a/src/Model/Route.php +++ b/src/Model/Route.php @@ -25,8 +25,6 @@ class Route extends SymfonyRoute implements RouteObjectInterface { /** * Unique id of this route. - * - * @var string|int|null */ protected $id; @@ -37,7 +35,7 @@ class Route extends SymfonyRoute implements RouteObjectInterface /** * Part of the URL that does not have parameters and thus can be used to - * naivly guess candidate routes. + * naively guess candidate routes. * * Note that this field is not used by PHPCR-ODM */ @@ -76,12 +74,9 @@ public function __construct(array $options = []) } } - /** - * {@inheritdoc} - */ public function getRouteKey(): string { - return (string) $this->getId(); + return $this->getId(); } /** @@ -117,9 +112,6 @@ public function setContent(object $object): static return $this; } - /** - * {@inheritdoc} - */ public function getContent(): ?object { return $this->content; @@ -185,9 +177,6 @@ protected function isBooleanOption(string $name): bool return \in_array($name, ['add_format_pattern', 'add_locale_pattern']); } - /** - * {@inheritdoc} - */ public function getPath(): string { $pattern = ''; diff --git a/src/Routing/DynamicRouter.php b/src/Routing/DynamicRouter.php index 350654bf..88f19693 100644 --- a/src/Routing/DynamicRouter.php +++ b/src/Routing/DynamicRouter.php @@ -79,7 +79,7 @@ public function matchRequest(Request $request): array * * @return array the updated defaults to return for this match */ - protected function cleanDefaults(array $defaults, Request $request = null): array + protected function cleanDefaults(array $defaults, ?Request $request = null): array { if (null === $request) { $request = $this->getRequest(); diff --git a/src/Routing/RedirectableRequestMatcher.php b/src/Routing/RedirectableRequestMatcher.php index 6136d027..ab527737 100644 --- a/src/Routing/RedirectableRequestMatcher.php +++ b/src/Routing/RedirectableRequestMatcher.php @@ -11,6 +11,7 @@ namespace Symfony\Cmf\Bundle\RoutingBundle\Routing; +use Symfony\Bundle\FrameworkBundle\Controller\RedirectController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Exception\ExceptionInterface; use Symfony\Component\Routing\Exception\ResourceNotFoundException; @@ -68,10 +69,10 @@ public function matchRequest(Request $request): array } } - private function redirect(string $path, string $route, string $scheme = null): array + private function redirect(string $path, string $route, ?string $scheme = null): array { return [ - '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction', + '_controller' => RedirectController::class.'::urlRedirectAction', 'path' => $path, 'permanent' => true, 'scheme' => $scheme, @@ -82,7 +83,7 @@ private function redirect(string $path, string $route, string $scheme = null): a } /** - * Return a duplicated version of $request with the new $newpath as request_uri. + * Return a duplicated version of $request with the new $newPath as request_uri. */ private function rebuildRequest(Request $request, string $newPath): Request { diff --git a/src/Validator/Constraints/RouteDefaultsTwigValidator.php b/src/Validator/Constraints/RouteDefaultsTwigValidator.php index 8742e0d6..f53e7e93 100644 --- a/src/Validator/Constraints/RouteDefaultsTwigValidator.php +++ b/src/Validator/Constraints/RouteDefaultsTwigValidator.php @@ -31,8 +31,11 @@ public function __construct(ControllerResolverInterface $controllerResolver, ?Lo $this->twig = $twig; } - public function validate($defaults, Constraint $constraint) + public function validate(mixed $defaults, Constraint $constraint): void { + if (!$constraint instanceof RouteDefaults) { + throw new \InvalidArgumentException(sprintf('Expected %s, got %s', RouteDefaults::class, get_class($constraint))); + } if (\array_key_exists('_controller', $defaults) && null !== $defaults['_controller']) { $controller = $defaults['_controller']; diff --git a/tests/Fixtures/App/DataFixtures/Phpcr/LoadRouteData.php b/tests/Fixtures/App/DataFixtures/Phpcr/LoadRouteData.php index 2ad83ea8..756ff05c 100644 --- a/tests/Fixtures/App/DataFixtures/Phpcr/LoadRouteData.php +++ b/tests/Fixtures/App/DataFixtures/Phpcr/LoadRouteData.php @@ -13,6 +13,7 @@ use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\ODM\PHPCR\Document\Generic; +use Doctrine\ODM\PHPCR\DocumentManagerInterface; use Doctrine\Persistence\ObjectManager; use PHPCR\Util\NodeHelper; use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\RedirectRoute; @@ -22,6 +23,9 @@ class LoadRouteData implements FixtureInterface { public function load(ObjectManager $manager) { + if (!$manager instanceof DocumentManagerInterface) { + throw new \InvalidArgumentException(sprintf('Expected %s, got %s', DocumentManagerInterface::class, get_class($manager))); + } NodeHelper::createPath($manager->getPhpcrSession(), '/test'); $root = $manager->find(null, '/test'); diff --git a/tests/Fixtures/App/Document/Content.php b/tests/Fixtures/App/Document/Content.php index c9eab724..bbba34b4 100644 --- a/tests/Fixtures/App/Document/Content.php +++ b/tests/Fixtures/App/Document/Content.php @@ -22,7 +22,7 @@ class Content #[PHPCRODM\ParentDocument] private $parent; - #[PHPCRODM\NodeName] + #[PHPCRODM\Nodename] private $name; #[PHPCRODM\Field(type: 'string')] diff --git a/tests/Fixtures/App/Kernel.php b/tests/Fixtures/App/Kernel.php index 8dbc25a2..14498e8a 100644 --- a/tests/Fixtures/App/Kernel.php +++ b/tests/Fixtures/App/Kernel.php @@ -11,6 +11,7 @@ namespace Symfony\Cmf\Bundle\RoutingBundle\Tests\Fixtures\App; +use Symfony\Cmf\Bundle\ResourceBundle\CmfResourceBundle; use Symfony\Cmf\Bundle\ResourceRestBundle\CmfResourceRestBundle; use Symfony\Cmf\Component\Testing\HttpKernel\TestKernel; use Symfony\Component\Config\Loader\LoaderInterface; @@ -31,10 +32,10 @@ public function configure(): void $this->registerConfiguredBundles(); - if (class_exists(CmfResourceRestBundle::class)) { + if (class_exists(CmfResourceBundle::class) && class_exists(CmfResourceRestBundle::class)) { $this->addBundles([ - new \Symfony\Cmf\Bundle\ResourceBundle\CmfResourceBundle(), - new \Symfony\Cmf\Bundle\ResourceRestBundle\CmfResourceRestBundle(), + new CmfResourceBundle(), + new CmfResourceRestBundle(), ]); } } diff --git a/tests/Functional/BaseTestCase.php b/tests/Functional/BaseTestCase.php index ba50b502..804c6886 100644 --- a/tests/Functional/BaseTestCase.php +++ b/tests/Functional/BaseTestCase.php @@ -19,20 +19,12 @@ class BaseTestCase extends ComponentBaseTestCase { - /** - * @return DocumentManagerInterface - */ - protected function getDm() + protected function getDm(): DocumentManagerInterface { return $this->db('PHPCR')->getOm(); } - /** - * @param string $path - * - * @return Route - */ - protected function createRoute($path) + protected function createRoute(string $path): Route { $parentPath = PathHelper::getParentPath($path); $parent = $this->getDm()->find(null, $parentPath); @@ -45,12 +37,7 @@ protected function createRoute($path) return $route; } - /** - * @param string $path - * - * @return Content - */ - protected function createContent($path = '/test/content') + protected function createContent(string $path = '/test/content'): Content { $content = new Content(); $content->setId($path); diff --git a/tests/Functional/Controller/RedirectControllerTest.php b/tests/Functional/Controller/RedirectControllerTest.php index cb531652..26486b12 100644 --- a/tests/Functional/Controller/RedirectControllerTest.php +++ b/tests/Functional/Controller/RedirectControllerTest.php @@ -22,7 +22,7 @@ final class RedirectControllerTest extends BaseTestCase private RedirectController $controller; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->db('PHPCR')->createTestNode(); diff --git a/tests/Functional/Doctrine/Orm/OrmTestCase.php b/tests/Functional/Doctrine/Orm/OrmTestCase.php index 4c3cdfab..2fbc583a 100644 --- a/tests/Functional/Doctrine/Orm/OrmTestCase.php +++ b/tests/Functional/Doctrine/Orm/OrmTestCase.php @@ -11,6 +11,9 @@ namespace Symfony\Cmf\Bundle\RoutingBundle\Tests\Functional\Doctrine\Orm; +use Doctrine\ODM\PHPCR\DocumentManager; +use Doctrine\ODM\PHPCR\DocumentManagerInterface; +use Doctrine\Persistence\ObjectManager; use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm\Route; use Symfony\Cmf\Component\Testing\Functional\BaseTestCase as ComponentBaseTestCase; @@ -23,7 +26,7 @@ protected static function getKernelConfiguration(): array ]; } - protected function clearDb($model) + protected function clearDb($model): void { if (\is_array($model)) { foreach ($model as $singleModel) { @@ -40,12 +43,12 @@ protected function clearDb($model) $this->getDm()->flush(); } - protected function getDm() + protected function getDm(): DocumentManager|ObjectManager|DocumentManagerInterface { return $this->db('ORM')->getOm(); } - protected function createRoute($name, $path) + protected function createRoute($name, $path): Route { // split path in static and variable part preg_match('{^(.*?)(/[^/]*\{.*)?$}', $path, $paths); diff --git a/tests/Functional/Doctrine/Orm/RedirectRouteTest.php b/tests/Functional/Doctrine/Orm/RedirectRouteTest.php index 1e938f68..9a02cfaf 100644 --- a/tests/Functional/Doctrine/Orm/RedirectRouteTest.php +++ b/tests/Functional/Doctrine/Orm/RedirectRouteTest.php @@ -19,13 +19,13 @@ class RedirectRouteTest extends OrmTestCase { private RedirectController $controller; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->clearDb(Route::class); $this->clearDb(RedirectRoute::class); - $this->controller = new RedirectController($this->getContainer()->get('router')); + $this->controller = new RedirectController(self::getContainer()->get('router')); } public function testRedirectDoctrine(): void diff --git a/tests/Functional/Doctrine/Orm/RouteProviderTest.php b/tests/Functional/Doctrine/Orm/RouteProviderTest.php index d2e8c162..be6fc06c 100644 --- a/tests/Functional/Doctrine/Orm/RouteProviderTest.php +++ b/tests/Functional/Doctrine/Orm/RouteProviderTest.php @@ -12,21 +12,22 @@ namespace Symfony\Cmf\Bundle\RoutingBundle\Tests\Functional\Doctrine\Orm; use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm\Route; +use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm\RouteProvider; use Symfony\Component\HttpFoundation\Request; class RouteProviderTest extends OrmTestCase { - private $repository; + private RouteProvider $repository; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->clearDb(Route::class); - $this->repository = $this->getContainer()->get('cmf_routing.route_provider'); + $this->repository = self::getContainer()->get('cmf_routing.route_provider'); } - public function testGetRouteCollectionForRequest() + public function testGetRouteCollectionForRequest(): void { $this->createRoute('route1', '/test'); $this->createRoute('route2', '/test/child'); diff --git a/tests/Functional/Doctrine/Phpcr/RedirectRouteTest.php b/tests/Functional/Doctrine/Phpcr/RedirectRouteTest.php index e663f830..b2bceef6 100644 --- a/tests/Functional/Doctrine/Phpcr/RedirectRouteTest.php +++ b/tests/Functional/Doctrine/Phpcr/RedirectRouteTest.php @@ -14,21 +14,20 @@ use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\RedirectRoute; use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\Route; use Symfony\Cmf\Bundle\RoutingBundle\Tests\Functional\BaseTestCase; -use Symfony\Cmf\Component\Routing\RedirectRouteInterface; use Symfony\Cmf\Component\Routing\RouteReferrersReadInterface; class RedirectRouteTest extends BaseTestCase { - const ROUTE_ROOT = '/test/redirectroute'; + private const ROUTE_ROOT = '/test/redirectroute'; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->db('PHPCR')->createTestNode(); $this->createRoute(self::ROUTE_ROOT); } - public function testRedirectDoctrine() + public function testRedirectDoctrine(): void { $content = $this->createContent(); $root = $this->getDm()->find(null, self::ROUTE_ROOT); @@ -51,15 +50,14 @@ public function testRedirectDoctrine() $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/testroute'); $redirect = $this->getDm()->find(null, self::ROUTE_ROOT.'/redirect'); - $this->assertInstanceOf(RedirectRouteInterface::class, $redirect); + $this->assertInstanceOf(RedirectRoute::class, $redirect); $this->assertSame($redirect, $redirect->getContent()); - $params = $redirect->getParameters(); $this->assertSame($route, $redirect->getRouteTarget()); $defaults = $redirect->getDefaults(); $this->assertEquals(['test' => 'toast'], $defaults); } - public function testSetContent() + public function testSetContent(): void { $content = $this->createMock(RouteReferrersReadInterface::class); $redirect = new RedirectRoute(); diff --git a/tests/Functional/Doctrine/Phpcr/RouteProviderTest.php b/tests/Functional/Doctrine/Phpcr/RouteProviderTest.php index 54931348..7bba5d9a 100644 --- a/tests/Functional/Doctrine/Phpcr/RouteProviderTest.php +++ b/tests/Functional/Doctrine/Phpcr/RouteProviderTest.php @@ -21,20 +21,19 @@ class RouteProviderTest extends BaseTestCase { - const ROUTE_ROOT = '/test/routing'; + private const ROUTE_ROOT = '/test/routing'; - /** @var RouteProvider */ - private $repository; + private RouteProvider $repository; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->db('PHPCR')->createTestNode(); $this->createRoute(self::ROUTE_ROOT); - $this->repository = $this->getContainer()->get('cmf_routing.route_provider'); + $this->repository = self::getContainer()->get('cmf_routing.route_provider'); } - private function buildRoutes() + private function buildRoutes(): void { $root = $this->getDm()->find(null, self::ROUTE_ROOT); @@ -58,7 +57,7 @@ private function buildRoutes() $this->getDm()->clear(); } - public function testGetRouteCollectionForRequest() + public function testGetRouteCollectionForRequest(): void { $this->buildRoutes(); @@ -83,7 +82,7 @@ public function testGetRouteCollectionForRequest() $this->assertNull($iterator->current()->getDefault('_format')); } - public function testGetRouteCollectionForRequestFormat() + public function testGetRouteCollectionForRequestFormat(): void { $this->buildRoutes(); @@ -111,7 +110,7 @@ public function testGetRouteCollectionForRequestFormat() /** * The root route will always be found. */ - public function testGetRouteCollectionForRequestNonPhpcrUrl() + public function testGetRouteCollectionForRequestNonPhpcrUrl(): void { $routes = $this->repository->getRouteCollectionForRequest(Request::create('http://localhost/')); $this->assertInstanceOf(RouteCollection::class, $routes); @@ -126,14 +125,14 @@ public function testGetRouteCollectionForRequestNonPhpcrUrl() /** * The root route will always be found. */ - public function testGetRouteCollectionForRequestColonInUrl() + public function testGetRouteCollectionForRequestColonInUrl(): void { $collection = $this->repository->getRouteCollectionForRequest(Request::create('http://foo.com/jcr:content')); $this->assertInstanceOf(RouteCollection::class, $collection); $this->assertCount(0, $collection); } - public function testGetRoutesByNames() + public function testGetRoutesByNames(): void { $this->buildRoutes(); diff --git a/tests/Functional/Doctrine/Phpcr/RouteTest.php b/tests/Functional/Doctrine/Phpcr/RouteTest.php index db03ea08..a5a8eff7 100644 --- a/tests/Functional/Doctrine/Phpcr/RouteTest.php +++ b/tests/Functional/Doctrine/Phpcr/RouteTest.php @@ -16,9 +16,9 @@ class RouteTest extends BaseTestCase { - const ROUTE_ROOT = '/test/routing'; + private const ROUTE_ROOT = '/test/routing'; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->db('PHPCR')->createTestNode(); diff --git a/tests/Functional/Routing/DynamicRouterTest.php b/tests/Functional/Routing/DynamicRouterTest.php index fd68b03b..a1b45ee2 100644 --- a/tests/Functional/Routing/DynamicRouterTest.php +++ b/tests/Functional/Routing/DynamicRouterTest.php @@ -32,23 +32,18 @@ */ class DynamicRouterTest extends BaseTestCase { - /** - * @var ChainRouter - */ - protected $router; + private ChainRouter $router; - protected $routeNamePrefix; + private const ROUTE_ROOT = '/test/routing'; - const ROUTE_ROOT = '/test/routing'; - - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->db('PHPCR')->createTestNode(); $this->createRoute(self::ROUTE_ROOT); - $this->router = $this->getContainer()->get('router'); + $this->router = self::getContainer()->get('router'); $root = $this->getDm()->find(null, self::ROUTE_ROOT); @@ -91,7 +86,7 @@ public function setUp(): void $this->getDm()->flush(); } - public function testMatch() + public function testMatch(): void { $expected = [ RouteObjectInterface::CONTROLLER_NAME, @@ -107,7 +102,7 @@ public function testMatch() $this->assertEquals('/test/routing/testroute/child', $matches[RouteObjectInterface::ROUTE_NAME]); } - public function testMatchParameters() + public function testMatchParameters(): void { $expected = [ RouteObjectInterface::CONTROLLER_NAME => 'testController', @@ -125,13 +120,13 @@ public function testMatchParameters() $this->assertEquals($expected, $matches); } - public function testNoMatch() + public function testNoMatch(): void { $this->expectException(ResourceNotFoundException::class); $this->router->matchRequest(Request::create('/testroute/child/123a')); } - public function testNotAllowed() + public function testNotAllowed(): void { $root = $this->getDm()->find(null, self::ROUTE_ROOT); @@ -147,7 +142,7 @@ public function testNotAllowed() $this->router->matchRequest(Request::create('/notallowed', 'POST')); } - public function testMatchDefaultFormat() + public function testMatchDefaultFormat(): void { $expected = [ '_controller' => 'testController', @@ -163,7 +158,7 @@ public function testMatchDefaultFormat() $this->assertEquals($expected, $matches); } - public function testMatchFormat() + public function testMatchFormat(): void { $expected = [ '_controller' => 'testController', @@ -203,13 +198,13 @@ public function testMatchFormat() $this->assertEquals($expected, $matches); } - public function testNoMatchingFormat() + public function testNoMatchingFormat(): void { $this->expectException(ResourceNotFoundException::class); $this->router->matchRequest(Request::create('/format/48.xml')); } - public function testMatchLocale() + public function testMatchLocale(): void { $route = new Route(); $route->setPosition($this->getDm()->find(null, self::ROUTE_ROOT), 'de'); @@ -254,7 +249,7 @@ public function testMatchLocale() ); } - public function testEnhanceControllerByAlias() + public function testEnhanceControllerByAlias(): void { // put a redirect route $root = $this->getDm()->find(null, self::ROUTE_ROOT); @@ -278,7 +273,7 @@ public function testEnhanceControllerByAlias() $this->assertEquals($expected, $matches); } - public function testEnhanceControllerByClass() + public function testEnhanceControllerByClass(): void { // put a redirect route $root = $this->getDm()->find(null, self::ROUTE_ROOT); @@ -301,7 +296,7 @@ public function testEnhanceControllerByClass() $this->assertEquals($expected, $matches); } - public function testEnhanceTemplateByClass() + public function testEnhanceTemplateByClass(): void { if ($content = $this->getDm()->find(null, '/test/content/templatebyclass')) { $this->getDm()->remove($content); @@ -335,7 +330,7 @@ public function testEnhanceTemplateByClass() $this->assertEquals('TestBundle:Content:index.html.twig', $request->attributes->get(DynamicRouter::CONTENT_TEMPLATE)); } - public function testGenerate() + public function testGenerate(): void { $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/testroute/child'); @@ -343,14 +338,14 @@ public function testGenerate() $this->assertEquals('/testroute/child?test=value', $url); } - public function testGenerateAbsolute() + public function testGenerateAbsolute(): void { $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/testroute/child'); $url = $this->router->generate(RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, ['test' => 'value', RouteObjectInterface::ROUTE_OBJECT => $route], UrlGeneratorInterface::ABSOLUTE_URL); $this->assertEquals('http://localhost/testroute/child?test=value', $url); } - public function testGenerateParameters() + public function testGenerateParameters(): void { $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/testroute'); @@ -358,7 +353,7 @@ public function testGenerateParameters() $this->assertEquals('/testroute/gen-slug?test=value', $url); } - public function testGenerateParametersInvalid() + public function testGenerateParametersInvalid(): void { $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/testroute'); @@ -366,7 +361,7 @@ public function testGenerateParametersInvalid() $this->router->generate(RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, ['slug' => 'gen-slug', 'id' => 'nonumber', RouteObjectInterface::ROUTE_OBJECT => $route]); } - public function testGenerateDefaultFormat() + public function testGenerateDefaultFormat(): void { $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/format'); @@ -374,7 +369,7 @@ public function testGenerateDefaultFormat() $this->assertEquals('/format/37', $url); } - public function testGenerateFormat() + public function testGenerateFormat(): void { $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/format'); @@ -382,7 +377,7 @@ public function testGenerateFormat() $this->assertEquals('/format/37.json', $url); } - public function testGenerateNoMatchingFormat() + public function testGenerateNoMatchingFormat(): void { $route = $this->getDm()->find(null, self::ROUTE_ROOT.'/format'); diff --git a/tests/Unit/DependencyInjection/CmfRoutingExtensionTest.php b/tests/Unit/DependencyInjection/CmfRoutingExtensionTest.php index 65bc5aa0..13b65be0 100644 --- a/tests/Unit/DependencyInjection/CmfRoutingExtensionTest.php +++ b/tests/Unit/DependencyInjection/CmfRoutingExtensionTest.php @@ -26,7 +26,7 @@ protected function getContainerExtensions(): array ]; } - public function testLoadDefault() + public function testLoadDefault(): void { $this->load([ 'dynamic' => [ @@ -56,7 +56,7 @@ public function testLoadDefault() ); } - public function testLoadConfigured() + public function testLoadConfigured(): void { $this->load([ 'dynamic' => [ @@ -93,7 +93,7 @@ public function testLoadConfigured() ); } - public function testWhitespaceInPriorities() + public function testWhitespaceInPriorities(): void { $this->load([ 'dynamic' => [ @@ -133,7 +133,7 @@ public function testWhitespaceInPriorities() /** * @dataProvider getBasePathsTests */ - public function testLoadBasePaths($phpcrConfig, $routeBasepathsParameter) + public function testLoadBasePaths(array $phpcrConfig, array $routeBasepathsParameter): void { $this->container->setParameter( 'kernel.bundles', @@ -163,7 +163,7 @@ public function testLoadBasePaths($phpcrConfig, $routeBasepathsParameter) ); } - public function getBasePathsTests() + public function getBasePathsTests(): array { return [ [ @@ -191,7 +191,7 @@ public function getBasePathsTests() /** * @dataProvider getBasePathsMergingTests */ - public function testRouteBasepathsMerging($phpcrConfig1, $phpcrConfig2, $routeBasepathsParameter) + public function testRouteBasepathsMerging(array $phpcrConfig1, array $phpcrConfig2, array $routeBasepathsParameter): void { $this->container->setParameter( 'kernel.bundles', @@ -232,7 +232,7 @@ public function testRouteBasepathsMerging($phpcrConfig1, $phpcrConfig2, $routeBa ); } - public function getBasePathsMergingTests() + public function getBasePathsMergingTests(): array { return [ [ @@ -258,7 +258,7 @@ public function getBasePathsMergingTests() ]; } - public function testInitializerEnabled() + public function testInitializerEnabled(): void { $this->container->setParameter( 'kernel.bundles', @@ -282,7 +282,7 @@ public function testInitializerEnabled() $this->assertContainerBuilderHasService('cmf_routing.initializer', GenericInitializer::class); } - public function testInitializerDisabled() + public function testInitializerDisabled(): void { $this->container->setParameter( 'kernel.bundles', @@ -306,7 +306,7 @@ public function testInitializerDisabled() $this->assertFalse($this->container->has('cmf_routing.initializer')); } - public function testSettingCustomRouteClassForOrm() + public function testSettingCustomRouteClassForOrm(): void { $this->load([ 'dynamic' => [ diff --git a/tests/Unit/DependencyInjection/Compiler/SetRouterPassTest.php b/tests/Unit/DependencyInjection/Compiler/SetRouterPassTest.php index 9e388c56..2331434d 100644 --- a/tests/Unit/DependencyInjection/Compiler/SetRouterPassTest.php +++ b/tests/Unit/DependencyInjection/Compiler/SetRouterPassTest.php @@ -22,7 +22,7 @@ protected function registerCompilerPass(ContainerBuilder $container): void $container->addCompilerPass(new SetRouterPass()); } - public function testMapperPassReplacesRouterAlias() + public function testMapperPassReplacesRouterAlias(): void { $this->container->setParameter('cmf_routing.replace_symfony_router', true); @@ -31,7 +31,7 @@ public function testMapperPassReplacesRouterAlias() $this->assertContainerBuilderHasAlias('router', 'cmf_routing.router'); } - public function testMapperPassDoesNotReplaceRouterAlias() + public function testMapperPassDoesNotReplaceRouterAlias(): void { $this->container->setParameter('cmf_routing.replace_symfony_router', false); diff --git a/tests/Unit/DependencyInjection/Compiler/TemplatingValidatorPassTest.php b/tests/Unit/DependencyInjection/Compiler/TemplatingValidatorPassTest.php deleted file mode 100644 index 4660036d..00000000 --- a/tests/Unit/DependencyInjection/Compiler/TemplatingValidatorPassTest.php +++ /dev/null @@ -1,75 +0,0 @@ -markTestSkipped(); - } - - parent::setUp(); - - $this->registerValidatorService(); - } - - protected function registerCompilerPass(ContainerBuilder $container): void - { - $container->addCompilerPass(new TemplatingValidatorPass()); - } - - /** - * It should replace the validator class with the templating one and - * provide the _templating_ service as second argument. - */ - public function testReplacesValidator() - { - $this->registerService('templating', \stdClass::class); - - $this->compile(); - - $definition = $this->container->getDefinition('cmf_routing.validator.route_defaults'); - - $this->assertEquals(RouteDefaultsTemplatingValidator::class, $definition->getClass()); - $this->assertEquals(['foo', new Reference('templating')], $definition->getArguments()); - } - - /** - * It should leave the validator untouched when the _templating_ service - * is not available. - */ - public function testDoesNotReplaceValidator() - { - $this->compile(); - - $definition = $this->container->getDefinition('cmf_routing.validator.route_defaults'); - - $this->assertEquals(\stdClass::class, $definition->getClass()); - $this->assertEquals(['foo', 'bar'], $definition->getArguments()); - } - - private function registerValidatorService() - { - $definition = $this->registerService('cmf_routing.validator.route_defaults', \stdClass::class); - - $definition->setArguments(['foo', 'bar']); - } -} diff --git a/tests/Unit/DependencyInjection/Compiler/ValidationPassTest.php b/tests/Unit/DependencyInjection/Compiler/ValidationPassTest.php index 768f1f33..f9266386 100644 --- a/tests/Unit/DependencyInjection/Compiler/ValidationPassTest.php +++ b/tests/Unit/DependencyInjection/Compiler/ValidationPassTest.php @@ -29,7 +29,7 @@ protected function registerCompilerPass(ContainerBuilder $container): void * * @dataProvider provideDocumentsValidationContext */ - public function testRegisterDocumentsValidation($hasPhpcr, $hasValidator, $shouldBeRegistered) + public function testRegisterDocumentsValidation(bool $hasPhpcr, bool $hasValidator, bool $shouldBeRegistered): void { if ($hasPhpcr) { $this->setParameter('cmf_routing.backend_type_phpcr', null); @@ -71,7 +71,7 @@ public function testRegisterDocumentsValidation($hasPhpcr, $hasValidator, $shoul * - _$hasValidator: Is the validator available ? * - _$shouldBeRegistered_: Should the documents validation be registered ? */ - public function provideDocumentsValidationContext() + public function provideDocumentsValidationContext(): array { return [ [true, true, true], diff --git a/tests/Unit/DependencyInjection/ConfigurationTest.php b/tests/Unit/DependencyInjection/ConfigurationTest.php index 089c472d..d3bc386f 100644 --- a/tests/Unit/DependencyInjection/ConfigurationTest.php +++ b/tests/Unit/DependencyInjection/ConfigurationTest.php @@ -29,7 +29,7 @@ protected function getConfiguration(): ConfigurationInterface return new Configuration(); } - public function testSupportsAllConfigFormats() + public function testSupportsAllConfigFormats(): void { $expectedConfiguration = [ 'chain' => [ @@ -80,7 +80,7 @@ public function testSupportsAllConfigFormats() ], ]; - $formats = array_map(function ($path) { + $formats = array_map(static function ($path) { return __DIR__.'/../../Fixtures/fixtures/'.$path; }, [ 'config/config.yml', diff --git a/tests/Unit/DependencyInjection/XmlSchemaTest.php b/tests/Unit/DependencyInjection/XmlSchemaTest.php index e06ae92f..ae2aa502 100644 --- a/tests/Unit/DependencyInjection/XmlSchemaTest.php +++ b/tests/Unit/DependencyInjection/XmlSchemaTest.php @@ -15,20 +15,19 @@ class XmlSchemaTest extends XmlSchemaTestCase { - protected $fixturesPath; + private string $fixturesPath; + private string $schemaPath; - protected $schemaPath; - - public function setUp(): void + protected function setUp(): void { $this->fixturesPath = __DIR__.'/../../Fixtures/fixtures/config/'; $this->schemaPath = __DIR__.'/../../../src/Resources/config/schema/routing-1.0.xsd'; } - public function testSchema() + public function testSchema(): void { $fixturesPath = $this->fixturesPath; - $xmlFiles = array_map(function ($file) use ($fixturesPath) { + $xmlFiles = array_map(static function ($file) use ($fixturesPath) { return $fixturesPath.$file; }, [ 'config.xml', @@ -41,7 +40,7 @@ public function testSchema() $this->assertSchemaAcceptsXml($xmlFiles, $this->schemaPath); } - public function testSchemaInvalidesTwoPersistenceLayers() + public function testSchemaInvalidatesTwoPersistenceLayers(): void { $this->assertSchemaRefusesXml($this->fixturesPath.'config_invalid1.xml', $this->schemaPath); } diff --git a/tests/Unit/Doctrine/Orm/ContentRepositoryTest.php b/tests/Unit/Doctrine/Orm/ContentRepositoryTest.php index caf4d00b..77250d78 100644 --- a/tests/Unit/Doctrine/Orm/ContentRepositoryTest.php +++ b/tests/Unit/Doctrine/Orm/ContentRepositoryTest.php @@ -14,20 +14,18 @@ use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ObjectManager; use Doctrine\Persistence\ObjectRepository; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm\ContentRepository; class ContentRepositoryTest extends TestCase { - private $document; + private \stdClass $document; + private ManagerRegistry&MockObject $managerRegistry; + private ObjectManager&MockObject $objectManager; + private ObjectRepository&MockObject $objectRepository; - private $managerRegistry; - - private $objectManager; - - private $objectRepository; - - public function setUp(): void + protected function setUp(): void { $this->document = new \stdClass(); $this->objectManager = $this->createMock(ObjectManager::class); @@ -35,26 +33,23 @@ public function setUp(): void $this->objectRepository = $this->createMock(ObjectRepository::class); } - public function testFindById() + public function testFindById(): void { $this->objectManager - ->expects($this->any()) ->method('getRepository') ->with($this->equalTo('stdClass')) - ->will($this->returnValue($this->objectRepository)) + ->willReturn($this->objectRepository) ; $this->objectRepository - ->expects($this->any()) ->method('find') ->with(123) - ->will($this->returnValue($this->document)) + ->willReturn($this->document) ; $this->managerRegistry - ->expects($this->any()) ->method('getManager') - ->will($this->returnValue($this->objectManager)) + ->willReturn($this->objectManager) ; $contentRepository = new ContentRepository($this->managerRegistry); @@ -68,26 +63,23 @@ public function testFindById() /** * @dataProvider getFindCorrectModelAndIdData */ - public function testFindCorrectModelAndId($input, $model, $id) + public function testFindCorrectModelAndId($input, $model, $id): void { $this->objectManager - ->expects($this->any()) ->method('getRepository') ->with($this->equalTo($model)) - ->will($this->returnValue($this->objectRepository)) + ->willReturn($this->objectRepository) ; $this->objectRepository - ->expects($this->any()) ->method('find') ->with($id) - ->will($this->returnValue($this)) + ->willReturn($this) ; $this->managerRegistry - ->expects($this->any()) ->method('getManager') - ->will($this->returnValue($this->objectManager)) + ->willReturn($this->objectManager) ; $contentRepository = new ContentRepository($this->managerRegistry); @@ -97,7 +89,7 @@ public function testFindCorrectModelAndId($input, $model, $id) $this->assertSame($this, $foundDocument); } - public function getFindCorrectModelAndIdData() + public function getFindCorrectModelAndIdData(): array { return [ ['Acme\ContentBundle\Entity\Content:12', 'Acme\ContentBundle\Entity\Content', 12], diff --git a/tests/Unit/Doctrine/Orm/RouteProviderTest.php b/tests/Unit/Doctrine/Orm/RouteProviderTest.php index 138f2331..6bca02fd 100644 --- a/tests/Unit/Doctrine/Orm/RouteProviderTest.php +++ b/tests/Unit/Doctrine/Orm/RouteProviderTest.php @@ -24,37 +24,14 @@ class RouteProviderTest extends TestCase { - /** - * @var Route&MockObject - */ - private Route $routeMock; - - /** - * @var Route&MockObject - */ - private Route $route2Mock; - - /** - * @var ManagerRegistry&MockObject - */ - private ManagerRegistry $managerRegistryMock; - - /** - * @var ObjectManager&MockObject - */ - private ObjectManager $objectManagerMock; - - /** - * @var EntityRepository&MockObject - */ - private EntityRepository $objectRepositoryMock; - - /** - * @var CandidatesInterface&MockObject - */ - private CandidatesInterface $candidatesMock; - - public function setUp(): void + private Route&MockObject $routeMock; + private Route&MockObject $route2Mock; + private ManagerRegistry&MockObject $managerRegistryMock; + private ObjectManager&MockObject $objectManagerMock; + private EntityRepository&MockObject $objectRepositoryMock; + private CandidatesInterface&MockObject $candidatesMock; + + protected function setUp(): void { $this->routeMock = $this->createMock(Route::class); $this->route2Mock = $this->createMock(Route::class); @@ -62,7 +39,8 @@ public function setUp(): void $this->managerRegistryMock = $this->createMock(ManagerRegistry::class); $this->objectRepositoryMock = $this->getMockBuilder(EntityRepository::class) ->disableOriginalConstructor() - ->setMethods(['findByStaticPrefix', 'findOneBy', 'findBy']) + ->onlyMethods(['findOneBy', 'findBy']) + ->addMethods(['findByStaticPrefix']) ->getMock(); $this->candidatesMock = $this->createMock(CandidatesInterface::class); $this->candidatesMock diff --git a/tests/Unit/Doctrine/Phpcr/ContentRepositoryTest.php b/tests/Unit/Doctrine/Phpcr/ContentRepositoryTest.php index f4104fa3..1902143d 100644 --- a/tests/Unit/Doctrine/Phpcr/ContentRepositoryTest.php +++ b/tests/Unit/Doctrine/Phpcr/ContentRepositoryTest.php @@ -15,22 +15,19 @@ use Doctrine\ODM\PHPCR\DocumentManagerInterface; use Doctrine\ODM\PHPCR\UnitOfWork; use Doctrine\Persistence\ManagerRegistry; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\ContentRepository; class ContentRepositoryTest extends TestCase { - private $document; + private \stdClass $document; + private \stdClass $document2; + private DocumentManagerInterface&MockObject $objectManager; + private DocumentManagerInterface&MockObject $objectManager2; + private ManagerRegistry&MockObject $managerRegistry; - private $document2; - - private $objectManager; - - private $objectManager2; - - private $managerRegistry; - - public function setUp(): void + protected function setUp(): void { $this->document = new \stdClass(); $this->document2 = new \stdClass(); diff --git a/tests/Unit/Doctrine/Phpcr/IdPrefixListenerTest.php b/tests/Unit/Doctrine/Phpcr/IdPrefixListenerTest.php index 46e9b8e8..96218345 100644 --- a/tests/Unit/Doctrine/Phpcr/IdPrefixListenerTest.php +++ b/tests/Unit/Doctrine/Phpcr/IdPrefixListenerTest.php @@ -22,20 +22,11 @@ final class IdPrefixListenerTest extends TestCase { private IdPrefixListener $listener; - private PrefixCandidates $candidates; + private DocumentManager&MockObject $dmMock; + private Route&MockObject $routeMock; - /** - * @var DocumentManager&MockObject - */ - private DocumentManager $dmMock; - - /** - * @var Route&MockObject - */ - private Route $routeMock; - - public function setUp(): void + protected function setUp(): void { $this->candidates = new PrefixCandidates(['/cms/routes', '/cms/simple']); diff --git a/tests/Unit/Doctrine/Phpcr/LocaleListenerTest.php b/tests/Unit/Doctrine/Phpcr/LocaleListenerTest.php index 1c17325f..a1071803 100644 --- a/tests/Unit/Doctrine/Phpcr/LocaleListenerTest.php +++ b/tests/Unit/Doctrine/Phpcr/LocaleListenerTest.php @@ -23,20 +23,11 @@ class LocaleListenerTest extends TestCase { private LocaleListener $listener; - private PrefixCandidates $candidates; + private DocumentManager&MockObject $dmMock; + private Route&MockObject $routeMock; - /** - * @var DocumentManager&MockObject - */ - private DocumentManager $dmMock; - - /** - * @var Route&MockObject - */ - private Route $routeMock; - - public function setUp(): void + protected function setUp(): void { $this->candidates = new PrefixCandidates(['/cms/routes', '/cms/simple']); @@ -73,7 +64,7 @@ public function testNoPrefixMatch(): void $this->listener->postLoad($args); } - private function prepareMatch() + private function prepareMatch(): LifecycleEventArgs { $this->routeMock->expects($this->once()) ->method('getId') @@ -162,7 +153,6 @@ public function testSetLocales(): void $this->listener->setLocales(['xx']); $reflection = new \ReflectionClass(LocaleListener::class); $locales = $reflection->getProperty('locales'); - $locales->setAccessible(true); $this->assertSame(['xx'], $locales->getValue($this->listener)); } diff --git a/tests/Unit/Doctrine/Phpcr/RouteProviderTest.php b/tests/Unit/Doctrine/Phpcr/RouteProviderTest.php index 8eb3ef4e..1142cadc 100644 --- a/tests/Unit/Doctrine/Phpcr/RouteProviderTest.php +++ b/tests/Unit/Doctrine/Phpcr/RouteProviderTest.php @@ -29,37 +29,14 @@ class RouteProviderTest extends TestCase { - /** - * @var ManagerRegistry&MockObject - */ - private ManagerRegistry $managerRegistryMock; - - /** - * @var CandidatesInterface&MockObject - */ - protected CandidatesInterface $candidatesMock; - - /** - * @var DocumentManager&MockObject - */ - protected DocumentManager $dmMock; - - /** - * @var DocumentManager&MockObject - */ - protected DocumentManager $dm2Mock; - - /** - * @var Route&MockObject - */ - protected Route $routeMock; - - /** - * @var Route&MockObject - */ - protected Route $route2Mock; - - public function setUp(): void + private ManagerRegistry&MockObject $managerRegistryMock; + private CandidatesInterface&MockObject $candidatesMock; + private DocumentManager&MockObject $dmMock; + private DocumentManager&MockObject $dm2Mock; + private Route&MockObject $routeMock; + private Route&MockObject $route2Mock; + + protected function setUp(): void { $this->routeMock = $this->createMock(Route::class); $this->route2Mock = $this->createMock(Route::class); @@ -69,7 +46,7 @@ public function setUp(): void $this->managerRegistryMock ->method('getManager') - ->will($this->returnValue($this->dmMock)) + ->willReturn($this->dmMock) ; $this->candidatesMock = $this->createMock(CandidatesInterface::class); @@ -187,7 +164,7 @@ public function testGetRouteByNameUuid(): void $this->assertEquals('/cms/routes/test-route', $foundRoute->getPath()); } - public function testGetRouteByNameUuidNotFound() + public function testGetRouteByNameUuidNotFound(): void { $uuid = UUIDHelper::generateUUID(); @@ -208,7 +185,6 @@ public function testGetRouteByNameUuidNotCandidate(): void { $uuid = UUIDHelper::generateUUID(); $this->routeMock - ->expects($this->any()) ->method('getPath') ->willReturn('/cms/routes/test-route') ; diff --git a/tests/Unit/Doctrine/Phpcr/RouteTest.php b/tests/Unit/Doctrine/Phpcr/RouteTest.php index 2bae6543..5dc6c5bb 100644 --- a/tests/Unit/Doctrine/Phpcr/RouteTest.php +++ b/tests/Unit/Doctrine/Phpcr/RouteTest.php @@ -18,10 +18,9 @@ class RouteTest extends TestCase { private Route $route; - private Route $childRoute1; - public function setUp(): void + protected function setUp(): void { $this->route = new Route(); @@ -33,7 +32,6 @@ public function testGetRouteChildren(): void { $refl = new \ReflectionClass($this->route); $prop = $refl->getProperty('children'); - $prop->setAccessible(true); $prop->setValue($this->route, new ArrayCollection([ new \stdClass(), $this->childRoute1, @@ -41,7 +39,7 @@ public function testGetRouteChildren(): void $res = $this->route->getRouteChildren(); $this->assertCount(1, $res); - $this->assertEquals('child route1', $res[0]->getName()); + $this->assertSame($this->childRoute1, $res[0]); } public function testGetRouteChildrenNull(): void diff --git a/tests/Unit/Form/Type/RouteTypeTypeTest.php b/tests/Unit/Form/Type/RouteTypeTypeTest.php index 92978403..742b2b06 100644 --- a/tests/Unit/Form/Type/RouteTypeTypeTest.php +++ b/tests/Unit/Form/Type/RouteTypeTypeTest.php @@ -17,17 +17,14 @@ class RouteTypeTypeTest extends TestCase { - /** - * @var RouteTypeType - */ - private $type; + private RouteTypeType $type; - public function setUp(): void + protected function setUp(): void { $this->type = new RouteTypeType(); } - public function testSetDefaultOptions() + public function testSetDefaultOptions(): void { $type = new RouteTypeType(); $optionsResolver = new OptionsResolver(); @@ -39,7 +36,7 @@ public function testSetDefaultOptions() $this->assertIsArray($options['choices']); } - public function testDefaultsSet() + public function testDefaultsSet(): void { $this->type->addRouteType('foobar'); $this->type->addRouteType('barfoo'); diff --git a/tests/Unit/Routing/DynamicRouterTest.php b/tests/Unit/Routing/DynamicRouterTest.php index b9c1890d..d323d7c5 100644 --- a/tests/Unit/Routing/DynamicRouterTest.php +++ b/tests/Unit/Routing/DynamicRouterTest.php @@ -24,52 +24,24 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Matcher\UrlMatcherInterface; use Symfony\Component\Routing\RequestContext; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; class DynamicRouterTest extends TestCase { - /** - * @var DynamicRouter - */ - private $router; - - /** - * @var UrlMatcherInterface|MockObject - */ - private $matcher; - - /** - * @var UrlGeneratorInterface|MockObject - */ - private $generator; - - /** - * @var RequestContext|MockObject - */ - private $context; - - /** - * @var Request - */ - private $request; - - /** - * @var RequestStack - */ - private $requestStack; - - /** - * @var EventDispatcherInterface|MockObject - */ - private $eventDispatcher; - - public function setUp(): void + private DynamicRouter $router; + private UrlMatcherInterface&MockObject $matcher; + private UrlGeneratorInterface&MockObject $generator; + private RequestContext&MockObject $context; + private Request $request; + private RequestStack $requestStack; + private EventDispatcherInterface&MockObject $eventDispatcher; + + protected function setUp(): void { $this->matcher = $this->createMock(UrlMatcherInterface::class); $this->matcher->expects($this->once()) ->method('match') ->with('/foo') - ->will($this->returnValue(['foo' => 'bar', RouteObjectInterface::CONTENT_OBJECT => 'bla', RouteObjectInterface::TEMPLATE_NAME => 'template'])) + ->willReturn(['foo' => 'bar', RouteObjectInterface::CONTENT_OBJECT => 'bla', RouteObjectInterface::TEMPLATE_NAME => 'template']) ; $this->generator = $this->createMock(UrlGeneratorInterface::class); @@ -83,7 +55,7 @@ public function setUp(): void $this->router->setRequestStack($this->requestStack); } - private function assertRequestAttributes($request) + private function assertRequestAttributes($request): void { $this->assertTrue($request->attributes->has(DynamicRouter::CONTENT_KEY)); $this->assertEquals('bla', $request->attributes->get(DynamicRouter::CONTENT_KEY)); @@ -94,17 +66,11 @@ private function assertRequestAttributes($request) /** * @group legacy */ - public function testMatch() + public function testMatch(): void { - $dispatchParams = [Events::PRE_DYNAMIC_MATCH, $this->equalTo(new RouterMatchEvent())]; - if ($this->eventDispatcher instanceof ContractsEventDispatcherInterface) { - // New Symfony 4.3 EventDispatcher signature - $dispatchParams = [$this->equalTo(new RouterMatchEvent()), Events::PRE_DYNAMIC_MATCH]; - } - $this->eventDispatcher->expects($this->once()) ->method('dispatch') - ->with(...$dispatchParams) + ->with($this->equalTo(new RouterMatchEvent()), Events::PRE_DYNAMIC_MATCH) ; $parameters = $this->router->match('/foo'); @@ -113,17 +79,11 @@ public function testMatch() $this->assertRequestAttributes($this->request); } - public function testMatchRequest() + public function testMatchRequest(): void { - $dispatchParams = [Events::PRE_DYNAMIC_MATCH_REQUEST, $this->equalTo(new RouterMatchEvent($this->request))]; - if ($this->eventDispatcher instanceof ContractsEventDispatcherInterface) { - // New Symfony 4.3 EventDispatcher signature - $dispatchParams = [$this->equalTo(new RouterMatchEvent($this->request)), Events::PRE_DYNAMIC_MATCH_REQUEST]; - } - $this->eventDispatcher->expects($this->once()) ->method('dispatch') - ->with(...$dispatchParams) + ->with($this->equalTo(new RouterMatchEvent($this->request)), Events::PRE_DYNAMIC_MATCH_REQUEST) ; $parameters = $this->router->matchRequest($this->request); @@ -135,19 +95,13 @@ public function testMatchRequest() /** * @group legacy */ - public function testMatchNoRequest() + public function testMatchNoRequest(): void { $this->router->setRequestStack(new RequestStack()); - $dispatchParams = [Events::PRE_DYNAMIC_MATCH, $this->equalTo(new RouterMatchEvent())]; - if ($this->eventDispatcher instanceof ContractsEventDispatcherInterface) { - // New Symfony 4.3 EventDispatcher signature - $dispatchParams = [$this->equalTo(new RouterMatchEvent()), Events::PRE_DYNAMIC_MATCH]; - } - $this->eventDispatcher->expects($this->once()) ->method('dispatch') - ->with(...$dispatchParams) + ->with($this->equalTo(new RouterMatchEvent()), Events::PRE_DYNAMIC_MATCH) ; $this->expectException(ResourceNotFoundException::class); @@ -155,7 +109,7 @@ public function testMatchNoRequest() $this->router->match('/foo'); } - public function testEventOptional() + public function testEventOptional(): void { $router = new DynamicRouter($this->context, $this->matcher, $this->generator); diff --git a/tests/Unit/Routing/RedirectableRequestMatcherTest.php b/tests/Unit/Routing/RedirectableRequestMatcherTest.php index 9d4c0fad..39464670 100644 --- a/tests/Unit/Routing/RedirectableRequestMatcherTest.php +++ b/tests/Unit/Routing/RedirectableRequestMatcherTest.php @@ -21,32 +21,13 @@ class RedirectableRequestMatcherTest extends TestCase { - /** - * @var RedirectableRequestMatcher - */ - private $redirectableRequestMatcher; + private RedirectableRequestMatcher $redirectableRequestMatcher; + private RequestMatcherInterface&MockObject $decoratedRequestMatcher; + private Request $requestWithoutSlash; + private Request $requestWithSlash; + private RequestContext&MockObject $context; - /** - * @var RequestMatcherInterface|MockObject - */ - private $decoratedRequestMatcher; - - /** - * @var Request - */ - private $requestWithoutSlash; - - /** - * @var Request - */ - private $requestWithSlash; - - /** - * @var RequestContext|MockObject - */ - private $context; - - public function setUp(): void + protected function setUp(): void { $this->requestWithoutSlash = Request::create('/foo'); $this->requestWithSlash = Request::create('/foo/'); @@ -55,19 +36,19 @@ public function setUp(): void $this->redirectableRequestMatcher = new RedirectableRequestMatcher($this->decoratedRequestMatcher, $this->context); } - public function testMatchRequest() + public function testMatchRequest(): void { $this->decoratedRequestMatcher ->expects($this->once()) ->method('matchRequest') ->with($this->requestWithoutSlash) - ->will($this->returnValue(['foo' => 'bar'])); + ->willReturn(['foo' => 'bar']); $parameters = $this->redirectableRequestMatcher->matchRequest($this->requestWithoutSlash); $this->assertEquals(['foo' => 'bar'], $parameters); } - public function testMatchRequestWithSlash() + public function testMatchRequestWithSlash(): void { $this->decoratedRequestMatcher ->method('matchRequest') @@ -82,7 +63,7 @@ public function testMatchRequestWithSlash() )); $parameters = $this->redirectableRequestMatcher->matchRequest($this->requestWithSlash); - $this->assertTrue('foobar' === $parameters['_route']); - $this->assertTrue('/foo' === $parameters['path']); + $this->assertSame('foobar', $parameters['_route']); + $this->assertSame('/foo', $parameters['path']); } } diff --git a/tests/Unit/Validator/Constraints/RouteDefaultsTemplatingValidatorTest.php b/tests/Unit/Validator/Constraints/RouteDefaultsTemplatingValidatorTest.php deleted file mode 100644 index 55c3e17f..00000000 --- a/tests/Unit/Validator/Constraints/RouteDefaultsTemplatingValidatorTest.php +++ /dev/null @@ -1,38 +0,0 @@ -createMock(EngineInterface::class); - } - - protected function setUp(): void - { - if (!class_exists(EngineInterface::class)) { - $this->markTestSkipped(); - } - - parent::setUp(); - } - - protected function createValidator(): ConstraintValidatorInterface - { - return new RouteDefaultsTemplatingValidator($this->controllerResolver, $this->engine); - } -} diff --git a/tests/Unit/Validator/Constraints/RouteDefaultsTwigValidatorTest.php b/tests/Unit/Validator/Constraints/RouteDefaultsTwigValidatorTest.php index 5894ff98..779d85ac 100644 --- a/tests/Unit/Validator/Constraints/RouteDefaultsTwigValidatorTest.php +++ b/tests/Unit/Validator/Constraints/RouteDefaultsTwigValidatorTest.php @@ -11,21 +11,33 @@ namespace Symfony\Cmf\Bundle\RoutingBundle\Tests\Unit\Validator\Constraints; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Cmf\Bundle\RoutingBundle\Validator\Constraints\RouteDefaults; use Symfony\Cmf\Bundle\RoutingBundle\Validator\Constraints\RouteDefaultsTwigValidator; +use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; +use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\ConstraintValidatorInterface; +use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; +use Symfony\Component\Validator\Test\ConstraintViolationAssertion; use Twig\Loader\LoaderInterface; -class RouteDefaultsTwigValidatorTest extends RouteDefaultsValidatorTest +class RouteDefaultsTwigValidatorTest extends ConstraintValidatorTestCase { - protected function mockEngine() + private MockObject&ControllerResolverInterface $controllerResolver; + private MockObject&LoaderInterface $loader; + + protected function setUp(): void { - return $this->createMock(LoaderInterface::class); + $this->controllerResolver = $this->createMock(ControllerResolverInterface::class); + $this->loader = $this->createMock(LoaderInterface::class); + + parent::setUp(); + $this->constraint = new RouteDefaults(); } protected function createValidator(): ConstraintValidatorInterface { - return new RouteDefaultsTwigValidator($this->controllerResolver, $this->engine); + return new RouteDefaultsTwigValidator($this->controllerResolver, $this->loader); } public function testNoTemplateViolationWithoutTwig(): void @@ -38,4 +50,54 @@ public function testNoTemplateViolationWithoutTwig(): void $this->assertNoViolation(); } + + public function testCorrectControllerPath(): void + { + $this->validator->validate(['_controller' => 'FrameworkBundle:Redirect:redirect'], new RouteDefaults()); + + $this->assertNoViolation(); + } + + public function testControllerPathViolation(): void + { + $this->controllerResolver + ->method('getController') + ->willThrowException(new \LogicException('Invalid controller')) + ; + + $this->validator->validate(['_controller' => 'NotExistingBundle:Foo:bar'], new RouteDefaults()); + + (new ConstraintViolationAssertion($this->context, 'Invalid controller', new NotNull()))->assertRaised(); + } + + public function testCorrectTemplate(): void + { + $this->loader + ->method('exists') + ->willReturn(true) + ; + + $this->validator->validate(['_template' => 'TwigBundle::layout.html.twig'], $this->constraint); + + $this->assertNoViolation(); + } + + public function testTemplateViolation(): void + { + $this + ->loader + ->method('exists') + ->willReturn(false) + ; + + $this->validator->validate( + ['_template' => 'NotExistingBundle:Foo:bar.html.twig'], + new RouteDefaults(['message' => 'my message']) + ); + + (new ConstraintViolationAssertion($this->context, 'my message', new NotNull())) + ->setParameter('%name%', 'NotExistingBundle:Foo:bar.html.twig') + ->assertRaised() + ; + } } diff --git a/tests/Unit/Validator/Constraints/RouteDefaultsValidatorTest.php b/tests/Unit/Validator/Constraints/RouteDefaultsValidatorTest.php deleted file mode 100644 index c7ec58b6..00000000 --- a/tests/Unit/Validator/Constraints/RouteDefaultsValidatorTest.php +++ /dev/null @@ -1,94 +0,0 @@ -controllerResolver = $this->createMock(ControllerResolverInterface::class); - $this->engine = $this->mockEngine(); - - parent::setUp(); - } - - /** - * @return MockObject|EngineInterface|LoaderInterface - */ - abstract protected function mockEngine(); - - public function testCorrectControllerPath(): void - { - $this->validator->validate(['_controller' => 'FrameworkBundle:Redirect:redirect'], new RouteDefaults()); - - $this->assertNoViolation(); - } - - public function testControllerPathViolation(): void - { - $this->controllerResolver - ->method('getController') - ->willThrowException(new \LogicException('Invalid controller')) - ; - - $this->validator->validate(['_controller' => 'NotExistingBundle:Foo:bar'], new RouteDefaults()); - - $this->buildViolation('Invalid controller')->assertRaised(); - } - - public function testCorrectTemplate(): void - { - $this->engine - ->method('exists') - ->willReturn(true) - ; - - $this->validator->validate(['_template' => 'TwigBundle::layout.html.twig'], $this->constraint); - - $this->assertNoViolation(); - } - - public function testTemplateViolation(): void - { - $this - ->engine - ->method('exists') - ->willReturn(false) - ; - - $this->validator->validate( - ['_template' => 'NotExistingBundle:Foo:bar.html.twig'], - new RouteDefaults(['message' => 'my message']) - ); - - $this->buildViolation('my message') - ->setParameter('%name%', 'NotExistingBundle:Foo:bar.html.twig') - ->assertRaised(); - } -}