diff --git a/README.md b/README.md index 9014792..b06cac2 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,16 @@ Action::new('close') A label for the confirmation button can still be passed as `askConfirmation()`'s second argument. Before EasyAdmin 5.7, and for the delete action, the title and the body are shown joined as a single message. Batch actions keep EasyAdmin's batch confirmation. +Since EasyAdmin 5.10, `askConfirmation()` also takes a closure, which EasyAdmin calls for each entity. It can return a `ConfirmationModal` too, which is shown the same way: + +```php +Action::new('close') + ->linkToCrudAction('close') + ->askConfirmation(static fn (Order $order): ConfirmationModal|false => $order->isOpen() + ? new ConfirmationModal(t('close.confirmation_modal.title'), t('close.confirmation_modal.content')) + : false); +``` + ## License This package is licensed using the MIT License. diff --git a/config/mago.toml b/config/mago.toml index 06e4293..fafbd20 100644 --- a/config/mago.toml +++ b/config/mago.toml @@ -49,4 +49,6 @@ ignore = [ { code = "incompatible-return-type", in = ["tests/Controller/BaseCrudControllerTest.php"] }, # 1 error on Symfony 6.4 # Symfony 6.4 types the return of Crawler::each() as array, 7.4 and later as list { code = "invalid-return-statement", in = ["src/Test/Controller/DashboardControllerTestCase.php"] }, # 2 errors on Symfony 6.4 + # askConfirmation() only takes a closure since EasyAdmin 5.10, so its closures are reported before + { code = "possibly-invalid-argument", in = ["tests/Test/TestApplication/Controller/ConfirmationModalCrudController.php"] }, # 2 errors before EasyAdmin 5.10 ] diff --git a/config/phpstan.neon b/config/phpstan.neon index 9f00c52..0d5ead4 100644 --- a/config/phpstan.neon +++ b/config/phpstan.neon @@ -21,6 +21,12 @@ parameters: identifier: missingType.generics path: ../src/Action/ConfirmationModalActionsExtension.php count: 2 + # askConfirmation() only takes a closure since EasyAdmin 5.10, so its closures are reported before + - + message: '#^Parameter \#1 \$confirmation of method EasyCorp\\Bundle\\EasyAdminBundle\\Config\\Action::askConfirmation\(\) expects bool\|string\|Symfony\\Contracts\\Translation\\TranslatableInterface, Closure given\.$#' + identifier: argument.type + path: ../tests/Test/TestApplication/Controller/ConfirmationModalCrudController.php + count: 2 # BaseCrudDtoController::handleFormRequest() is a byte-identical copy of EasyAdmin's, so it keeps EasyAdmin's # untyped form and nested access to the posted data - diff --git a/src/Action/ConfirmationModal.php b/src/Action/ConfirmationModal.php index c2a6b74..e844389 100644 --- a/src/Action/ConfirmationModal.php +++ b/src/Action/ConfirmationModal.php @@ -11,6 +11,7 @@ /** * Passed to `askConfirmation()`, it gives an action's modal a title and a body, like the delete confirmation's. * {@see ConfirmationModalActionsExtension} sends the two to EasyAdmin, which only takes a single message. + * {@see ConfirmationModalClosureSubscriber} does the same for one returned by a closure passed instead (EasyAdmin 5.10). */ final readonly class ConfirmationModal implements TranslatableInterface { diff --git a/src/Action/ConfirmationModalClosureSubscriber.php b/src/Action/ConfirmationModalClosureSubscriber.php new file mode 100644 index 0000000..06b1820 --- /dev/null +++ b/src/Action/ConfirmationModalClosureSubscriber.php @@ -0,0 +1,105 @@ + */ + #[Override] + public static function getSubscribedEvents(): array + { + return [AfterCrudActionEvent::class => 'sendClosureConfirmationModals']; + } + + public function sendClosureConfirmationModals(AfterCrudActionEvent $event): void + { + // Before 5.10, a ConfirmationModal still found here was passed directly and is left as the single message. + if (version_compare(EasyAdminBundle::VERSION, '5.10.0', '<')) { + return; + } + + // The entities' actions of the index, detail, edit and new pages, and the index page's global actions. + foreach (['entities', 'entity', 'global_actions'] as $parameterName) { + foreach ($this->actionDtos($event->getResponseParameters()->get($parameterName)) as $actionDto) { + $confirmationModal = $actionDto->getConfirmationMessage(); + + // The same exclusions as the extension's. + if (! $confirmationModal instanceof ConfirmationModal || $actionDto->getName() === Action::DELETE || $actionDto->isBatchAction()) { + continue; + } + + $htmlAttributes = $actionDto->getHtmlAttributes(); + // EasyAdmin's JavaScript hides the title whenever there is a message. + unset($htmlAttributes['data-action-confirmation-message']); + $htmlAttributes['data-action-confirmation-title'] = $confirmationModal->title; + $htmlAttributes['data-action-confirmation-content'] = $confirmationModal->content; + + $actionDto->setHtmlAttributes($htmlAttributes); + $actionDto->setConfirmationMessage(true); + } + } + } + + /** + * The actions of an entity collection, an entity, an action collection or an action group, and an action itself. + * Anything else a response parameter can hold has none. + * + * @return Generator + */ + private function actionDtos(mixed $value): Generator + { + if ($value instanceof EntityCollection) { + foreach ($value as $entityDto) { + yield from $this->actionDtos($entityDto); + } + + return; + } + + if ($value instanceof EntityDto) { + yield from $this->actionDtos($value->getActions()); + + return; + } + + if ($value instanceof ActionCollection) { + foreach ($value as $action) { + yield from $this->actionDtos($action); + } + + return; + } + + if ($value instanceof ActionGroupDto) { + yield from $this->actionDtos($value->getMainAction()); + yield from $value->getActions(); + + return; + } + + if ($value instanceof ActionDto) { + yield $value; + } + } +} diff --git a/tests/Action/ConfirmationModalClosureSubscriberTest.php b/tests/Action/ConfirmationModalClosureSubscriberTest.php new file mode 100644 index 0000000..d395200 --- /dev/null +++ b/tests/Action/ConfirmationModalClosureSubscriberTest.php @@ -0,0 +1,124 @@ + + */ +#[CoversClass(ConfirmationModalClosureSubscriber::class)] +final class ConfirmationModalClosureSubscriberTest extends AdminControllerWebTestCase +{ + #[Override] + protected function setUp(): void + { + if (version_compare(EasyAdminBundle::VERSION, '5.10.0', '<')) { + self::markTestSkipped('askConfirmation() takes a closure since EasyAdmin 5.10.'); + } + + parent::setUp(); + } + + #[Override] + protected static function usePrettyUrls(): bool + { + return true; + } + + #[Override] + protected function controllerUnderTest(): string + { + return ConfirmationModalCrudController::class; + } + + #[Override] + protected function actionName(): string + { + return Action::NEW; + } + + public function testClosureReturningAConfirmationModalSendsItAsTitleAndContent(): void + { + $this->assertRequestGet(); + + self::assertSame( + [ + 'data-action-confirmation' => 'true', + 'data-action-confirmation-title' => 'closure_modal.title', + 'data-action-confirmation-content' => 'closure_modal.content', + 'data-action-confirmation-message' => null, + ], + $this->renderedConfirmation('closure_modal'), + ); + self::assertTrue($this->processedAction('closure_modal')->getConfirmationMessage()); + } + + public function testClosureReturningFalseAsksNoConfirmation(): void + { + $this->assertRequestGet(); + + self::assertSame( + [ + 'data-action-confirmation' => null, + 'data-action-confirmation-title' => null, + 'data-action-confirmation-content' => null, + 'data-action-confirmation-message' => null, + ], + $this->renderedConfirmation('closure_false'), + ); + self::assertFalse($this->processedAction('closure_false')->getConfirmationMessage()); + } + + public function testConfirmationModalPassedDirectlyIsStillSentAsTitleAndContent(): void + { + $this->assertRequestGet(); + + self::assertSame( + [ + 'data-action-confirmation' => 'true', + 'data-action-confirmation-title' => 'direct_modal.title', + 'data-action-confirmation-content' => 'direct_modal.content', + 'data-action-confirmation-message' => null, + ], + $this->renderedConfirmation('direct_modal'), + ); + self::assertTrue($this->processedAction('direct_modal')->getConfirmationMessage()); + } + + /** @return array */ + private function renderedConfirmation(string $actionName): array + { + $action = $this->getClient()->getCrawler()->filter('[data-action-name="' . $actionName . '"]'); + + self::assertCount(1, $action); + + $attributes = []; + foreach (['data-action-confirmation', 'data-action-confirmation-title', 'data-action-confirmation-content', 'data-action-confirmation-message'] as $attribute) { + $attributes[$attribute] = $action->attr($attribute); + } + + return $attributes; + } + + private function processedAction(string $actionName): ActionDto + { + return Type\instance_of(ActionDto::class)->coerce( + $this->getAdminContextFromLastRequest()->getEntity()->getActions()->get($actionName), + ); + } +} diff --git a/tests/Test/TestApplication/Controller/ConfirmationModalCrudController.php b/tests/Test/TestApplication/Controller/ConfirmationModalCrudController.php new file mode 100644 index 0000000..c483fd2 --- /dev/null +++ b/tests/Test/TestApplication/Controller/ConfirmationModalCrudController.php @@ -0,0 +1,54 @@ + + */ +final class ConfirmationModalCrudController extends AbstractCrudController +{ + #[Override] + public static function getEntityFqcn(): string + { + return Report::class; + } + + #[Override] + public function configureActions(Actions $actions): Actions + { + return $actions + ->add( + Crud::PAGE_NEW, + Action::new('closure_modal') + ->linkToUrl('#') + ->askConfirmation(static fn (): ConfirmationModal => new ConfirmationModal(t('closure_modal.title'), t('closure_modal.content'))), + ) + ->add( + Crud::PAGE_NEW, + Action::new('closure_false') + ->linkToUrl('#') + ->askConfirmation(static fn (): bool => false), + ) + ->add( + Crud::PAGE_NEW, + Action::new('direct_modal') + ->linkToUrl('#') + ->askConfirmation(new ConfirmationModal(t('direct_modal.title'), t('direct_modal.content'))), + ); + } +} diff --git a/tests/Test/TestApplication/TestKernel.php b/tests/Test/TestApplication/TestKernel.php index d237521..f845460 100644 --- a/tests/Test/TestApplication/TestKernel.php +++ b/tests/Test/TestApplication/TestKernel.php @@ -18,6 +18,7 @@ use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; use Symfony\Component\Security\Core\User\InMemoryUser; use Symfony\UX\TwigComponent\TwigComponentBundle; +use Twig\Extra\TwigExtraBundle\TwigExtraBundle; use function dirname; @@ -37,6 +38,7 @@ public function registerBundles(): Generator yield new SecurityBundle(); yield new TwigBundle(); yield new TwigComponentBundle(); + yield new TwigExtraBundle(); yield new DoctrineBundle(); yield new EasyAdminBundle(); yield new ProtungEasyAdminPlusBundle();