Skip to content
Snippets Groups Projects
Commit 22fff370 authored by Nikita Chernykh's avatar Nikita Chernykh
Browse files

Merge branch 'PTPS|Controller_1' into 'main'

Ptps|controller 1

See merge request !1
parents f205f644 295a6342
No related branches found
No related tags found
1 merge request!1Ptps|controller 1
<?php
namespace App\Actions;
class SortPriceAction
{
/**
* Выполняет сортировку массива по убыванию цены
* @param array $array
* @return array отсортированный
*/
public function act(array $array): array
{
$priceColumn = array_column($array, "price");
$countColumn = array_column($array, "count");
array_multisort(
$priceColumn,
SORT_DESC,
$countColumn,
SORT_ASC,
$array,
);
return $array;
}
}
<?php
namespace App\Controller;
use App\Actions\SortPriceAction;
use App\Requests\PricesRequest;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
class SortPriceController extends AbstractController
{
/**
* Контроллер волняет сортировку массива по убыванию цены используя sortPrice
* @param PricesRequest $request
* @param SortPriceAction $action
* @return JsonResponse
*/
#[Route('/sort/price', name: 'app_sort_price', methods: ['POST'])]
public function index(PricesRequest $request, SortPriceAction $action): JsonResponse
{
return new JsonResponse($action->act($request->serialise()));
}
}
<?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