FreemiumPlaceProvider.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\State\Provider\Freemium;
  4. use ApiPlatform\Metadata\GetCollection;
  5. use ApiPlatform\Metadata\Operation;
  6. use ApiPlatform\State\Pagination\TraversablePaginator;
  7. use ApiPlatform\State\ProviderInterface;
  8. use App\ApiResources\Freemium\FreemiumPlace;
  9. use App\Entity\Place\Place;
  10. use App\Repository\Place\PlaceRepository;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  13. use Symfony\Component\ObjectMapper\ObjectMapperInterface;
  14. /**
  15. * Class FreemiumPlaceProvider : custom provider pour assurer l'alimentation de la réponse du GET freemium/places/{id}.
  16. */
  17. final class FreemiumPlaceProvider implements ProviderInterface
  18. {
  19. public function __construct(
  20. private ObjectMapperInterface $objectMapper,
  21. private PlaceRepository $placeRepository
  22. ) {
  23. }
  24. /**
  25. * @param array<mixed> $uriVariables
  26. * @param array<mixed> $context
  27. *
  28. * @throws \Doctrine\ORM\Exception\ORMException
  29. * @throws \Doctrine\ORM\OptimisticLockException
  30. */
  31. public function provide(Operation $operation, array $uriVariables = [], array $context = []): TraversablePaginator|FreemiumPlace|null
  32. {
  33. if ($operation instanceof GetCollection) {
  34. throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
  35. }
  36. return $this->provideItem($uriVariables, $context);
  37. }
  38. /**
  39. * @param array<mixed> $uriVariables
  40. * @param array<mixed> $context
  41. *
  42. * @throws \Doctrine\ORM\Exception\ORMException
  43. * @throws \Doctrine\ORM\OptimisticLockException
  44. */
  45. private function provideItem(array $uriVariables, array $context): ?FreemiumPlace
  46. {
  47. /** @var Place $place */
  48. $place = $this->placeRepository->find($uriVariables['id']);
  49. if(empty($place)){
  50. throw new NotFoundHttpException('place not found');
  51. }
  52. return $this->objectMapper->map($place, FreemiumPlace::class);
  53. }
  54. }