From 66114238b2effa1cabe937ffa62d886eea5b71eb Mon Sep 17 00:00:00 2001 From: Dragos Protung Date: Fri, 13 Nov 2026 09:13:34 +0100 Subject: [PATCH] Link entity fields through a dashboard that has a route for the target's detail page --- config/mago.toml | 2 + config/phpstan.neon | 6 ++ src/Field/Configurator/EntityConfigurator.php | 38 ++++++- .../EntityConfigurator/EntityMetadata.php | 3 + .../Configurator/EntityConfiguratorTest.php | 102 ++++++++++++++++++ .../Controller/DashboardController.php | 2 +- .../Controller/ReportLinkCrudController.php | 39 +++++++ .../ReportLinkDashboardController.php | 16 +++ .../UnroutedReportCrudController.php | 23 ++++ 9 files changed, 229 insertions(+), 2 deletions(-) create mode 100644 tests/Field/Configurator/EntityConfiguratorTest.php create mode 100644 tests/Test/TestApplication/Controller/ReportLinkCrudController.php create mode 100644 tests/Test/TestApplication/Controller/ReportLinkDashboardController.php create mode 100644 tests/Test/TestApplication/Controller/UnroutedReportCrudController.php diff --git a/config/mago.toml b/config/mago.toml index fafbd20..1d6c4b1 100644 --- a/config/mago.toml +++ b/config/mago.toml @@ -51,4 +51,6 @@ ignore = [ { 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 + # AdminRouteGenerator::usesPrettyUrls() only exists in EasyAdmin 4, EasyAdmin 5 always uses pretty URLs + { code = "non-existent-method", in = ["src/Field/Configurator/EntityConfigurator.php"] }, # 1 error on EasyAdmin 5 ] diff --git a/config/phpstan.neon b/config/phpstan.neon index 0d5ead4..7d8ca06 100644 --- a/config/phpstan.neon +++ b/config/phpstan.neon @@ -27,6 +27,12 @@ parameters: identifier: argument.type path: ../tests/Test/TestApplication/Controller/ConfirmationModalCrudController.php count: 2 + # AdminRouteGenerator::usesPrettyUrls() only exists in EasyAdmin 4, EasyAdmin 5 always uses pretty URLs + - + message: '#^Call to an undefined method EasyCorp\\Bundle\\EasyAdminBundle\\Router\\AdminRouteGenerator::usesPrettyUrls\(\)\.$#' + identifier: method.notFound + path: ../src/Field/Configurator/EntityConfigurator.php + count: 1 # 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/Field/Configurator/EntityConfigurator.php b/src/Field/Configurator/EntityConfigurator.php index 6a47620..44878dd 100644 --- a/src/Field/Configurator/EntityConfigurator.php +++ b/src/Field/Configurator/EntityConfigurator.php @@ -16,7 +16,9 @@ use EasyCorp\Bundle\EasyAdminBundle\Dto\CrudDto; use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto; use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto; +use EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle; use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory; +use EasyCorp\Bundle\EasyAdminBundle\Router\AdminRouteGenerator; use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGeneratorInterface; use Override; use Protung\EasyAdminPlusBundle\Field\Configurator\EntityConfigurator\EntityMetadata; @@ -35,6 +37,7 @@ use function is_bool; use function is_callable; use function Psl\invariant; +use function version_compare; final readonly class EntityConfigurator implements FieldConfiguratorInterface { @@ -46,6 +49,7 @@ public function __construct( private Environment $twig, private PropertyAccessorInterface $propertyAccessor, private EntityManagerInterface $entityManager, + private AdminRouteGenerator $adminRouteGenerator, ) { } @@ -78,10 +82,17 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c invariant(Class\exists($targetEntityFqcn), 'Could not determine target entity for set CRUD controller.'); invariant(Class\exists($targetCrudControllerFqcn), 'Could not determine target CRUD controller.'); + $currentDashboardControllerFqcn = Type\class_string(DashboardControllerInterface::class)->coerce($context->getDashboardControllerFqcn()); + $linkDashboardControllerFqcn = $this->linkDashboardControllerFqcn($context, $currentDashboardControllerFqcn, $targetCrudControllerFqcn); + if ($linkDashboardControllerFqcn === null) { + // a link through a dashboard without a route for the detail page would point to the dashboard itself + $field->setCustomOption(EntityField::OPTION_LINK_TO_ENTITY, false); + } + $entityMetadata = new EntityMetadata( $entityDto->getPrimaryKeyValue(), $sourceCrudControllerFqcn, - Type\class_string(DashboardControllerInterface::class)->coerce($context->getDashboardControllerFqcn()), + $linkDashboardControllerFqcn ?? $currentDashboardControllerFqcn, $targetCrudControllerFqcn, $targetEntityFqcn, $field->getValue(), @@ -262,6 +273,31 @@ private function generateLinkToAssociatedEntity(EntityMetadata $entityMetadata, ->generateUrl(); } + /** + * @param AdminContext $context + * @param class-string $currentDashboardControllerFqcn + * @param class-string> $targetCrudControllerFqcn + * + * @return class-string|null The current dashboard when it has a route for the detail page of + * the target, otherwise the first dashboard that has one, if any. + */ + private function linkDashboardControllerFqcn(AdminContext $context, string $currentDashboardControllerFqcn, string $targetCrudControllerFqcn): string|null + { + // EasyAdmin 5 only has pretty URLs, EasyAdmin 4 has them when the application imports its routes. + // Without them, every dashboard links to every CRUD controller. + if (version_compare(EasyAdminBundle::VERSION, '5.0.0', '<') && ! $this->adminRouteGenerator->usesPrettyUrls()) { + return $currentDashboardControllerFqcn; + } + + foreach ([$currentDashboardControllerFqcn, ...$context->getAdminControllers()->getAllDashboards()] as $dashboardControllerFqcn) { + if ($this->adminRouteGenerator->findRouteName($dashboardControllerFqcn, $targetCrudControllerFqcn, Action::DETAIL) !== null) { + return Type\class_string(DashboardControllerInterface::class)->coerce($dashboardControllerFqcn); + } + } + + return null; + } + private function configureOnChange(FieldDto $field, EntityMetadata $entityMetadata): void { $onChangeCallable = $field->getCustomOption(EntityField::OPTION_ON_CHANGE); diff --git a/src/Field/Configurator/EntityConfigurator/EntityMetadata.php b/src/Field/Configurator/EntityConfigurator/EntityMetadata.php index c78ddb6..2576b65 100644 --- a/src/Field/Configurator/EntityConfigurator/EntityMetadata.php +++ b/src/Field/Configurator/EntityConfigurator/EntityMetadata.php @@ -64,6 +64,9 @@ public function sourceCrudControllerFqcn(): string } /** + * The dashboard that the link to the target goes through: the current one when it has a route for the detail page of the target CRUD controller, + * otherwise the first dashboard that has one. When none has, the current one. + * * @return class-string */ public function targetDashboardControllerFqcn(): string diff --git a/tests/Field/Configurator/EntityConfiguratorTest.php b/tests/Field/Configurator/EntityConfiguratorTest.php new file mode 100644 index 0000000..62c12d5 --- /dev/null +++ b/tests/Field/Configurator/EntityConfiguratorTest.php @@ -0,0 +1,102 @@ + + */ +#[CoversClass(EntityConfigurator::class)] +final class EntityConfiguratorTest extends DetailActionTestCase +{ + protected static string|int $expectedEntityIdUnderTest = 1; + + /** @var class-string|null */ + private string|null $dashboardControllerFqcn = null; + + #[Override] + protected function setUp(): void + { + parent::setUp(); + + $entityManager = $this->getEntityManager(); + $metadata = $entityManager->getMetadataFactory()->getAllMetadata(); + $schemaTool = new SchemaTool($entityManager); + $schemaTool->dropSchema($metadata); + $schemaTool->createSchema($metadata); + + $report = new Report(); + $report->id = 1; + $entityManager->persist($report); + $entityManager->flush(); + $entityManager->clear(); + } + + #[Override] + protected static function usePrettyUrls(): bool + { + return true; + } + + #[Override] + protected function controllerUnderTest(): string + { + return ReportLinkCrudController::class; + } + + #[Override] + protected function dashboardControllerFqcn(): string|null + { + return $this->dashboardControllerFqcn; + } + + public function testLinkGoesThroughTheCurrentDashboardWhenItHasARouteForTheTarget(): void + { + $this->assertRequestGet(); + + self::assertSame('http://localhost/admin/report/1', $this->renderedField('Report')->filter('a')->attr('href')); + } + + public function testLinkGoesThroughAnotherDashboardWhenOnlyItHasARouteForTheTarget(): void + { + $this->dashboardControllerFqcn = ReportLinkDashboardController::class; + + $this->assertRequestGet(); + + self::assertSame('http://localhost/admin/report/1', $this->renderedField('Report')->filter('a')->attr('href')); + } + + public function testNoLinkWhenNoDashboardHasARouteForTheTarget(): void + { + $this->assertRequestGet(); + + $field = $this->renderedField('Unrouted report'); + self::assertSame('1', $this->extractFieldValue($field)); + self::assertCount(0, $field->filter('a')); + } + + private function renderedField(string $label): Crawler + { + $field = $this->getClient()->getCrawler() + ->filter($this->mainContentSelector() . ' ' . $this->fieldSelector()) + ->reduce(static fn (Crawler $field): bool => $field->filter('div.field-label')->text(normalizeWhitespace: true) === $label); + + self::assertCount(1, $field); + + return $field; + } +} diff --git a/tests/Test/TestApplication/Controller/DashboardController.php b/tests/Test/TestApplication/Controller/DashboardController.php index cf396fb..3148f6c 100644 --- a/tests/Test/TestApplication/Controller/DashboardController.php +++ b/tests/Test/TestApplication/Controller/DashboardController.php @@ -7,7 +7,7 @@ use EasyCorp\Bundle\EasyAdminBundle\Attribute\AdminDashboard; use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController; -#[AdminDashboard(routePath: '/admin', routeName: 'admin')] +#[AdminDashboard(routePath: '/admin', routeName: 'admin', deniedControllers: [UnroutedReportCrudController::class])] final class DashboardController extends AbstractDashboardController { } diff --git a/tests/Test/TestApplication/Controller/ReportLinkCrudController.php b/tests/Test/TestApplication/Controller/ReportLinkCrudController.php new file mode 100644 index 0000000..3c2d4fb --- /dev/null +++ b/tests/Test/TestApplication/Controller/ReportLinkCrudController.php @@ -0,0 +1,39 @@ + + */ +final class ReportLinkCrudController extends AbstractCrudController +{ + #[Override] + public static function getEntityFqcn(): string + { + return Report::class; + } + + /** @return iterable */ + #[Override] + public function configureFields(string $pageName): iterable + { + // the ID is the ID of the linked report, so the fields need no association + yield EntityField::new('id', 'Report') + ->setCrudController(ReportCrudController::class) + ->setEntityDisplayField('id'); + + yield EntityField::new('id', 'Unrouted report') + ->setCrudController(UnroutedReportCrudController::class) + ->setEntityDisplayField('id'); + } +} diff --git a/tests/Test/TestApplication/Controller/ReportLinkDashboardController.php b/tests/Test/TestApplication/Controller/ReportLinkDashboardController.php new file mode 100644 index 0000000..c123716 --- /dev/null +++ b/tests/Test/TestApplication/Controller/ReportLinkDashboardController.php @@ -0,0 +1,16 @@ + + */ +final class UnroutedReportCrudController extends AbstractCrudController +{ + #[Override] + public static function getEntityFqcn(): string + { + return Report::class; + } +}