Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions config/mago.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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<R>
{ 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
]
6 changes: 6 additions & 0 deletions config/phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
-
Expand Down
1 change: 1 addition & 0 deletions src/Action/ConfirmationModal.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
105 changes: 105 additions & 0 deletions src/Action/ConfirmationModalClosureSubscriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

declare(strict_types=1);

namespace Protung\EasyAdminPlusBundle\Action;

use EasyCorp\Bundle\EasyAdminBundle\Collection\ActionCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\EntityCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Dto\ActionDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\ActionGroupDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
use Generator;
use Override;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use function version_compare;

/**
* Since 5.10, `askConfirmation()` also takes a closure, which EasyAdmin calls for each entity after the actions extensions have run,
* so {@see ConfirmationModalActionsExtension} never sees the {@see ConfirmationModal} it returns.
* Once the CRUD action has built the actions, the modal EasyAdmin made a single message of is sent as title and content instead, like the extension does.
*/
final readonly class ConfirmationModalClosureSubscriber implements EventSubscriberInterface
{
/** @return array<class-string, string> */
#[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<ActionDto>
*/
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;
}
}
}
124 changes: 124 additions & 0 deletions tests/Action/ConfirmationModalClosureSubscriberTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?php

declare(strict_types=1);

namespace Protung\EasyAdminPlusBundle\Tests\Action;

use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Dto\ActionDto;
use EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle;
use Override;
use PHPUnit\Framework\Attributes\CoversClass;
use Protung\EasyAdminPlusBundle\Action\ConfirmationModalClosureSubscriber;
use Protung\EasyAdminPlusBundle\Test\Controller\AdminControllerWebTestCase;
use Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Controller\ConfirmationModalCrudController;
use Psl\Type;

use function version_compare;

/**
* The confirmations as rendered by EasyAdmin, which calls the closures itself.
*
* @template-extends AdminControllerWebTestCase<ConfirmationModalCrudController>
*/
#[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<string, string|null> */
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),
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Controller;

use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use Override;
use Protung\EasyAdminPlusBundle\Action\ConfirmationModal;
use Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Entity\Report;

use function Symfony\Component\Translation\t;

/**
* The confirmations of the new page's actions, in the ways a {@see ConfirmationModal} can be asked for.
* Its closures need EasyAdmin 5.10.
*
* @template-extends AbstractCrudController<Report>
*/
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'))),
);
}
}
2 changes: 2 additions & 0 deletions tests/Test/TestApplication/TestKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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();
Expand Down
Loading