|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\DataProvider; |
| 4 | + |
| 5 | +use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\PaginationExtension; |
| 6 | +use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface; |
| 7 | +use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator; |
| 8 | +use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface; |
| 9 | +use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface; |
| 10 | +use App\Entity\Car; |
| 11 | +use Doctrine\Persistence\ManagerRegistry; |
| 12 | + |
| 13 | +final class CarCollectionDataProvider implements ContextAwareCollectionDataProviderInterface, RestrictedDataProviderInterface |
| 14 | +{ |
| 15 | + private $managerRegistry; |
| 16 | + private $paginationExtension; |
| 17 | + |
| 18 | + public function __construct(ManagerRegistry $managerRegistry, PaginationExtension $paginationExtension) |
| 19 | + { |
| 20 | + $this->managerRegistry = $managerRegistry; |
| 21 | + $this->paginationExtension = $paginationExtension; |
| 22 | + } |
| 23 | + |
| 24 | + public function supports(string $resourceClass, string $operationName = null, array $context = []): bool |
| 25 | + { |
| 26 | + return Car::class === $resourceClass; |
| 27 | + } |
| 28 | + |
| 29 | + public function getCollection(string $resourceClass, string $operationName = null, array $context = []): iterable |
| 30 | + { |
| 31 | + $queryBuilder = $this->managerRegistry |
| 32 | + ->getManagerForClass($resourceClass) |
| 33 | + ->getRepository($resourceClass)->createQueryBuilder('c'); |
| 34 | + |
| 35 | + if (isset($context['filters']['color'])) { |
| 36 | + $queryBuilder |
| 37 | + ->where('c.color = :color') |
| 38 | + ->setParameter('color', $context['filters']['color']) |
| 39 | + ; |
| 40 | + } |
| 41 | + |
| 42 | + $this->paginationExtension->applyToCollection($queryBuilder, new QueryNameGenerator(), $resourceClass, $operationName, $context); |
| 43 | + |
| 44 | + if ($this->paginationExtension instanceof QueryResultCollectionExtensionInterface && |
| 45 | + $this->paginationExtension->supportsResult($resourceClass, $operationName, $context)) { |
| 46 | + return $this->paginationExtension->getResult($queryBuilder, $resourceClass, $operationName, $context); |
| 47 | + } |
| 48 | + |
| 49 | + return $queryBuilder->getQuery()->getResult(); |
| 50 | + |
| 51 | + } |
| 52 | +} |
0 commit comments