From 98cbc53f13be18f8ca6c3b0d4204ac8e8c231c7d Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:22:02 +0200 Subject: [PATCH 01/16] Same `doctrine/orm` requirement as `damienharper/auditor` --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 5764a0d..6676d1e 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,7 @@ "ext-json": "*", "damienharper/auditor": "dev-master", "doctrine/doctrine-bundle": "^2.0", - "doctrine/orm": "^2.13 || ^3.1", + "doctrine/orm": "^2.13|^3.2", "symfony/asset": "^5.4|^6.0|^7.0", "symfony/doctrine-bridge": "^5.4|^6.0|^7.0", "symfony/event-dispatcher": "^5.4|^6.0|^7.0", From ee65df839d21eb23a76dc7729286c0c93564a779 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:22:39 +0200 Subject: [PATCH 02/16] Same PHP-CS-Fixer config as `damienharper/auditor` --- .php-cs-fixer.dist.php | 50 +++++++++++++++++++++++++++++++++++++++ .php-cs-fixer.php | 53 ------------------------------------------ 2 files changed, 50 insertions(+), 53 deletions(-) create mode 100644 .php-cs-fixer.dist.php delete mode 100644 .php-cs-fixer.php diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..ebb3f12 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,50 @@ +setParallelConfig(ParallelConfigFactory::detect()) // @TODO 4.0 no need to call this manually :poop: + ->setRiskyAllowed(true) + ->setRules([ + '@PHP82Migration' => true, + '@Symfony' => true, + '@Symfony:risky' => true, + '@DoctrineAnnotation' => true, + '@PhpCsFixer' => true, + '@PhpCsFixer:risky' => true, + '@PHPUnit100Migration:risky' => true, +// 'date_time_immutable' => true, + 'general_phpdoc_annotation_remove' => [ + 'annotations' => [ + 'expectedDeprecation', + 'expectedException', + 'expectedExceptionMessage', + 'expectedExceptionMessageRegExp', + ], + ], + 'ordered_interfaces' => true, + 'ordered_traits' => true, + 'phpdoc_to_param_type' => true, + 'phpdoc_to_property_type' => true, + 'phpdoc_to_return_type' => true, + 'regular_callable_call' => true, + 'simplified_if_return' => true, + 'get_class_to_class_keyword' => true, + 'mb_str_functions' => true, + 'modernize_strpos' => true, + 'no_useless_concat_operator' => false, // TODO switch back on when the `src/Console/Application.php` no longer needs the concat + 'numeric_literal_separator' => true, + 'string_implicit_backslashes' => true, // https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/pull/7786 + 'php_unit_test_case_static_method_calls' => false, + ]) + ->setFinder( + (new Finder()) + ->ignoreDotFiles(false) + ->ignoreVCSIgnored(true) + ->in(__DIR__.'/src') + ->in(__DIR__.'/tests') + ) +; diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php deleted file mode 100644 index d766c38..0000000 --- a/.php-cs-fixer.php +++ /dev/null @@ -1,53 +0,0 @@ -in(__DIR__.'/src') - ->notPath('DependencyInjection/Configuration.php') - ->in(__DIR__.'/tests') - ->exclude('App/var') - ->append([__FILE__]) -; - -return (new Config()) - ->setRiskyAllowed(true) - ->setRules([ - '@PhpCsFixer' => true, - '@PhpCsFixer:risky' => true, - '@DoctrineAnnotation' => true, - '@PHPUnit84Migration:risky' => true, - 'date_time_immutable' => true, - 'final_public_method_for_abstract_class' => false, - 'general_phpdoc_annotation_remove' => [ - 'annotations' => [ - 'expectedException', - 'expectedExceptionMessage', - 'expectedExceptionMessageRegExp', - ], - ], - 'global_namespace_import' => true, - 'linebreak_after_opening_tag' => true, - 'list_syntax' => ['syntax' => 'short'], - 'mb_str_functions' => true, - 'method_chaining_indentation' => true, - 'nullable_type_declaration_for_default_null_value' => true, - 'ordered_interfaces' => true, - 'ordered_traits' => true, - 'php_unit_size_class' => true, - 'php_unit_test_class_requires_covers' => false, - 'phpdoc_types' => true, - 'phpdoc_to_param_type' => true, - 'phpdoc_to_property_type' => true, - 'phpdoc_to_return_type' => true, - 'regular_callable_call' => true, - 'self_static_accessor' => true, - 'simplified_if_return' => true, - 'simplified_null_return' => true, - 'static_lambda' => true, - 'get_class_to_class_keyword' => true, - ]) - ->setFinder($finder) -; From 1288e4a9199105eab2a875fa56561914720e345e Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:24:00 +0200 Subject: [PATCH 03/16] Same composer scripts config as `damienharper/auditor` --- composer.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 6676d1e..f08e68c 100644 --- a/composer.json +++ b/composer.json @@ -56,15 +56,15 @@ "doctrine/data-fixtures": "^1.4" }, "scripts": { - "test": "php -d pcov.enabled=1 ./vendor/bin/phpunit --colors=always", - "csfixer": "tools/php-cs-fixer/vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --using-cache=no --verbose --ansi", - "cs-check": "tools/php-cs-fixer/vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --using-cache=no --verbose --ansi --dry-run", - "phpstan": "tools/phpstan/vendor/bin/phpstan --ansi analyse src", - "setup44": "SYMFONY_REQUIRE='^4.4' composer update --prefer-stable", - "setup54": "SYMFONY_REQUIRE='^5.4' composer update --prefer-stable", - "rector": "tools/rector/vendor/bin/rector process src", + "test": "XDEBUG_MODE=coverage ./vendor/bin/phpunit --colors=always", + "cs-fix": "tools/php-cs-fixer/vendor/bin/php-cs-fixer fix --using-cache=no --verbose --ansi", + "cs-check": "tools/php-cs-fixer/vendor/bin/php-cs-fixer fix --using-cache=no --verbose --ansi --dry-run", + "phpstan": "tools/phpstan/vendor/bin/phpstan --memory-limit=1G --ansi analyse src", + "rector": "tools/rector/vendor/bin/rector", "rector-check": "tools/rector/vendor/bin/rector --dry-run", - "update-tools": "composer update --working-dir=tools/php-cs-fixer ; composer update --working-dir=tools/phpstan ; composer update --working-dir=tools/rector" + "update-tools": "composer update --working-dir=tools/php-cs-fixer ; composer update --working-dir=tools/phpstan ; composer update --working-dir=tools/rector", + "setup44": "SYMFONY_REQUIRE='^4.4' composer update --prefer-stable", + "setup54": "SYMFONY_REQUIRE='^5.4' composer update --prefer-stable" }, "config": { "sort-packages": true, From 7cc7c4a0908756bd7ade555d9ad00e9299fcb360 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:33:46 +0200 Subject: [PATCH 04/16] Same PHPStan config as `damienharper/auditor` --- phpstan.neon | 11 +++++++---- tools/phpstan/composer.json | 18 ++++++++++++------ 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index dc74e96..731be49 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,10 +1,13 @@ -includes: - - tools/phpstan/vendor/phpstan/phpstan-doctrine/extension.neon - - tools/phpstan/vendor/phpstan/phpstan-doctrine/rules.neon - parameters: level: max inferPrivatePropertyTypeFromConstructor: true + + type_coverage: + return_type: 100 + param_type: 100 + property_type: 100 + constant: 0 + paths: - src diff --git a/tools/phpstan/composer.json b/tools/phpstan/composer.json index 8728ce3..f4ec84e 100644 --- a/tools/phpstan/composer.json +++ b/tools/phpstan/composer.json @@ -1,9 +1,15 @@ { - "require": { - "phpstan/phpstan": "^1.0", - "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-doctrine": "^1.0", - "phpstan/phpstan-strict-rules": "^1.0", - "phpstan/phpstan-symfony": "^1.0" + "require-dev": { + "phpstan/phpstan": "^1.10", + "phpstan/extension-installer": "^1.3", + "phpstan/phpstan-doctrine": "^1.3", + "phpstan/phpstan-phpunit": "^1.3", + "phpstan/phpstan-deprecation-rules": "^1.1", + "tomasvotruba/type-coverage": "^0.3" + }, + "config": { + "allow-plugins": { + "phpstan/extension-installer": true + } } } From 8dc5173789e33f2fc1378fdb9732fea525a210a8 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:33:51 +0200 Subject: [PATCH 05/16] Same Rector config as `damienharper/auditor` --- tools/rector/composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/rector/composer.json b/tools/rector/composer.json index 8cb0ef9..a754466 100644 --- a/tools/rector/composer.json +++ b/tools/rector/composer.json @@ -1,5 +1,5 @@ { "require": { - "rector/rector": "^0.15" + "rector/rector": "^1.2" } } From fc7c48cd06b5957070a07ed799e05f56c41af358 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:38:20 +0200 Subject: [PATCH 06/16] PHP-CS-Fixer --- .php-cs-fixer.dist.php | 2 ++ src/Routing/RoutingLoader.php | 5 ++--- src/User/UserProvider.php | 3 +-- tests/App/Command/CreatePostCommand.php | 3 +-- tests/App/Kernel.php | 4 ++-- tests/App/public/index.php | 2 +- tests/Console/ConsoleUserProviderTest.php | 2 ++ tests/Controller/ViewerControllerTest.php | 2 ++ tests/DHAuditorBundleTest.php | 2 ++ .../Compiler/AddProvidersCompilerPassTest.php | 2 ++ .../Compiler/CustomConfigurationCompilerPassTest.php | 2 ++ .../Compiler/DoctrineMiddlewareCompilerPassTest.php | 2 ++ .../Compiler/StorageConfigurationCompilerPassTest.php | 2 ++ tests/Helper/UrlHelperTest.php | 2 ++ tests/Twig/Views/MacrosTest.php | 2 ++ tests/User/UserProviderTest.php | 7 ++++--- 16 files changed, 31 insertions(+), 13 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index ebb3f12..0e39e55 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -45,6 +45,8 @@ ->ignoreDotFiles(false) ->ignoreVCSIgnored(true) ->in(__DIR__.'/src') + ->notPath('DependencyInjection/Configuration.php') ->in(__DIR__.'/tests') + ->exclude('App/var') ) ; diff --git a/src/Routing/RoutingLoader.php b/src/Routing/RoutingLoader.php index af9233a..67c8f0f 100644 --- a/src/Routing/RoutingLoader.php +++ b/src/Routing/RoutingLoader.php @@ -5,7 +5,6 @@ namespace DH\AuditorBundle\Routing; use DH\AuditorBundle\Controller\ViewerController; -use RuntimeException; use Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader; use Symfony\Bundle\FrameworkBundle\Routing\AttributeRouteControllerLoader; use Symfony\Component\Config\Loader\Loader; @@ -30,7 +29,7 @@ public function __construct(AttributeRouteControllerLoader $annotatedRouteContro public function load(mixed $resource, ?string $type = null): RouteCollection { if ($this->isLoaded) { - throw new RuntimeException('Do not add the "audit" loader twice'); + throw new \RuntimeException('Do not add the "audit" loader twice'); } $routeCollection = new RouteCollection(); @@ -66,7 +65,7 @@ public function __construct(AnnotatedRouteControllerLoader $annotatedRouteContro public function load(mixed $resource, ?string $type = null): RouteCollection { if ($this->isLoaded) { - throw new RuntimeException('Do not add the "audit" loader twice'); + throw new \RuntimeException('Do not add the "audit" loader twice'); } $routeCollection = new RouteCollection(); diff --git a/src/User/UserProvider.php b/src/User/UserProvider.php index 95a4a9e..5f6f81a 100644 --- a/src/User/UserProvider.php +++ b/src/User/UserProvider.php @@ -7,7 +7,6 @@ use DH\Auditor\User\User; use DH\Auditor\User\UserInterface as AuditorUserInterface; use DH\Auditor\User\UserProviderInterface; -use Exception; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; use Symfony\Component\Security\Core\User\UserInterface; @@ -65,7 +64,7 @@ private function getTokenUser(): ?UserInterface { try { $token = $this->tokenStorage->getToken(); - } catch (Exception $e) { + } catch (\Exception $e) { $token = null; } diff --git a/tests/App/Command/CreatePostCommand.php b/tests/App/Command/CreatePostCommand.php index 0d4b649..7d5db33 100644 --- a/tests/App/Command/CreatePostCommand.php +++ b/tests/App/Command/CreatePostCommand.php @@ -4,7 +4,6 @@ namespace DH\AuditorBundle\Tests\App\Command; -use DateTimeImmutable; use DH\Auditor\Provider\Doctrine\DoctrineProvider; use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Post; use Symfony\Component\Console\Command\Command; @@ -37,7 +36,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $post ->setTitle('Blameable post') ->setBody('yet another post') - ->setCreatedAt(new DateTimeImmutable('2020-01-17 22:17:34')) + ->setCreatedAt(new \DateTimeImmutable('2020-01-17 22:17:34')) ; $entityManager = $this->doctrineProvider->getAuditingServiceForEntity(Post::class)->getEntityManager(); diff --git a/tests/App/Kernel.php b/tests/App/Kernel.php index 94978dd..64e8796 100644 --- a/tests/App/Kernel.php +++ b/tests/App/Kernel.php @@ -36,7 +36,7 @@ public function getProjectDir(): string protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void { $container->addResource(new FileResource($this->getProjectDir().'/config/bundles.php')); - $container->setParameter('.container.dumper.inline_class_loader', \PHP_VERSION_ID < 70400 || $this->debug); + $container->setParameter('.container.dumper.inline_class_loader', \PHP_VERSION_ID < 70_400 || $this->debug); $container->setParameter('.container.dumper.inline_factories', true); $confDir = $this->getProjectDir().'/config'; @@ -78,7 +78,7 @@ public function getProjectDir(): string protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void { $container->addResource(new FileResource($this->getProjectDir().'/config/bundles.php')); - $container->setParameter('container.dumper.inline_class_loader', \PHP_VERSION_ID < 70400 || $this->debug); + $container->setParameter('container.dumper.inline_class_loader', \PHP_VERSION_ID < 70_400 || $this->debug); $container->setParameter('container.dumper.inline_factories', true); $confDir = $this->getProjectDir().'/config'; diff --git a/tests/App/public/index.php b/tests/App/public/index.php index a8132ef..7e45fbf 100644 --- a/tests/App/public/index.php +++ b/tests/App/public/index.php @@ -9,7 +9,7 @@ require dirname(__DIR__).'/config/bootstrap.php'; if ($_SERVER['APP_DEBUG']) { - umask(0000); + umask(0o000); Debug::enable(); } diff --git a/tests/Console/ConsoleUserProviderTest.php b/tests/Console/ConsoleUserProviderTest.php index a50a282..d4c2ada 100644 --- a/tests/Console/ConsoleUserProviderTest.php +++ b/tests/Console/ConsoleUserProviderTest.php @@ -17,6 +17,8 @@ * @internal * * @small + * + * @coversNothing */ final class ConsoleUserProviderTest extends KernelTestCase { diff --git a/tests/Controller/ViewerControllerTest.php b/tests/Controller/ViewerControllerTest.php index 706e4ae..84bce42 100644 --- a/tests/Controller/ViewerControllerTest.php +++ b/tests/Controller/ViewerControllerTest.php @@ -24,6 +24,8 @@ * @internal * * @small + * + * @coversNothing */ final class ViewerControllerTest extends WebTestCase { diff --git a/tests/DHAuditorBundleTest.php b/tests/DHAuditorBundleTest.php index e98d90d..c01726d 100644 --- a/tests/DHAuditorBundleTest.php +++ b/tests/DHAuditorBundleTest.php @@ -26,6 +26,8 @@ * @internal * * @small + * + * @coversNothing */ final class DHAuditorBundleTest extends KernelTestCase { diff --git a/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php b/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php index a4a3bc6..b82dfd3 100644 --- a/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php @@ -12,6 +12,8 @@ * @internal * * @small + * + * @coversNothing */ final class AddProvidersCompilerPassTest extends AbstractCompilerPassTestCase { diff --git a/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php b/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php index 393fa3e..3247aa1 100644 --- a/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php @@ -20,6 +20,8 @@ * @internal * * @small + * + * @coversNothing */ final class CustomConfigurationCompilerPassTest extends AbstractCompilerPassTestCase { diff --git a/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php b/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php index df7a3a0..9bdd207 100644 --- a/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php @@ -22,6 +22,8 @@ * @internal * * @small + * + * @coversNothing */ final class DoctrineMiddlewareCompilerPassTest extends AbstractCompilerPassTestCase { diff --git a/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php b/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php index d1ce981..23b93f8 100644 --- a/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php @@ -12,6 +12,8 @@ * @internal * * @small + * + * @coversNothing */ final class StorageConfigurationCompilerPassTest extends AbstractCompilerPassTestCase { diff --git a/tests/Helper/UrlHelperTest.php b/tests/Helper/UrlHelperTest.php index 598b3e4..7ae8f41 100644 --- a/tests/Helper/UrlHelperTest.php +++ b/tests/Helper/UrlHelperTest.php @@ -12,6 +12,8 @@ * @internal * * @small + * + * @coversNothing */ final class UrlHelperTest extends TestCase { diff --git a/tests/Twig/Views/MacrosTest.php b/tests/Twig/Views/MacrosTest.php index cf37849..a1f4d4b 100644 --- a/tests/Twig/Views/MacrosTest.php +++ b/tests/Twig/Views/MacrosTest.php @@ -16,6 +16,8 @@ * @internal * * @small + * + * @coversNothing */ final class MacrosTest extends KernelTestCase { diff --git a/tests/User/UserProviderTest.php b/tests/User/UserProviderTest.php index d7c8be8..7f55d95 100644 --- a/tests/User/UserProviderTest.php +++ b/tests/User/UserProviderTest.php @@ -4,7 +4,6 @@ namespace DH\AuditorBundle\Tests\User; -use DateTimeImmutable; use DH\Auditor\Provider\Doctrine\DoctrineProvider; use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Post; use DH\Auditor\Tests\Provider\Doctrine\Traits\ReaderTrait; @@ -23,6 +22,8 @@ * @internal * * @small + * + * @coversNothing */ final class UserProviderTest extends WebTestCase { @@ -71,7 +72,7 @@ public function testBlameUser(): void $post ->setTitle('Blameable post') ->setBody('yet another post') - ->setCreatedAt(new DateTimeImmutable('2020-01-17 22:17:34')) + ->setCreatedAt(new \DateTimeImmutable('2020-01-17 22:17:34')) ; $auditingServices[Post::class]->getEntityManager()->persist($post); $this->flushAll($auditingServices); @@ -106,7 +107,7 @@ public function testBlameImpersonator(): void $post ->setTitle('Blameable post') ->setBody('yet another post') - ->setCreatedAt(new DateTimeImmutable('2020-01-17 22:17:34')) + ->setCreatedAt(new \DateTimeImmutable('2020-01-17 22:17:34')) ; $auditingServices[Post::class]->getEntityManager()->persist($post); $this->flushAll($auditingServices); From bec9f7730ebbe87608a4d1820a738fe04e50770d Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:44:51 +0200 Subject: [PATCH 07/16] PHPStan fixes --- src/Controller/ViewerController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/ViewerController.php b/src/Controller/ViewerController.php index 2db6334..3b781f1 100644 --- a/src/Controller/ViewerController.php +++ b/src/Controller/ViewerController.php @@ -44,7 +44,7 @@ public function listAuditsAction(Reader $reader): Response $audited, array_filter( $schemaManager->getAuditableTableNames($auditingService->getEntityManager()), - static function ($entity) use ($reader, $scope) { + static function (string $entity) use ($reader, $scope) { $roleChecker = $reader->getProvider()->getAuditor()->getConfiguration()->getRoleChecker(); return null === $roleChecker ? true : $roleChecker($entity, $scope); From 60e4806e38a01f8047be310e726be32c857656d5 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 15:51:48 +0200 Subject: [PATCH 08/16] DHMiddleware has been renamed to AuditorMiddleware --- .../DoctrineProviderConfigurationCompilerPass.php | 10 +++++----- .../Compiler/DoctrineMiddlewareCompilerPassTest.php | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php b/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php index 94340ed..ffeb7fd 100644 --- a/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php +++ b/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php @@ -5,7 +5,7 @@ namespace DH\AuditorBundle\DependencyInjection\Compiler; use DH\Auditor\Provider\Doctrine\Auditing\Annotation\AnnotationLoader; -use DH\Auditor\Provider\Doctrine\Auditing\Logger\Middleware\DHMiddleware; +use DH\Auditor\Provider\Doctrine\Auditing\DBAL\Middleware\AuditorMiddleware; use DH\Auditor\Provider\Doctrine\DoctrineProvider; use DH\Auditor\Provider\Doctrine\Service\AuditingService; use DH\Auditor\Provider\Doctrine\Service\StorageService; @@ -78,9 +78,9 @@ public function process(ContainerBuilder $container): void private function registerDHMiddleware(ContainerBuilder $container): void { - if (interface_exists(Middleware::class) && class_exists(DHMiddleware::class)) { + if (interface_exists(Middleware::class) && class_exists(AuditorMiddleware::class)) { $this->isDHMiddlewareSupported = true; - $container->register('doctrine.dbal.dh_middleware', DHMiddleware::class); + $container->register('doctrine.dbal.auditor_middleware', AuditorMiddleware::class); } } @@ -105,8 +105,8 @@ private function configureDHMiddleware(ContainerBuilder $container, string $enti $container ->setDefinition( - $connectionName.'.dh_middleware', - new ChildDefinition('doctrine.dbal.dh_middleware') + $connectionName.'.auditor_middleware', + new ChildDefinition('doctrine.dbal.auditor_middleware') ) ->addTag('doctrine.middleware') ; diff --git a/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php b/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php index 9bdd207..55b33f2 100644 --- a/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php @@ -5,7 +5,7 @@ namespace DH\AuditorBundle\Tests\DependencyInjection\Compiler; use DH\Auditor\Configuration; -use DH\Auditor\Provider\Doctrine\Auditing\Logger\Middleware\DHMiddleware; +use DH\Auditor\Provider\Doctrine\Auditing\DBAL\Middleware\AuditorMiddleware; use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Author; use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Comment; use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Post; @@ -29,7 +29,7 @@ final class DoctrineMiddlewareCompilerPassTest extends AbstractCompilerPassTestC { public function testCompilerPass(): void { - if (!interface_exists(Middleware::class) || !class_exists(DHMiddleware::class)) { + if (!interface_exists(Middleware::class) || !class_exists(AuditorMiddleware::class)) { self::markTestSkipped('DHMiddleware isn\'t supported'); } $this->container->setParameter('kernel.cache_dir', sys_get_temp_dir()); @@ -96,7 +96,7 @@ public function testCompilerPass(): void $this->compile(); $this->assertContainerBuilderHasServiceDefinitionWithTag( - 'doctrine.dbal.default_connection.dh_middleware', + 'doctrine.dbal.default_connection.auditor_middleware', 'doctrine.middleware' ); } From 3388c9eec7ea101bdb3961f059ccf15b55c1169f Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 17:12:02 +0200 Subject: [PATCH 09/16] PHPUnit 11.x --- .gitignore | 2 +- composer.json | 2 +- phpunit.xml.dist => phpunit.xml | 23 ++++++++++------------- 3 files changed, 12 insertions(+), 15 deletions(-) rename phpunit.xml.dist => phpunit.xml (65%) diff --git a/.gitignore b/.gitignore index e7d00f8..0d1247d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ tests/coverage/ .DS_Store .php_cs.cache .php-cs-fixer.cache -.phpunit.result.cache +.phpunit.cache/ composer.lock *.sqlite .preload.php diff --git a/composer.json b/composer.json index f08e68c..7235962 100644 --- a/composer.json +++ b/composer.json @@ -47,7 +47,7 @@ "gedmo/doctrine-extensions": "^2.4|^3.0", "matthiasnoback/symfony-dependency-injection-test": "^3.1|^4.0|^5.0", "nyholm/symfony-bundle-test": "^2.0|^3.0", - "phpunit/phpunit": "^9.0", + "phpunit/phpunit": "^11.0", "symfony/browser-kit": "^5.4|^6.0|^7.0", "symfony/css-selector": "^5.4|^6.0|^7.0", "symfony/framework-bundle": "^5.4|^6.0|^7.0", diff --git a/phpunit.xml.dist b/phpunit.xml similarity index 65% rename from phpunit.xml.dist rename to phpunit.xml index 8159e05..75504ee 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml @@ -1,17 +1,9 @@ + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.3/phpunit.xsd" bootstrap="tests/bootstrap.php" + executionOrder="depends,defects" beStrictAboutOutputDuringTests="true" cacheDirectory=".phpunit.cache" + requireCoverageMetadata="false" beStrictAboutCoverageMetadata="true"> - - src - @@ -22,12 +14,17 @@ - + - + tests + + + src + + From 06649227185bcedfca25904f87119329bc57a478 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 17:12:17 +0200 Subject: [PATCH 10/16] temporary fix for PHPUnit 11.x --- tests/App/config/bootstrap.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/App/config/bootstrap.php b/tests/App/config/bootstrap.php index 6ac7ee1..fa3985d 100644 --- a/tests/App/config/bootstrap.php +++ b/tests/App/config/bootstrap.php @@ -23,3 +23,8 @@ $_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev'; $_SERVER['APP_DEBUG'] ??= $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV']; $_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0'; + +// TODO: temporary fix for PHPUnit 11.x +// cf. https://github.com/symfony/symfony/issues/53812 +use Symfony\Component\ErrorHandler\ErrorHandler; +set_exception_handler([new ErrorHandler(), 'handleException']); From ef11499168b21fa827afba3ab4a1ae7ef3732bc6 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 17:15:00 +0200 Subject: [PATCH 11/16] Adjusted deps --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 7235962..8be2f07 100644 --- a/composer.json +++ b/composer.json @@ -45,7 +45,7 @@ }, "require-dev": { "gedmo/doctrine-extensions": "^2.4|^3.0", - "matthiasnoback/symfony-dependency-injection-test": "^3.1|^4.0|^5.0", + "matthiasnoback/symfony-dependency-injection-test": "^6.0", "nyholm/symfony-bundle-test": "^2.0|^3.0", "phpunit/phpunit": "^11.0", "symfony/browser-kit": "^5.4|^6.0|^7.0", From c63232f24d7a99e8efffd3ef19e6edee8e117337 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 17:19:53 +0200 Subject: [PATCH 12/16] Same Rector config as `damienharper/auditor` --- rector.php | 80 +++++++++++++++++++----------------------------------- 1 file changed, 28 insertions(+), 52 deletions(-) diff --git a/rector.php b/rector.php index 4dde3b0..ad1f83e 100644 --- a/rector.php +++ b/rector.php @@ -3,63 +3,39 @@ declare(strict_types=1); use Rector\Config\RectorConfig; -use Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector; use Rector\Doctrine\Set\DoctrineSetList; -use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector; use Rector\PHPUnit\Set\PHPUnitSetList; -use Rector\Set\ValueObject\LevelSetList; -use Rector\Set\ValueObject\SetList; -use Rector\Symfony\Rector\Class_\MakeCommandLazyRector; use Rector\Symfony\Set\SymfonySetList; -use Rector\Transform\Rector\Attribute\AttributeKeyToClassConstFetchRector; -use Rector\TypeDeclaration\Rector\ClassMethod\AddArrayParamDocTypeRector; -use Rector\TypeDeclaration\Rector\ClassMethod\AddArrayReturnDocTypeRector; -return static function (RectorConfig $rectorConfig): void { - $rectorConfig->paths([__DIR__.'/src', __DIR__.'/tests']); - - // Do not try to change simple property init and assign to constructor promotion - // to make code easier to read (no more class with properties declared both - // at the start of the class and in the constructor) - $rectorConfig->skip([ - ClassPropertyAssignToConstructorPromotionRector::class, - RemoveUnusedPrivatePropertyRector::class, - AttributeKeyToClassConstFetchRector::class, - MakeCommandLazyRector::class, - AddArrayReturnDocTypeRector::class, - AddArrayParamDocTypeRector::class, +return RectorConfig::configure() + ->withPaths([__DIR__.'/src', __DIR__.'/tests']) + ->withSkip([ __DIR__.'/tests/App/var/*', - ]); - - // PHP rules - $rectorConfig->sets([ - LevelSetList::UP_TO_PHP_80, - SetList::CODE_QUALITY, - SetList::DEAD_CODE, - SetList::CODING_STYLE, - SetList::TYPE_DECLARATION, - ]); - - // Symfony rules - $rectorConfig->sets([ + ]) + ->withPhpSets(php82: true) + ->withPreparedSets( + deadCode: true, + codeQuality: true, + codingStyle: true, + typeDeclarations: true, + privatization: true, + instanceOf: true, + earlyReturn: true, + phpunitCodeQuality: true, + doctrineCodeQuality: true, + symfonyCodeQuality: true, + phpunit: true, + ) + ->withSets([ SymfonySetList::SYMFONY_54, - SymfonySetList::SYMFONY_CODE_QUALITY, - SymfonySetList::SYMFONY_CONSTRUCTOR_INJECTION, - SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES, - ]); - - // Doctrine rules - $rectorConfig->sets([ + PHPUnitSetList::PHPUNIT_110, DoctrineSetList::DOCTRINE_CODE_QUALITY, - DoctrineSetList::DOCTRINE_DBAL_30, DoctrineSetList::DOCTRINE_ORM_29, - DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES, - ]); - - // PHPUnit rules - $rectorConfig->sets([ - PHPUnitSetList::PHPUNIT_91, - PHPUnitSetList::PHPUNIT_CODE_QUALITY, - PHPUnitSetList::PHPUNIT_YIELD_DATA_PROVIDER, - ]); -}; + DoctrineSetList::DOCTRINE_DBAL_40, + ]) + ->withAttributesSets( + symfony: true, + doctrine: true, + phpunit: true, + ) +; From 9ef86cc52b765198d3749ca286d87d4b686374c8 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 17:41:15 +0200 Subject: [PATCH 13/16] DHMiddleware has been renamed to AuditorMiddleware --- .../DoctrineProviderConfigurationCompilerPass.php | 14 +++++++------- .../DoctrineMiddlewareCompilerPassTest.php | 10 +++++----- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php b/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php index ffeb7fd..bf29f84 100644 --- a/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php +++ b/src/DependencyInjection/Compiler/DoctrineProviderConfigurationCompilerPass.php @@ -20,7 +20,7 @@ /** @see DoctrineMiddlewareCompilerPassTest */ class DoctrineProviderConfigurationCompilerPass implements CompilerPassInterface { - private bool $isDHMiddlewareSupported = false; + private bool $isAuditorMiddlewareSupported = false; public function process(ContainerBuilder $container): void { @@ -54,7 +54,7 @@ public function process(ContainerBuilder $container): void \assert(\is_array($config) && \array_key_exists('auditing_services', $config)); - $this->registerDHMiddleware($container); + $this->registerAuditorMiddleware($container); foreach (array_unique($config['auditing_services']) as $entityManagerName) { $entityManagerName = str_replace('@', '', $entityManagerName); @@ -72,21 +72,21 @@ public function process(ContainerBuilder $container): void $container->setDefinition(AnnotationLoader::class, $annotationLoaderDefinition); $providerDefinition->addMethodCall('registerAuditingService', [$serviceReference]); - $this->configureDHMiddleware($container, $entityManagerName); + $this->configureAuditorMiddleware($container, $entityManagerName); } } - private function registerDHMiddleware(ContainerBuilder $container): void + private function registerAuditorMiddleware(ContainerBuilder $container): void { if (interface_exists(Middleware::class) && class_exists(AuditorMiddleware::class)) { - $this->isDHMiddlewareSupported = true; + $this->isAuditorMiddlewareSupported = true; $container->register('doctrine.dbal.auditor_middleware', AuditorMiddleware::class); } } - private function configureDHMiddleware(ContainerBuilder $container, string $entityManagerName): void + private function configureAuditorMiddleware(ContainerBuilder $container, string $entityManagerName): void { - if (!$this->isDHMiddlewareSupported) { + if (!$this->isAuditorMiddlewareSupported) { return; } diff --git a/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php b/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php index 55b33f2..56a3f21 100644 --- a/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/DoctrineMiddlewareCompilerPassTest.php @@ -15,26 +15,26 @@ use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension; use Doctrine\DBAL\Driver\Middleware; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase; +use PHPUnit\Framework\Attributes\Small; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class DoctrineMiddlewareCompilerPassTest extends AbstractCompilerPassTestCase { public function testCompilerPass(): void { if (!interface_exists(Middleware::class) || !class_exists(AuditorMiddleware::class)) { - self::markTestSkipped('DHMiddleware isn\'t supported'); + self::markTestSkipped("AuditorMiddleware isn't supported"); } + $this->container->setParameter('kernel.cache_dir', sys_get_temp_dir()); $this->container->setParameter('kernel.debug', false); $this->container->setParameter('kernel.bundles', []); + $doctrineConfig = [ 'dbal' => [ 'default_connection' => 'default', From 5c47c30a71637b1896abf43c75689bff207df455 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Fri, 6 Sep 2024 17:42:25 +0200 Subject: [PATCH 14/16] Rector + PHP-CS-Fixer + PHPStan --- .php-cs-fixer.dist.php | 1 + phpunit.xml | 48 +++--- src/Controller/ViewerController.php | 12 +- src/DependencyInjection/Configuration.php | 2 +- src/Event/ConsoleEventSubscriber.php | 13 +- src/Event/ViewerEventSubscriber.php | 7 +- src/Routing/RoutingLoader.php | 17 +- src/Security/RoleChecker.php | 10 +- src/Security/SecurityProvider.php | 13 +- src/User/ConsoleUserProvider.php | 2 +- src/User/UserProvider.php | 20 +-- tests/App/Command/CreatePostCommand.php | 5 +- tests/App/config/bootstrap.php | 1 + tests/App/public/index.php | 2 +- tests/Console/ConsoleUserProviderTest.php | 19 +-- tests/Controller/ViewerControllerTest.php | 155 ++++++++---------- tests/DHAuditorBundleTest.php | 53 +++--- .../Compiler/AddProvidersCompilerPassTest.php | 6 +- .../CustomConfigurationCompilerPassTest.php | 6 +- .../StorageConfigurationCompilerPassTest.php | 6 +- tests/Helper/UrlHelperTest.php | 10 +- tests/Twig/Views/MacrosTest.php | 10 +- tests/User/UserProviderTest.php | 17 +- 23 files changed, 167 insertions(+), 268 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 0e39e55..c10118c 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -39,6 +39,7 @@ 'numeric_literal_separator' => true, 'string_implicit_backslashes' => true, // https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/pull/7786 'php_unit_test_case_static_method_calls' => false, + 'php_unit_test_class_requires_covers' => false, ]) ->setFinder( (new Finder()) diff --git a/phpunit.xml b/phpunit.xml index 75504ee..4a1080b 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -3,28 +3,28 @@ xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.3/phpunit.xsd" bootstrap="tests/bootstrap.php" executionOrder="depends,defects" beStrictAboutOutputDuringTests="true" cacheDirectory=".phpunit.cache" requireCoverageMetadata="false" beStrictAboutCoverageMetadata="true"> - - - - - - - - - - - - - - - - - tests - - - - - src - - + + + + + + + + + + + + + + + + + tests + + + + + src + + diff --git a/src/Controller/ViewerController.php b/src/Controller/ViewerController.php index 3b781f1..624e5c1 100644 --- a/src/Controller/ViewerController.php +++ b/src/Controller/ViewerController.php @@ -23,12 +23,7 @@ */ final class ViewerController { - private Environment $environment; - - public function __construct(Environment $environment) - { - $this->environment = $environment; - } + public function __construct(private readonly Environment $environment) {} #[Route(path: '/audit', name: 'dh_auditor_list_audits', methods: ['GET'])] public function listAuditsAction(Reader $reader): Response @@ -76,7 +71,8 @@ public function showEntityHistoryAction(Request $request, Reader $reader, string { \assert(\is_string($request->query->get('page', '1')) || \is_int($request->query->get('page', '1'))); $page = (int) $request->query->get('page', '1'); - $page = $page < 1 ? 1 : $page; + $page = max(1, $page); + $entity = UrlHelper::paramToNamespace($entity); if (!$reader->getProvider()->isAuditable($entity)) { @@ -89,7 +85,7 @@ public function showEntityHistoryAction(Request $request, Reader $reader, string 'page' => $page, 'page_size' => Reader::PAGE_SIZE, ]), $page, Reader::PAGE_SIZE); - } catch (AccessDeniedException $e) { + } catch (AccessDeniedException) { throw new SymfonyAccessDeniedException('Access Denied.'); } diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 1ff7535..411b468 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -67,7 +67,7 @@ private function getProvidersNode(): ArrayNodeDefinition ->validate() ->always() - ->then(static function ($v) { + ->then(static function (array $v) { if (!\array_key_exists('doctrine', $v)) { $v['doctrine'] = []; } diff --git a/src/Event/ConsoleEventSubscriber.php b/src/Event/ConsoleEventSubscriber.php index 66b3e3c..485306e 100644 --- a/src/Event/ConsoleEventSubscriber.php +++ b/src/Event/ConsoleEventSubscriber.php @@ -13,18 +13,7 @@ class ConsoleEventSubscriber implements EventSubscriberInterface { - private ConsoleUserProvider $consoleUserProvider; - - private Configuration $configuration; - - private UserProviderInterface $provider; - - public function __construct(ConsoleUserProvider $consoleUserProvider, Configuration $configuration, UserProviderInterface $provider) - { - $this->consoleUserProvider = $consoleUserProvider; - $this->configuration = $configuration; - $this->provider = $provider; - } + public function __construct(private readonly ConsoleUserProvider $consoleUserProvider, private readonly Configuration $configuration, private readonly UserProviderInterface $provider) {} public static function getSubscribedEvents(): array { diff --git a/src/Event/ViewerEventSubscriber.php b/src/Event/ViewerEventSubscriber.php index 0eaf2eb..7a628d7 100644 --- a/src/Event/ViewerEventSubscriber.php +++ b/src/Event/ViewerEventSubscriber.php @@ -16,12 +16,7 @@ class ViewerEventSubscriber implements EventSubscriberInterface { - private Auditor $auditor; - - public function __construct(Auditor $auditor) - { - $this->auditor = $auditor; - } + public function __construct(private readonly Auditor $auditor) {} public function onKernelController(KernelEvent $event): void { diff --git a/src/Routing/RoutingLoader.php b/src/Routing/RoutingLoader.php index 67c8f0f..ca41f59 100644 --- a/src/Routing/RoutingLoader.php +++ b/src/Routing/RoutingLoader.php @@ -14,17 +14,9 @@ if (BaseKernel::MAJOR_VERSION >= 6) { class RoutingLoader extends Loader { - private AttributeRouteControllerLoader $annotatedRouteControllerLoader; - private bool $isLoaded = false; - private array $configuration; - - public function __construct(AttributeRouteControllerLoader $annotatedRouteController, array $configuration) - { - $this->annotatedRouteControllerLoader = $annotatedRouteController; - $this->configuration = $configuration; - } + public function __construct(private readonly AttributeRouteControllerLoader $annotatedRouteControllerLoader, private array $configuration) {} public function load(mixed $resource, ?string $type = null): RouteCollection { @@ -50,16 +42,13 @@ public function supports(mixed $resource, ?string $type = null): bool } else { class RoutingLoader extends Loader { - private AnnotatedRouteControllerLoader $annotatedRouteControllerLoader; + private readonly AnnotatedRouteControllerLoader $annotatedRouteControllerLoader; private bool $isLoaded = false; - private array $configuration; - - public function __construct(AnnotatedRouteControllerLoader $annotatedRouteController, array $configuration) + public function __construct(AnnotatedRouteControllerLoader $annotatedRouteController, private array $configuration) { $this->annotatedRouteControllerLoader = $annotatedRouteController; - $this->configuration = $configuration; } public function load(mixed $resource, ?string $type = null): RouteCollection diff --git a/src/Security/RoleChecker.php b/src/Security/RoleChecker.php index a8773ab..cd0698b 100644 --- a/src/Security/RoleChecker.php +++ b/src/Security/RoleChecker.php @@ -12,15 +12,7 @@ class RoleChecker implements RoleCheckerInterface { - private AuthorizationCheckerInterface $authorizationChecker; - - private DoctrineProvider $provider; - - public function __construct(AuthorizationCheckerInterface $authorizationChecker, DoctrineProvider $doctrineProvider) - { - $this->authorizationChecker = $authorizationChecker; - $this->provider = $doctrineProvider; - } + public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker, private readonly DoctrineProvider $provider) {} public function __invoke(string $entity, string $scope): bool { diff --git a/src/Security/SecurityProvider.php b/src/Security/SecurityProvider.php index ffc19ec..edccaa0 100644 --- a/src/Security/SecurityProvider.php +++ b/src/Security/SecurityProvider.php @@ -7,19 +7,12 @@ use DH\Auditor\Security\SecurityProviderInterface; use Symfony\Bundle\SecurityBundle\Security\FirewallConfig; use Symfony\Bundle\SecurityBundle\Security\FirewallMap; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; class SecurityProvider implements SecurityProviderInterface { - private RequestStack $requestStack; - - private FirewallMap $firewallMap; - - public function __construct(RequestStack $requestStack, FirewallMap $firewallMap) - { - $this->requestStack = $requestStack; - $this->firewallMap = $firewallMap; - } + public function __construct(private readonly RequestStack $requestStack, private readonly FirewallMap $firewallMap) {} public function __invoke(): array { @@ -27,7 +20,7 @@ public function __invoke(): array $firewallName = null; $request = $this->requestStack->getCurrentRequest(); - if (null !== $request) { + if ($request instanceof Request) { $firewallConfig = $this->firewallMap->getFirewallConfig($request); $clientIp = $request->getClientIp(); diff --git a/src/User/ConsoleUserProvider.php b/src/User/ConsoleUserProvider.php index 486163d..5d75a31 100644 --- a/src/User/ConsoleUserProvider.php +++ b/src/User/ConsoleUserProvider.php @@ -27,6 +27,6 @@ public function __invoke(): ?UserInterface public function setCurrentCommand(?Command $command): void { - $this->currentCommand = null === $command ? null : $command->getName(); + $this->currentCommand = $command instanceof Command ? $command->getName() : null; } } diff --git a/src/User/UserProvider.php b/src/User/UserProvider.php index 5f6f81a..c43e8e7 100644 --- a/src/User/UserProvider.php +++ b/src/User/UserProvider.php @@ -9,16 +9,12 @@ use DH\Auditor\User\UserProviderInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\User\UserInterface; class UserProvider implements UserProviderInterface { - private TokenStorageInterface $tokenStorage; - - public function __construct(TokenStorageInterface $tokenStorage) - { - $this->tokenStorage = $tokenStorage; - } + public function __construct(private readonly TokenStorageInterface $tokenStorage) {} public function __invoke(): ?AuditorUserInterface { @@ -53,6 +49,7 @@ private function getUsername(UserInterface $user): string if (method_exists($user, 'getUserIdentifier')) { return $user->getUserIdentifier(); } + if (method_exists($user, 'getUsername')) { return $user->getUsername(); } @@ -64,20 +61,15 @@ private function getTokenUser(): ?UserInterface { try { $token = $this->tokenStorage->getToken(); - } catch (\Exception $e) { + } catch (\Exception) { $token = null; } - if (null === $token) { + if (!$token instanceof TokenInterface) { return null; } - $tokenUser = $token->getUser(); - if ($tokenUser instanceof UserInterface) { - return $tokenUser; - } - - return null; + return $token->getUser(); } private function getImpersonatorUser(): ?UserInterface diff --git a/tests/App/Command/CreatePostCommand.php b/tests/App/Command/CreatePostCommand.php index 7d5db33..2bb65ad 100644 --- a/tests/App/Command/CreatePostCommand.php +++ b/tests/App/Command/CreatePostCommand.php @@ -13,12 +13,9 @@ class CreatePostCommand extends Command { - private DoctrineProvider $doctrineProvider; - - public function __construct(DoctrineProvider $doctrineProvider) + public function __construct(private readonly DoctrineProvider $doctrineProvider) { parent::__construct(); - $this->doctrineProvider = $doctrineProvider; } protected function configure(): void diff --git a/tests/App/config/bootstrap.php b/tests/App/config/bootstrap.php index fa3985d..543da22 100644 --- a/tests/App/config/bootstrap.php +++ b/tests/App/config/bootstrap.php @@ -27,4 +27,5 @@ // TODO: temporary fix for PHPUnit 11.x // cf. https://github.com/symfony/symfony/issues/53812 use Symfony\Component\ErrorHandler\ErrorHandler; + set_exception_handler([new ErrorHandler(), 'handleException']); diff --git a/tests/App/public/index.php b/tests/App/public/index.php index 7e45fbf..0248744 100644 --- a/tests/App/public/index.php +++ b/tests/App/public/index.php @@ -15,7 +15,7 @@ } if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) { - Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); + Request::setTrustedProxies(explode(',', (string) $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); } if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) { diff --git a/tests/Console/ConsoleUserProviderTest.php b/tests/Console/ConsoleUserProviderTest.php index d4c2ada..0c24052 100644 --- a/tests/Console/ConsoleUserProviderTest.php +++ b/tests/Console/ConsoleUserProviderTest.php @@ -8,18 +8,15 @@ use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Post; use DH\Auditor\Tests\Provider\Doctrine\Traits\ReaderTrait; use DH\Auditor\Tests\Provider\Doctrine\Traits\Schema\BlogSchemaSetupTrait; -use DH\AuditorBundle\DHAuditorBundle; +use PHPUnit\Framework\Attributes\Small; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\Console\Tester\ApplicationTester; /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class ConsoleUserProviderTest extends KernelTestCase { use BlogSchemaSetupTrait; @@ -52,6 +49,7 @@ public function testBlameUser(): void $kernel = self::bootKernel(); $application = new Application($kernel); $application->setAutoExit(false); + $tester = new ApplicationTester($application); $tester->run(['app:post:create']); @@ -62,14 +60,9 @@ public function testBlameUser(): void // get history $entries = $this->createReader()->createQuery(Post::class)->execute(); - self::assertNotEmpty($entries, 'There are audit entries'); - self::assertSame('app:post:create', $entries[0]->getUsername(), 'Username is OK'); - self::assertSame('command', $entries[0]->getUserId(), 'User ID is OK'); - } - - protected function getBundleClass() - { - return DHAuditorBundle::class; + $this->assertNotEmpty($entries, 'There are audit entries'); + $this->assertSame('app:post:create', $entries[0]->getUsername(), 'Username is OK'); + $this->assertSame('command', $entries[0]->getUserId(), 'User ID is OK'); } private function createAndInitDoctrineProvider(): void diff --git a/tests/Controller/ViewerControllerTest.php b/tests/Controller/ViewerControllerTest.php index 84bce42..09dec44 100644 --- a/tests/Controller/ViewerControllerTest.php +++ b/tests/Controller/ViewerControllerTest.php @@ -12,6 +12,8 @@ use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Tag; use DH\Auditor\Tests\Provider\Doctrine\Traits\ReaderTrait; use DH\Auditor\Tests\Provider\Doctrine\Traits\Schema\BlogSchemaSetupTrait; +use PHPUnit\Framework\Attributes\Depends; +use PHPUnit\Framework\Attributes\Small; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\BrowserKit\AbstractBrowser; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -22,11 +24,8 @@ /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class ViewerControllerTest extends WebTestCase { use BlogSchemaSetupTrait; @@ -65,16 +64,16 @@ public function testListAuditsAnonymously(): void $crawler = $this->client->request('GET', '/audit'); // asserts that the response status code is 2xx - self::assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); + $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); - self::assertPageTitleContains('auditor', 'Title is auditor'); + $this->assertPageTitleContains('auditor', 'Title is auditor'); $breadcrumbs = $crawler->filter('nav > ol > li'); - self::assertSame(1, $breadcrumbs->count(), 'Nav has 1 item.'); - self::assertSame('Home', trim($breadcrumbs->text()), 'Nav has 1 item: Home'); + $this->assertCount(1, $breadcrumbs, 'Nav has 1 item.'); + $this->assertSame('Home', trim($breadcrumbs->text()), 'Nav has 1 item: Home'); $cards = $crawler->filter('div.auditor-audits > div'); - self::assertSame(4, $cards->count(), 'There are 4 entity audits.'); + $this->assertCount(4, $cards, 'There are 4 entity audits.'); $expected = [ [Author::class, 'author', '7 operation(s)', 'View audit'], @@ -84,38 +83,36 @@ public function testListAuditsAnonymously(): void ]; $cards->each(static function ($row, $rowIndex) use ($expected): void { $cell = $row->filter('div > h3 > code'); - self::assertSame($expected[$rowIndex][0], trim($cell->text()), 'Entity is OK'); + self::assertSame($expected[$rowIndex][0], trim((string) $cell->text()), 'Entity is OK'); $cell = $row->filter('div > p'); - self::assertSame($expected[$rowIndex][1], trim($cell->text()), 'Tablename is OK'); + self::assertSame($expected[$rowIndex][1], trim((string) $cell->text()), 'Tablename is OK'); $cell = $row->filter('div > dl > dt'); - self::assertSame($expected[$rowIndex][2], trim($cell->text()), 'Operation count is OK'); + self::assertSame($expected[$rowIndex][2], trim((string) $cell->text()), 'Operation count is OK'); $cell = $row->filter('div > dl > dd > a'); - self::assertSame($expected[$rowIndex][3], trim($cell->text()), 'Link is OK'); + self::assertSame($expected[$rowIndex][3], trim((string) $cell->text()), 'Link is OK'); }); } - /** - * @depends testListAuditsAnonymously - */ + #[Depends('testListAuditsAnonymously')] public function testListAuditsWithRoleNotGrantedForAuthorAuditViewing(): void { $this->login(['ROLE_USER']); $crawler = $this->client->request('GET', '/audit'); // asserts that the response status code is 2xx - self::assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); + $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); - self::assertPageTitleContains('auditor', 'Title is auditor'); + $this->assertPageTitleContains('auditor', 'Title is auditor'); $breadcrumbs = $crawler->filter('nav > ol > li'); - self::assertSame(1, $breadcrumbs->count(), 'Nav has 1 item.'); - self::assertSame('Home', trim($breadcrumbs->text()), 'Nav has 1 item: Home'); + $this->assertCount(1, $breadcrumbs, 'Nav has 1 item.'); + $this->assertSame('Home', trim($breadcrumbs->text()), 'Nav has 1 item: Home'); $cards = $crawler->filter('div.auditor-audits > div'); - self::assertSame(3, $cards->count(), 'There are 3 entity audits.'); + $this->assertCount(3, $cards, 'There are 3 entity audits.'); $expected = [ [Comment::class, 'comment', '3 operation(s)', 'View audit'], @@ -124,38 +121,36 @@ public function testListAuditsWithRoleNotGrantedForAuthorAuditViewing(): void ]; $cards->each(static function ($row, $rowIndex) use ($expected): void { $cell = $row->filter('div > h3 > code'); - self::assertSame($expected[$rowIndex][0], trim($cell->text()), 'Entity is OK'); + self::assertSame($expected[$rowIndex][0], trim((string) $cell->text()), 'Entity is OK'); $cell = $row->filter('div > p'); - self::assertSame($expected[$rowIndex][1], trim($cell->text()), 'Tablename is OK'); + self::assertSame($expected[$rowIndex][1], trim((string) $cell->text()), 'Tablename is OK'); $cell = $row->filter('div > dl > dt'); - self::assertSame($expected[$rowIndex][2], trim($cell->text()), 'Operation count is OK'); + self::assertSame($expected[$rowIndex][2], trim((string) $cell->text()), 'Operation count is OK'); $cell = $row->filter('div > dl > dd > a'); - self::assertSame($expected[$rowIndex][3], trim($cell->text()), 'Link is OK'); + self::assertSame($expected[$rowIndex][3], trim((string) $cell->text()), 'Link is OK'); }); } - /** - * @depends testListAuditsWithRoleNotGrantedForAuthorAuditViewing - */ + #[Depends('testListAuditsWithRoleNotGrantedForAuthorAuditViewing')] public function testListAuditsWithRoleGrantedForAuthorAuditViewing(): void { $this->login(['ROLE1']); $crawler = $this->client->request('GET', '/audit'); // asserts that the response status code is 2xx - self::assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); + $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); - self::assertPageTitleContains('auditor', 'Title is auditor'); + $this->assertPageTitleContains('auditor', 'Title is auditor'); $breadcrumbs = $crawler->filter('nav > ol > li'); - self::assertSame(1, $breadcrumbs->count(), 'Nav has 1 item.'); - self::assertSame('Home', trim($breadcrumbs->text()), 'Nav has 1 item: Home'); + $this->assertCount(1, $breadcrumbs, 'Nav has 1 item.'); + $this->assertSame('Home', trim($breadcrumbs->text()), 'Nav has 1 item: Home'); $cards = $crawler->filter('div.auditor-audits > div'); - self::assertSame(4, $cards->count(), 'There are 4 entity audits.'); + $this->assertCount(4, $cards, 'There are 4 entity audits.'); $expected = [ [Author::class, 'author', '7 operation(s)', 'View audit'], @@ -165,87 +160,77 @@ public function testListAuditsWithRoleGrantedForAuthorAuditViewing(): void ]; $cards->each(static function ($row, $rowIndex) use ($expected): void { $cell = $row->filter('div > h3 > code'); - self::assertSame($expected[$rowIndex][0], trim($cell->text()), 'Entity is OK'); + self::assertSame($expected[$rowIndex][0], trim((string) $cell->text()), 'Entity is OK'); $cell = $row->filter('div > p'); - self::assertSame($expected[$rowIndex][1], trim($cell->text()), 'Tablename is OK'); + self::assertSame($expected[$rowIndex][1], trim((string) $cell->text()), 'Tablename is OK'); $cell = $row->filter('div > dl > dt'); - self::assertSame($expected[$rowIndex][2], trim($cell->text()), 'Operation count is OK'); + self::assertSame($expected[$rowIndex][2], trim((string) $cell->text()), 'Operation count is OK'); $cell = $row->filter('div > dl > dd > a'); - self::assertSame($expected[$rowIndex][3], trim($cell->text()), 'Link is OK'); + self::assertSame($expected[$rowIndex][3], trim((string) $cell->text()), 'Link is OK'); }); } - /** - * @depends testListAuditsAnonymously - */ + #[Depends('testListAuditsAnonymously')] public function testShowEntityHistoryAnonymously(): void { $this->login(); $crawler = $this->client->request('GET', '/audit/DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author'); // asserts that the response status code is 2xx - self::assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); + $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); - self::assertPageTitleContains('auditor', 'Title is auditor'); + $this->assertPageTitleContains('auditor', 'Title is auditor'); $breadcrumbs = $crawler->filter('nav > ol > li'); - self::assertSame(2, $breadcrumbs->count(), 'Nav has 2 item.'); - self::assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); - self::assertSame(Author::class, trim($breadcrumbs->eq(1)->children('div > a > code')->text()), 'Nav has 1 item: '.Author::class); + $this->assertCount(2, $breadcrumbs, 'Nav has 2 item.'); + $this->assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); + $this->assertSame(Author::class, trim($breadcrumbs->eq(1)->children('div > a > code')->text()), 'Nav has 1 item: '.Author::class); } - /** - * @depends testShowEntityHistoryAnonymously - */ + #[Depends('testShowEntityHistoryAnonymously')] public function testShowEntityHistoryWithRoleNotGrantedForAuthorAuditViewing(): void { $this->login(['ROLE_USER']); $this->client->catchExceptions(false); $this->expectException(AccessDeniedException::class); - $crawler = $this->client->request('GET', '/audit/DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author'); + $this->client->request('GET', '/audit/DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author'); - self::assertSame(403, $this->client->getResponse()->getStatusCode(), 'Response status is 403'); + $this->assertSame(403, $this->client->getResponse()->getStatusCode(), 'Response status is 403'); } - /** - * @depends testShowEntityHistoryWithRoleNotGrantedForAuthorAuditViewing - */ + #[Depends('testShowEntityHistoryWithRoleNotGrantedForAuthorAuditViewing')] public function testShowEntityHistoryWithRoleGrantedForAuthorAuditViewing(): void { $this->login(['ROLE1']); $crawler = $this->client->request('GET', '/audit/DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author'); // asserts that the response status code is 2xx - self::assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); + $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); - self::assertPageTitleContains('auditor', 'Title is auditor'); + $this->assertPageTitleContains('auditor', 'Title is auditor'); $breadcrumbs = $crawler->filter('nav > ol > li'); - self::assertSame(2, $breadcrumbs->count(), 'Nav has 2 item.'); - self::assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); - self::assertSame(Author::class, trim($breadcrumbs->eq(1)->children('div > a > code')->text()), 'Nav has 1 item: '.Author::class); + $this->assertCount(2, $breadcrumbs, 'Nav has 2 item.'); + $this->assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); + $this->assertSame(Author::class, trim($breadcrumbs->eq(1)->children('div > a > code')->text()), 'Nav has 1 item: '.Author::class); } - /** - * @depends testShowEntityHistoryWithRoleGrantedForAuthorAuditViewing - */ + #[Depends('testShowEntityHistoryWithRoleGrantedForAuthorAuditViewing')] public function testShowEntityHistoryOfUnauditedEntity(): void { $this->login(); $this->client->catchExceptions(false); $this->expectException(NotFoundHttpException::class); - $crawler = $this->client->request('GET', '/audit/DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Damn'); + $this->client->request('GET', '/audit/DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Damn'); - self::assertSame(404, $this->client->getResponse()->getStatusCode(), 'Response status is 404'); + $this->assertSame(404, $this->client->getResponse()->getStatusCode(), 'Response status is 404'); } - /** - * @depends testShowEntityHistoryWithRoleNotGrantedForAuthorAuditViewing - */ + #[Depends('testShowEntityHistoryWithRoleNotGrantedForAuthorAuditViewing')] public function testShowTransactionHistoryAnonymously(): void { $reader = $this->createReader(); @@ -258,25 +243,23 @@ public function testShowTransactionHistoryAnonymously(): void $crawler = $this->client->request('GET', '/audit/transaction/'.$first->getTransactionHash()); // asserts that the response status code is 2xx - self::assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); + $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); - self::assertPageTitleContains('auditor', 'Title is auditor'); + $this->assertPageTitleContains('auditor', 'Title is auditor'); $breadcrumbs = $crawler->filter('nav > ol > li'); - self::assertSame(2, $breadcrumbs->count(), 'Nav has 2 item.'); - self::assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); - self::assertSame($first->getTransactionHash(), trim($breadcrumbs->eq(1)->children('div > a')->text()), 'Nav has 1 item: '.$first->getTransactionHash()); + $this->assertCount(2, $breadcrumbs, 'Nav has 2 item.'); + $this->assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); + $this->assertSame($first->getTransactionHash(), trim($breadcrumbs->eq(1)->children('div > a')->text()), 'Nav has 1 item: '.$first->getTransactionHash()); $sections = $crawler->filter('.flow-root > div'); - self::assertSame(4, $sections->count(), 'There are 3 sections.'); - self::assertSame(Author::class, trim($sections->eq(0)->children('div > code')->text()), Author::class); - self::assertSame(Post::class, trim($sections->eq(1)->children('div > code')->text()), Post::class); - self::assertSame(Comment::class, trim($sections->eq(2)->children('div > code')->text()), Comment::class); + $this->assertCount(4, $sections, 'There are 3 sections.'); + $this->assertSame(Author::class, trim($sections->eq(0)->children('div > code')->text()), Author::class); + $this->assertSame(Post::class, trim($sections->eq(1)->children('div > code')->text()), Post::class); + $this->assertSame(Comment::class, trim($sections->eq(2)->children('div > code')->text()), Comment::class); } - /** - * @depends testShowTransactionHistoryAnonymously - */ + #[Depends('testShowTransactionHistoryAnonymously')] public function testShowTransactionHistoryWithRoleNotGrantedForAuthorAuditViewing(): void { $reader = $this->createReader(); @@ -289,19 +272,19 @@ public function testShowTransactionHistoryWithRoleNotGrantedForAuthorAuditViewin $crawler = $this->client->request('GET', '/audit/transaction/'.$first->getTransactionHash()); // asserts that the response status code is 2xx - self::assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); + $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Response status is 2xx'); - self::assertPageTitleContains('auditor', 'Title is auditor'); + $this->assertPageTitleContains('auditor', 'Title is auditor'); $breadcrumbs = $crawler->filter('nav > ol > li'); - self::assertSame(2, $breadcrumbs->count(), 'Nav has 2 item.'); - self::assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); - self::assertSame($first->getTransactionHash(), trim($breadcrumbs->eq(1)->children('div > a')->text()), 'Nav has 1 item: '.$first->getTransactionHash()); + $this->assertCount(2, $breadcrumbs, 'Nav has 2 item.'); + $this->assertSame('Home', trim($breadcrumbs->eq(0)->text()), 'Nav has 1 item: Home'); + $this->assertSame($first->getTransactionHash(), trim($breadcrumbs->eq(1)->children('div > a')->text()), 'Nav has 1 item: '.$first->getTransactionHash()); $sections = $crawler->filter('.flow-root > div'); - self::assertSame(3, $sections->count(), 'There are 2 sections.'); - self::assertSame(Post::class, trim($sections->eq(0)->children('div > code')->text()), Post::class); - self::assertSame(Comment::class, trim($sections->eq(1)->children('div > code')->text()), Comment::class); + $this->assertCount(3, $sections, 'There are 2 sections.'); + $this->assertSame(Post::class, trim($sections->eq(0)->children('div > code')->text()), Post::class); + $this->assertSame(Comment::class, trim($sections->eq(1)->children('div > code')->text()), Comment::class); } private function login(array $roles = []): void diff --git a/tests/DHAuditorBundleTest.php b/tests/DHAuditorBundleTest.php index c01726d..7968689 100644 --- a/tests/DHAuditorBundleTest.php +++ b/tests/DHAuditorBundleTest.php @@ -16,6 +16,7 @@ use DH\AuditorBundle\Event\ConsoleEventSubscriber; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; use Nyholm\BundleTest\TestKernel; +use PHPUnit\Framework\Attributes\Small; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Bundle\SecurityBundle\SecurityBundle; use Symfony\Bundle\TwigBundle\TwigBundle; @@ -24,17 +25,14 @@ /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class DHAuditorBundleTest extends KernelTestCase { public function testInitBundle(): void { // Boot the kernel with a config closure, the handleOptions call in createKernel is important for that to work - $kernel = self::bootKernel(['config' => static function (TestKernel $kernel) { + self::bootKernel(['config' => static function (TestKernel $kernel): void { // Add some other bundles we depend on $kernel->addTestBundle(DoctrineBundle::class); $kernel->addTestBundle(SecurityBundle::class); @@ -54,40 +52,35 @@ public function testInitBundle(): void // Get the container $container = self::getContainer(); - self::assertTrue($container->has(AuditorConfiguration::class)); - self::assertInstanceOf(AuditorConfiguration::class, $container->get(AuditorConfiguration::class)); + $this->assertTrue($container->has(AuditorConfiguration::class)); + $this->assertInstanceOf(AuditorConfiguration::class, $container->get(AuditorConfiguration::class)); - self::assertTrue($container->has(Auditor::class)); - self::assertInstanceOf(Auditor::class, $container->get(Auditor::class)); + $this->assertTrue($container->has(Auditor::class)); + $this->assertInstanceOf(Auditor::class, $container->get(Auditor::class)); - self::assertTrue($container->has(DoctrineProviderConfiguration::class)); - self::assertInstanceOf(DoctrineProviderConfiguration::class, $container->get(DoctrineProviderConfiguration::class)); + $this->assertTrue($container->has(DoctrineProviderConfiguration::class)); + $this->assertInstanceOf(DoctrineProviderConfiguration::class, $container->get(DoctrineProviderConfiguration::class)); - self::assertTrue($container->has(DoctrineProvider::class)); - self::assertInstanceOf(DoctrineProvider::class, $container->get(DoctrineProvider::class)); + $this->assertTrue($container->has(DoctrineProvider::class)); + $this->assertInstanceOf(DoctrineProvider::class, $container->get(DoctrineProvider::class)); - self::assertTrue($container->has('dh_auditor.provider.doctrine')); - self::assertInstanceOf(DoctrineProvider::class, $container->get('dh_auditor.provider.doctrine')); + $this->assertTrue($container->has('dh_auditor.provider.doctrine')); + $this->assertInstanceOf(DoctrineProvider::class, $container->get('dh_auditor.provider.doctrine')); - self::assertTrue($container->has(Reader::class)); - self::assertInstanceOf(Reader::class, $container->get(Reader::class)); + $this->assertTrue($container->has(Reader::class)); + $this->assertInstanceOf(Reader::class, $container->get(Reader::class)); - self::assertTrue($container->has(TableSchemaListener::class)); - self::assertInstanceOf(TableSchemaListener::class, $container->get(TableSchemaListener::class)); + $this->assertTrue($container->has(TableSchemaListener::class)); + $this->assertInstanceOf(TableSchemaListener::class, $container->get(TableSchemaListener::class)); - self::assertTrue($container->has(CreateSchemaListener::class)); - self::assertInstanceOf(CreateSchemaListener::class, $container->get(CreateSchemaListener::class)); + $this->assertTrue($container->has(CreateSchemaListener::class)); + $this->assertInstanceOf(CreateSchemaListener::class, $container->get(CreateSchemaListener::class)); - self::assertTrue($container->has(ViewerController::class)); - self::assertInstanceOf(ViewerController::class, $container->get(ViewerController::class)); + $this->assertTrue($container->has(ViewerController::class)); + $this->assertInstanceOf(ViewerController::class, $container->get(ViewerController::class)); - self::assertTrue($container->has(ConsoleEventSubscriber::class)); - self::assertInstanceOf(ConsoleEventSubscriber::class, $container->get(ConsoleEventSubscriber::class)); - } - - protected function getBundleClass(): string - { - return DHAuditorBundle::class; + $this->assertTrue($container->has(ConsoleEventSubscriber::class)); + $this->assertInstanceOf(ConsoleEventSubscriber::class, $container->get(ConsoleEventSubscriber::class)); } protected static function getKernelClass(): string diff --git a/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php b/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php index b82dfd3..837eb17 100644 --- a/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/AddProvidersCompilerPassTest.php @@ -6,15 +6,13 @@ use DH\AuditorBundle\DependencyInjection\Compiler\AddProviderCompilerPass; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase; +use PHPUnit\Framework\Attributes\Small; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class AddProvidersCompilerPassTest extends AbstractCompilerPassTestCase { protected function registerCompilerPass(ContainerBuilder $container): void diff --git a/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php b/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php index 3247aa1..eb2e6fc 100644 --- a/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/CustomConfigurationCompilerPassTest.php @@ -12,17 +12,15 @@ use DH\AuditorBundle\DependencyInjection\Compiler\AddProviderCompilerPass; use DH\AuditorBundle\DependencyInjection\Compiler\CustomConfigurationCompilerPass; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase; +use PHPUnit\Framework\Attributes\Small; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class CustomConfigurationCompilerPassTest extends AbstractCompilerPassTestCase { public function testCompilerPass(): void diff --git a/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php b/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php index 23b93f8..8ceb3ca 100644 --- a/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/StorageConfigurationCompilerPassTest.php @@ -6,15 +6,13 @@ use DH\AuditorBundle\DependencyInjection\Compiler\DoctrineProviderConfigurationCompilerPass; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase; +use PHPUnit\Framework\Attributes\Small; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class StorageConfigurationCompilerPassTest extends AbstractCompilerPassTestCase { protected function registerCompilerPass(ContainerBuilder $container): void diff --git a/tests/Helper/UrlHelperTest.php b/tests/Helper/UrlHelperTest.php index 7ae8f41..4254bef 100644 --- a/tests/Helper/UrlHelperTest.php +++ b/tests/Helper/UrlHelperTest.php @@ -6,24 +6,22 @@ use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Author; use DH\AuditorBundle\Helper\UrlHelper; +use PHPUnit\Framework\Attributes\Small; use PHPUnit\Framework\TestCase; /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class UrlHelperTest extends TestCase { public function testParamToNamespace(): void { - self::assertSame(Author::class, UrlHelper::paramToNamespace('DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author'), 'AuditHelper::paramToNamespace() is ok.'); + $this->assertSame(Author::class, UrlHelper::paramToNamespace('DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author'), 'AuditHelper::paramToNamespace() is ok.'); } public function testNamespaceToParam(): void { - self::assertSame('DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author', UrlHelper::namespaceToParam(Author::class), 'AuditHelper::namespaceToParam() is ok.'); + $this->assertSame('DH-Auditor-Tests-Provider-Doctrine-Fixtures-Entity-Standard-Blog-Author', UrlHelper::namespaceToParam(Author::class), 'AuditHelper::namespaceToParam() is ok.'); } } diff --git a/tests/Twig/Views/MacrosTest.php b/tests/Twig/Views/MacrosTest.php index a1f4d4b..d5553af 100644 --- a/tests/Twig/Views/MacrosTest.php +++ b/tests/Twig/Views/MacrosTest.php @@ -8,17 +8,15 @@ use DH\Auditor\Provider\Doctrine\Auditing\Transaction\AuditTrait; use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Issue112\DummyEntity; use DH\Auditor\Tests\Provider\Doctrine\Traits\Schema\SchemaSetupTrait; +use PHPUnit\Framework\Attributes\Small; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Twig\Environment; use Twig\Extension\StringLoaderExtension; /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class MacrosTest extends KernelTestCase { use AuditTrait; @@ -32,12 +30,14 @@ public function testSummarizeOnTargetWithUnusualPK(): void if (!$twig instanceof Environment) { self::markTestIncomplete('Twig missing'); } + $twig->addExtension(new StringLoaderExtension()); $em = $this->createEntityManager([ __DIR__.'/../../../vendor/damienharper/auditor/tests/Provider/Doctrine/Fixtures/Issue112', ]); $entity = new DummyEntity(); $entity->setPrimaryKey(1); + $entry = Entry::fromArray([ 'diffs' => json_encode([ 'source' => [ @@ -54,7 +54,7 @@ public function testSummarizeOnTargetWithUnusualPK(): void 'entry' => $entry, 'entity' => $entity::class, ]); - self::assertSame($this->getExpected(), trim($response)); + $this->assertSame($this->getExpected(), trim($response)); } private function getTemplateAsString(): string diff --git a/tests/User/UserProviderTest.php b/tests/User/UserProviderTest.php index 7f55d95..3ce450c 100644 --- a/tests/User/UserProviderTest.php +++ b/tests/User/UserProviderTest.php @@ -8,7 +8,7 @@ use DH\Auditor\Tests\Provider\Doctrine\Fixtures\Entity\Standard\Blog\Post; use DH\Auditor\Tests\Provider\Doctrine\Traits\ReaderTrait; use DH\Auditor\Tests\Provider\Doctrine\Traits\Schema\BlogSchemaSetupTrait; -use DH\AuditorBundle\DHAuditorBundle; +use PHPUnit\Framework\Attributes\Small; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\HttpKernel\HttpKernelBrowser; use Symfony\Component\HttpKernel\Kernel; @@ -20,17 +20,15 @@ /** * @internal - * - * @small - * - * @coversNothing */ +#[Small] final class UserProviderTest extends WebTestCase { use BlogSchemaSetupTrait; use ReaderTrait; private DoctrineProvider $provider; + private HttpKernelBrowser $client; protected function setUp(): void @@ -79,7 +77,7 @@ public function testBlameUser(): void // get history $entries = $this->createReader()->createQuery(Post::class)->execute(); - self::assertSame('dark.vador', $entries[0]->getUsername()); + $this->assertSame('dark.vador', $entries[0]->getUsername()); } public function testBlameImpersonator(): void @@ -114,12 +112,7 @@ public function testBlameImpersonator(): void // get history $entries = $this->createReader()->createQuery(Post::class)->execute(); - self::assertSame('second_user[impersonator dark.vador]', $entries[0]->getUsername()); - } - - protected function getBundleClass() - { - return DHAuditorBundle::class; + $this->assertSame('second_user[impersonator dark.vador]', $entries[0]->getUsername()); } private function createAndInitDoctrineProvider(): void From 6831b2c6205c1ee45b58a3422cfd7769869c55b2 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Sat, 7 Sep 2024 00:29:36 +0200 Subject: [PATCH 15/16] Updated composer scripts --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 8be2f07..4337fa4 100644 --- a/composer.json +++ b/composer.json @@ -63,8 +63,8 @@ "rector": "tools/rector/vendor/bin/rector", "rector-check": "tools/rector/vendor/bin/rector --dry-run", "update-tools": "composer update --working-dir=tools/php-cs-fixer ; composer update --working-dir=tools/phpstan ; composer update --working-dir=tools/rector", - "setup44": "SYMFONY_REQUIRE='^4.4' composer update --prefer-stable", - "setup54": "SYMFONY_REQUIRE='^5.4' composer update --prefer-stable" + "setup54": "SYMFONY_REQUIRE='^5.4' composer update --prefer-stable && rm -rf tests/App/var/cache/*", + "setup64": "SYMFONY_REQUIRE='^6.4' composer update --prefer-stable && rm -rf tests/App/var/cache/*" }, "config": { "sort-packages": true, From e0878dd3527315dcbc2cd5af7c180a1b64630ea4 Mon Sep 17 00:00:00 2001 From: Damien Harper Date: Sat, 7 Sep 2024 00:29:56 +0200 Subject: [PATCH 16/16] Fixed Symfony 5.4 failing test --- phpstan.neon | 2 ++ src/User/UserProvider.php | 7 ++----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index 731be49..d133bca 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -17,3 +17,5 @@ parameters: ignoreErrors: - identifier: missingType.iterableValue + - message: '~Class Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken not found.~' + reportUnmatched: false diff --git a/src/User/UserProvider.php b/src/User/UserProvider.php index c43e8e7..3d0c94c 100644 --- a/src/User/UserProvider.php +++ b/src/User/UserProvider.php @@ -7,6 +7,7 @@ use DH\Auditor\User\User; use DH\Auditor\User\UserInterface as AuditorUserInterface; use DH\Auditor\User\UserProviderInterface; +use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; @@ -50,10 +51,6 @@ private function getUsername(UserInterface $user): string return $user->getUserIdentifier(); } - if (method_exists($user, 'getUsername')) { - return $user->getUsername(); - } - return ''; } @@ -65,7 +62,7 @@ private function getTokenUser(): ?UserInterface $token = null; } - if (!$token instanceof TokenInterface) { + if (!$token instanceof TokenInterface || $token instanceof AnonymousToken) { return null; }