Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Built-in ArgumentValueResolver for UIDs #41690

Closed
@logarytm

Description

@logarytm

Description
I use UUIDs (provided by the excellent Symfony UID component) as entity IDs in my project. Because of this, I also have UUID parameters in my routes. To keep the code clean from explicit conversions, I would like to be able to receive the parameter value as a Uuid instance in a controller action:

use Symfony\Component\Uid\Uuid;

/**
 * @Route("/frog/{id}")
 */
public function get(Uuid $id)
{
    return $this->render('frog.html.twig', ['frog' => $this->frogs->find($id)]);
}

instead of:

use Symfony\Component\Uid\Uuid;

/**
 * @Route("/frog/{id}")
 */
public function get(string $id)
{
    $id = Uuid::fromString($id);

    return $this->render('frog.html.twig', ['frog' => $this->frogs->find($id)]);
}

Example
For now, I use the following implementation of ArgumentValueResolverInterface:

namespace App\ArgumentResolver;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Uid\Uuid;

class UuidArgumentResolver implements ArgumentValueResolverInterface
{
    public function supports(Request $request, ArgumentMetadata $argument): bool
    {
        return (
            !$argument->isVariadic()
            && is_a($argument->getType(), Uuid::class, /* allow_strings */ true)
            && $request->attributes->has($argument->getName())
        );
    }

    public function resolve(Request $request, ArgumentMetadata $argument): iterable
    {
        try {
            yield Uuid::fromString($request->attributes->get($argument->getName()));
        } catch (\InvalidArgumentException $e) {
            throw new BadRequestHttpException();
        }
    }
}

Perhaps this could one day be handled by default?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions