|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\City\Infrastructure\ApiPlatform\State\Provider; |
| 6 | + |
| 7 | +use ApiPlatform\Metadata\Operation; |
| 8 | +use ApiPlatform\State\Pagination\Pagination; |
| 9 | +use ApiPlatform\State\ProviderInterface; |
| 10 | +use App\City\Infrastructure\ApiPlatform\Resource\CityResource; |
| 11 | +use App\Core\Domain\Search\Service\SearchServiceInterface; |
| 12 | +use App\Shared\Infrastructure\ApiPlatform\State\Paginator; |
| 13 | + |
| 14 | +/** |
| 15 | + * @implements ProviderInterface<CityResource> |
| 16 | + */ |
| 17 | +final class CityCollectionProvider implements ProviderInterface |
| 18 | +{ |
| 19 | + public function __construct( |
| 20 | + private Pagination $pagination, |
| 21 | + private SearchServiceInterface $searchService, |
| 22 | + ) { |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @return Paginator<CityResource>|list<CityResource> |
| 27 | + */ |
| 28 | + public function provide(Operation $operation, array $uriVariables = [], array $context = []): Paginator|array |
| 29 | + { |
| 30 | + $name = $context['filters']['name'] ?? null; |
| 31 | + $page = $itemsPerPage = null; |
| 32 | + $cities = []; |
| 33 | + |
| 34 | + if ($this->pagination->isEnabled($operation, $context)) { |
| 35 | + $page = $this->pagination->getPage($context); |
| 36 | + $itemsPerPage = $this->pagination->getLimit($operation, $context); |
| 37 | + } |
| 38 | + |
| 39 | + if ($name !== null) { |
| 40 | + $cities = $this->searchService->searchCities($name, $itemsPerPage, $page - 1); |
| 41 | + }; |
| 42 | + |
| 43 | + $resources = []; |
| 44 | + foreach ($cities as $city) { |
| 45 | + $resources[] = CityResource::fromModel($city); |
| 46 | + } |
| 47 | + |
| 48 | + return $resources; |
| 49 | + } |
| 50 | +} |
0 commit comments