I
I
Igor2020-02-27 19:53:37
symfony
Igor, 2020-02-27 19:53:37

Symfony, Argument resolver used as intended?

Greetings!

I would like to clarify, to know.

How accurate are the actions?

- Requires parameter validation before they get into the controller
- Reducing the amount of shitty code in controllers.

Usage example.

<?php


namespace App\ArgumentResolver;


use App\Entity\Product;
use App\Repository\ProductRepository;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

/**
 * Class ProductValueResolver
 * @package App\ArgumentResolver
 */
class ProductValueResolver implements ArgumentValueResolverInterface
{
    private EntityManagerInterface $em;
    private ProductRepository $products_repository;

    /**
     * ProductValueResolver constructor.
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
        $this->products_repository = $em->getRepository(Product::class);
    }

    /**
     * @inheritDoc
     */
    public function supports(Request $request, ArgumentMetadata $argument)
    {
       return Product::class == $argument->getType();
    }

    /**
     * @inheritDoc
     * @throws Exception
     */
    public function resolve(Request $request, ArgumentMetadata $argument)
    {
        if (!$request->get("product_id", false)) {
            throw new Exception("Ошибка!");
        }

        $product = $this->products_repository->getById($request->get("product_id"));

        if (!is_a($product, $this->products_repository->getClassName())) {
            throw new Exception("Ошибка, объект не пренадлежит классу!");
        }

        yield $product;
    }
}


// In the controller
/**
     * @Route(
     *     path="/products.edit",
     *     methods={"POST"}
     * )
     * @param Product $product
     * @return JsonResponse
     */
    public function edit(Product $product)
    {
     // модификация, персист, флуш
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2020-02-27
@Maksclub

You can only make it more abstract, so that any entity gets and checked, if indicated, and not for each to do its own, but leave this possibility
. This is implicitly done in different admin panels. Only not in the controller arguments, but simply in the request, in EasyAdmin like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question