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

create search actions controller and req

parent 4ebf14ce
Loading
Loading
Loading
Loading
+29 −0
Original line number Diff line number Diff line
<?php

namespace App\Actions;

class IdSearchAction
{
    /**
     * Найдет элемент с указаным id
     * @param array $array - массив, содержащий элементы со структурой
     * [
     * 'id' => 30,
     * 'name' => 'Jhon',
     * 'age' => 23,
     * ]
     * @param $id - ид искомого элемента
     * @return array|null - найденный элемент/ вернет null при его отсутствии
     */
    public static function act(array $array): ?array
    {

        foreach ($array['users'] as $item){
            if ($item['id'] === $array['id']){
                return $item;
            }
        }

        return null;
    }
}
+27 −0
Original line number Diff line number Diff line
<?php

namespace App\Controller;

use App\Actions\IdSearchAction;
use App\Requests\UsersRequest;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

class IdSearchController extends AbstractController
{
    /**
     * Контроллер найдет элемент с указаным id используя sortPrice
     * @param UsersRequest $request
     * @param IdSearchAction $action
     * @return JsonResponse
     */
    #[Route('/search', name: 'app_search', methods: ['POST'])]
    public function index(UsersRequest $request, IdSearchAction $action): JsonResponse
    {
        return new JsonResponse(
            $action->act($request->serialise()),
            200
        );
    }
}
 No newline at end of file
+45 −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\Optional;
use Symfony\Component\Validator\Constraints\Type;

class UsersRequest extends BaseRequest
{
    #[Type('integer')]
    #[NotBlank]
    public $id;

    #[Type('array')]
    #[All(
        constraints: new Collection(fields: [
                'id' => [
                    new Type('integer'),
                    new NotBlank(),
                ],
                'name' => [
                    new Type('string'),
                    new NotBlank(),
                ],
                'age' => new Optional([
                    new Type('integer'),
                ])
            ])
    )]
    public $users;

    /**
     * @return array
     */
    public function serialise(): array
    {
        return [
            'id' => $this->id,
            'users' => $this->users,
        ];
    }
}
 No newline at end of file