|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace SchedulerBundle\Bridge\ApiPlatform; |
| 6 | + |
| 7 | +use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface; |
| 8 | +use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface; |
| 9 | +use Psr\Log\LoggerInterface; |
| 10 | +use Psr\Log\NullLogger; |
| 11 | +use SchedulerBundle\Bridge\ApiPlatform\Filter\SearchFilter; |
| 12 | +use SchedulerBundle\Task\TaskInterface; |
| 13 | +use SchedulerBundle\Task\TaskListInterface; |
| 14 | +use SchedulerBundle\Transport\TransportInterface; |
| 15 | +use Throwable; |
| 16 | +use function array_key_exists; |
| 17 | + |
| 18 | +/** |
| 19 | + * @author Guillaume Loulier <[email protected]> |
| 20 | + */ |
| 21 | +final class CollectionDataProvider implements ContextAwareCollectionDataProviderInterface, RestrictedDataProviderInterface |
| 22 | +{ |
| 23 | + private SearchFilter $searchFilter; |
| 24 | + private TransportInterface $transport; |
| 25 | + private LoggerInterface $logger; |
| 26 | + |
| 27 | + public function __construct( |
| 28 | + SearchFilter $searchFilter, |
| 29 | + TransportInterface $transport, |
| 30 | + ?LoggerInterface $logger = null |
| 31 | + ) { |
| 32 | + $this->searchFilter = $searchFilter; |
| 33 | + $this->transport = $transport; |
| 34 | + $this->logger = $logger ?: new NullLogger(); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * {@inheritdoc} |
| 39 | + */ |
| 40 | + public function supports(string $resourceClass, string $operationName = null, array $context = []): bool |
| 41 | + { |
| 42 | + return $resourceClass === TaskInterface::class; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * {@inheritdoc} |
| 47 | + */ |
| 48 | + public function getCollection(string $resourceClass, string $operationName = null, array $context = []): TaskListInterface |
| 49 | + { |
| 50 | + try { |
| 51 | + $list = $this->transport->list(); |
| 52 | + } catch (Throwable $throwable) { |
| 53 | + $this->logger->critical('The list cannot be retrieved', [ |
| 54 | + 'error' => $throwable->getMessage(), |
| 55 | + ]); |
| 56 | + |
| 57 | + throw $throwable; |
| 58 | + } |
| 59 | + |
| 60 | + if (array_key_exists('filters', $context) && [] !== $context['filters']) { |
| 61 | + return $this->searchFilter->filter($list, $context['filters']); |
| 62 | + } |
| 63 | + |
| 64 | + return $list; |
| 65 | + } |
| 66 | +} |
0 commit comments