Extract an entity from EasyAdmin requests

12/19/2022 by Stefan Bauer

I just had to extract the entity that I was currently working on from an EasyAdmin 4 request and had a quick look at the existing best practices. I usually don't write about code snippets, but I found it odd that there are so many entity-specific solutions for this common issue on StackOverflow and Reddit. You can use PHPStan generics to extract an entity from an EasyAdmin request with perfect support by PhpStorm or any other IDE that supports PHPStan.

<?php

namespace App\Infrastructure\Service;

use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
use RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

class EasyAdminEntityExtractor
{
    public function __construct(
        private readonly RequestStack           $requestStack,
        private readonly EntityManagerInterface $entityManager
    ) {
    }

    /**
     * @link https://phpstan.org/blog/generics-in-php-using-phpdocs
     * @template T
     * @param class-string<T> $fqcn
     * @return T
     */
    public function extractFromRequest(string $fqcn, ?Request $request = null)
    {
        $request = $request ?? $this->requestStack->getCurrentRequest();
        $id = (int)$request->query->get(EA::ENTITY_ID);
        $repository = $this->entityManager->getRepository($fqcn);
        $instance = $repository->find($id);
        if ($instance === null) {
            throw new RuntimeException(sprintf('Could not find %s with ID %s.', $fqcn, $id));
        }

        return $instance;
    }
}

The usage of this service is quite self-explanatory:

try {
    $landingPage = $this->entityExtractor->extractFromRequest(LandingPage::class, $request);
} catch (\Throwable $throwable) {
    # TODO handle error.
}

Cheers, I hope this was helpful to some of you.