Commit 4ebf14ce authored by Александр Плохих's avatar Александр Плохих 🌔
Browse files

symplify controller

parent 2b3fa047
Loading
Loading
Loading
Loading
+3 −7
Original line number Diff line number Diff line
@@ -2,19 +2,15 @@

namespace App\Actions;

use App\Entity\InterfaceDataEntity;

class SortPriceAction implements InterfaceAction
class SortPriceAction
{
    /**
     * Выполняет сортировку массива по убыванию цены
     * @param InterfaceDataEntity $model
     * @param array $array
     * @return array отсортированный
     */
    public function act(InterfaceDataEntity $model): array
    public function act(array $array): array
    {
        $array = $model->prices;

        $priceColumn = array_column($array, "price");
        $countColumn = array_column($array, "count");

+6 −8
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ namespace App\Controller;

use App\Actions\SortPriceAction;
use App\Entity\PricesEntity;
use App\Requests\PricesRequest;
use App\Service\ValidationService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -19,14 +20,11 @@ class SortPriceController extends AbstractController
     * @return JsonResponse
     */
    #[Route('/sort/price', name: 'app_sort_price', methods: ['POST'])]
    public function index(Request $request, SortPriceAction $action): JsonResponse
    public function index(PricesRequest $request, SortPriceAction $action): JsonResponse
    {
        $priceEntity = new PricesEntity();
        $priceEntity->serialise($request);

        $validation = new ValidationService();
        $validation->validate($priceEntity);

        return new JsonResponse($action->act($priceEntity));
        return new JsonResponse(
            $action->act($request->serialise()),
            200
        );
    }
}
+71 −0
Original line number Diff line number Diff line
<?php

namespace App\Requests;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

abstract class BaseRequest
{
    /**
     * активация автовалидации
     * перезаписать на false для отключение автовалидации
     */
    protected const AUTO_VALIDATE = true;

    public function __construct(protected ValidatorInterface $validator)
    {
        $this->populate();

        if (self::AUTO_VALIDATE) {
            $this->validate();
        }
    }

    protected function populate(): void
    {
        foreach ($this->getRequest()->toArray() as $property => $value) {
            if (property_exists($this, $property)) {
                $this->{$property} = $value;
            }
        }
    }

    /**
     * валидация и выброкса ошибки при валидации
     * @return void
     */
    public function validate()
    {
        $errors = $this->validator->validate($this);

        $messages = [
            'message' => 'validation_failed',
            'errors' => []
        ];

        foreach ($errors as $error) {
            $messages['errors'][] = [
                'property' => $error->getPropertyPath(),
                'value' => $error->getInvalidValue(),
                'message' => $error->getMessage(),
            ];
        }

        if (count($messages['errors']) > 0) {
            $response = new JsonResponse($messages, 201);
            $response->send();

            throw new ValidatorException('Validation failed', $messages);
        }
    }

    public function getRequest(): Request
    {
        return Request::createFromGlobals();
    }

    abstract public function serialise(): mixed;
}
 No newline at end of file
+42 −0
Original line number Diff line number Diff line
<?php

namespace App\Requests;

use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Contracts\Service\Attribute\Required;

class PricesRequest extends BaseRequest
{
    #[Type('array')]
    #[NotBlank()]
    #[Required()]
    #[All(
        constraints: [
            new Collection(
                fields: [
                    'price' => [
                        new NotBlank(),
                        new Type('integer'),
                    ],
                    'count' => [
                        new NotBlank(),
                        new Type('integer'),
                    ],
                ],
            )
        ]
    )]
    public $prices;

    /**
     * серализация реквеста под массив
     * @return mixed
     */
    public function serialise(): mixed
    {
        return $this->prices;
    }
}
+20 −0
Original line number Diff line number Diff line
{% extends 'base.html.twig' %}

{% block title %}Hello IdSearchController!{% endblock %}

{% block body %}
<style>
    .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
    .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>

<div class="example-wrapper">
    <h1>Hello {{ controller_name }}! ✅</h1>

    This friendly message is coming from:
    <ul>
        <li>Your controller at <code>/home/tamanit/myProj/iqdevTranningProgram/src/Controller/IdSearchController.php</code></li>
        <li>Your template at <code>/home/tamanit/myProj/iqdevTranningProgram/templates/id_search/index.html.twig</code></li>
    </ul>
</div>
{% endblock %}