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
2 changes: 2 additions & 0 deletions config/mago.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
]
6 changes: 6 additions & 0 deletions config/phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
-
Expand Down
38 changes: 37 additions & 1 deletion src/Field/Configurator/EntityConfigurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
{
Expand All @@ -46,6 +49,7 @@ public function __construct(
private Environment $twig,
private PropertyAccessorInterface $propertyAccessor,
private EntityManagerInterface $entityManager,
private AdminRouteGenerator $adminRouteGenerator,
) {
}

Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -262,6 +273,31 @@ private function generateLinkToAssociatedEntity(EntityMetadata $entityMetadata,
->generateUrl();
}

/**
* @param AdminContext<object> $context
* @param class-string<DashboardControllerInterface> $currentDashboardControllerFqcn
* @param class-string<CrudControllerInterface<*>> $targetCrudControllerFqcn
*
* @return class-string<DashboardControllerInterface>|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);
Expand Down
3 changes: 3 additions & 0 deletions src/Field/Configurator/EntityConfigurator/EntityMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<DashboardControllerInterface>
*/
public function targetDashboardControllerFqcn(): string
Expand Down
102 changes: 102 additions & 0 deletions tests/Field/Configurator/EntityConfiguratorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

declare(strict_types=1);

namespace Protung\EasyAdminPlusBundle\Tests\Field\Configurator;

use Doctrine\ORM\Tools\SchemaTool;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\DashboardControllerInterface;
use Override;
use PHPUnit\Framework\Attributes\CoversClass;
use Protung\EasyAdminPlusBundle\Field\Configurator\EntityConfigurator;
use Protung\EasyAdminPlusBundle\Test\Controller\DetailActionTestCase;
use Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Controller\ReportLinkCrudController;
use Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Controller\ReportLinkDashboardController;
use Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Entity\Report;
use Symfony\Component\DomCrawler\Crawler;

/**
* The links of entity fields to the detail page of the linked entity.
*
* @template-extends DetailActionTestCase<ReportLinkCrudController>
*/
#[CoversClass(EntityConfigurator::class)]
final class EntityConfiguratorTest extends DetailActionTestCase
{
protected static string|int $expectedEntityIdUnderTest = 1;

/** @var class-string<DashboardControllerInterface>|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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
}
39 changes: 39 additions & 0 deletions tests/Test/TestApplication/Controller/ReportLinkCrudController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

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

use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use Override;
use Protung\EasyAdminPlusBundle\Field\EntityField;
use Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Entity\Report;

/**
* Entity fields that link each report to itself, through a CRUD controller that only the main dashboard has routes for
* and through one that no dashboard has routes for.
*
* @template-extends AbstractCrudController<Report>
*/
final class ReportLinkCrudController extends AbstractCrudController
{
#[Override]
public static function getEntityFqcn(): string
{
return Report::class;
}

/** @return iterable<EntityField> */
#[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');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

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

use EasyCorp\Bundle\EasyAdminBundle\Attribute\AdminDashboard;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;

/**
* A second dashboard that only has routes for the report links, so their links to the reports go through another dashboard.
*/
#[AdminDashboard(routePath: '/report-links', routeName: 'report_links', allowedControllers: [ReportLinkCrudController::class])]
final class ReportLinkDashboardController extends AbstractDashboardController
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

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

use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use Override;
use Protung\EasyAdminPlusBundle\Tests\Test\TestApplication\Entity\Report;

/**
* A CRUD controller that no dashboard has a route for.
*
* @template-extends AbstractCrudController<Report>
*/
final class UnroutedReportCrudController extends AbstractCrudController
{
#[Override]
public static function getEntityFqcn(): string
{
return Report::class;
}
}
Loading