Skip to content
Snippets Groups Projects
Commit 4ebf14ce authored by Александр Плохих's avatar Александр Плохих :waxing_gibbous_moon:
Browse files

symplify controller

parent 2b3fa047
No related branches found
No related tags found
1 merge request!1Ptps|controller 1
This commit is part of merge request !8. Comments created here will be created in the context of that merge request.
...@@ -2,19 +2,15 @@ ...@@ -2,19 +2,15 @@
namespace App\Actions; namespace App\Actions;
use App\Entity\InterfaceDataEntity; class SortPriceAction
class SortPriceAction implements InterfaceAction
{ {
/** /**
* Выполняет сортировку массива по убыванию цены * Выполняет сортировку массива по убыванию цены
* @param InterfaceDataEntity $model * @param array $array
* @return array отсортированный * @return array отсортированный
*/ */
public function act(InterfaceDataEntity $model): array public function act(array $array): array
{ {
$array = $model->prices;
$priceColumn = array_column($array, "price"); $priceColumn = array_column($array, "price");
$countColumn = array_column($array, "count"); $countColumn = array_column($array, "count");
......
...@@ -4,6 +4,7 @@ namespace App\Controller; ...@@ -4,6 +4,7 @@ namespace App\Controller;
use App\Actions\SortPriceAction; use App\Actions\SortPriceAction;
use App\Entity\PricesEntity; use App\Entity\PricesEntity;
use App\Requests\PricesRequest;
use App\Service\ValidationService; use App\Service\ValidationService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
...@@ -19,14 +20,11 @@ class SortPriceController extends AbstractController ...@@ -19,14 +20,11 @@ class SortPriceController extends AbstractController
* @return JsonResponse * @return JsonResponse
*/ */
#[Route('/sort/price', name: 'app_sort_price', methods: ['POST'])] #[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(); return new JsonResponse(
$priceEntity->serialise($request); $action->act($request->serialise()),
200
$validation = new ValidationService(); );
$validation->validate($priceEntity);
return new JsonResponse($action->act($priceEntity));
} }
} }
<?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
<?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;
}
}
{% 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 %}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment