Tuesday, 5 March 2024

Validation by Using ValidatorInterface & Entities

 Example validate request data with 2 parameters:

- ids: array of integer

- qr_sizes: array of integer can null

1. Create ValidatorTrait

\app\Customize\Entity\Validator\ValidatorTrait.php

<?php

namespace Customize\Entity\Validator;

trait ValidatorTrait
{
    /**
     * setDataFromArray
     * @param array<string, string> $data Data for object.
     *
     * @return ValidatorTrait Object data.
     */
    public function setDataFromArray(array $data)
    {
        foreach ($data as $key => $value) {
            if (property_exists($this, $key)) {
                $this->$key = $value;
            }
        }
        return $this;
    }
}

2. Create DownloadQrCodeValidator

app\Customize\Entity\Validator\Product\DownloadQrCodeValidator.php

see mor Constrains here >> https://symfony.com/doc/5.x/validation.html

<?php
namespace Customize\Entity\Validator\Product;

use Symfony\Component\Validator\Constraints as Assert;
use Customize\Entity\Validator\ValidatorTrait;

class DownloadQrCodeValidator
{
    use ValidatorTrait;

    /**
     * ids
     *
     * @Assert\NotBlank(message="The ids must not be blank.")
     * @Assert\All({
     *     @Assert\Regex(pattern="/\d+/", message="All elements of the array ids must be number.")
     * })
     */
    public $ids;

    /**
     * qr_sizes
     *
     * @Assert\NotBlank(allowNull = true)
     * @Assert\All({
     *     @Assert\Regex(pattern="/\d+/", message="All elements of the array qr_sizes must be number.")
     * })
     */
    public $qr_sizes;
}

3. Using in DownloadQrCodeController

app\Customize\Entity\Validator\Product\DownloadQrCodeValidator.php

<?php

namespace Customize\Controller\Admin\Product;

use Customize\Common\ErrorsHelper;
use Customize\Entity\Validator\Product\DownloadQrCodeValidator;
use Customize\Service\Product\GetQrCodeService;
use Eccube\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Eccube\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class DownloadQrCodeController extends AbstractController
{
    /**
     * @var ProductRepository
     */
    protected $productRepository;

    /**
     * @var GetQrCodeService
     */
    protected $getQrCodeService;

    /**
     * @var ValidatorInterface
     */
    protected $validator;

    /**
     * DownloadQrCodeController constructor.
     *
     * @param ProductRepository $productRepository Description productRepository.
     * @param GetQrCodeService $getQrCodeService Description DesGetQrCodeService.
     * @param ValidatorInterface $validator Description ValidatorInterface.
     */
    public function __construct(
        ProductRepository $productRepository,
        GetQrCodeService $getQrCodeService,
        ValidatorInterface $validator
    ) {
        $this->productRepository = $productRepository;
        $this->getQrCodeService = $getQrCodeService;
        $this->validator = $validator;
    }

    /**
     * downloadQrCode
     * @param Request $request Request data.
     * @Route("/admin/download_qr", name="admin_download_qr", methods={"POST"})
     */
    public function downloadQrCode(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            return $this->json(['status' => 'NG'], 400);
        }
        $this->isTokenValid();

        $data = (new DownloadQrCodeValidator())->setDataFromArray($request->request->all());
        $errors = $this->validator->validate($data);

        if ((count($errors) > 0)) {
            $this->addError(trans('admin.product.qr_code_form_download.download_failure', [
                '%errors%' => json_encode(ErrorsHelper::getMgsErrors($errors))
            ]), 'admin');
        } else {
            $this->addSuccess(trans('admin.product.qr_code_form_download.download_success'), 'admin');
            return new Response(
                $this->getQrCodeService->setData($data)->setHandler($this->getUser())->handle(),
                Response::HTTP_OK
            );
        }
    }
}

 Thank you

No comments:

Post a Comment

Golang Advanced Interview Q&A