EnumProvider.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\State\Provider\Enum;
  4. use ApiPlatform\Metadata\GetCollection;
  5. use ApiPlatform\Metadata\Operation;
  6. use ApiPlatform\State\ProviderInterface;
  7. use App\ApiResources\Enum\Enum;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use App\Service\Utils\Parser\YamlParser;
  10. use App\Service\Utils\Reflection;
  11. use Exception;
  12. use RuntimeException;
  13. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  14. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  15. /**
  16. * Class EnumProvider : custom provider pour assurer l'alimentation des enums
  17. * @package App\DataProvider\Access
  18. */
  19. final class EnumProvider implements ProviderInterface
  20. {
  21. public function __construct(
  22. private Reflection $reflection,
  23. private readonly ParameterBagInterface $parameterBag
  24. )
  25. { }
  26. /**
  27. * @param Operation $operation
  28. * @param mixed[] $uriVariables
  29. * @param mixed[] $context
  30. * @return Enum|null
  31. */
  32. public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?Enum
  33. {
  34. if($operation instanceof GetCollection) {
  35. throw new RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
  36. }
  37. $id = $uriVariables['name'];
  38. $enums = $this->parameterBag->get('opentalent.enum');
  39. $enumClass = $enums[$id];
  40. if(!$enumClass) {
  41. throw new NotFoundHttpException(sprintf('Enum %s does\'nt exist', $id));
  42. }
  43. try{
  44. $items = $this->reflection->dynamicInvokeClassWithArgsAndMethod(
  45. $enumClass,
  46. 'toArray'
  47. );
  48. }catch (Exception){
  49. throw new NotFoundHttpException(sprintf('Enum %s does\'nt exist', $id));
  50. }
  51. $enumResponse = new Enum();
  52. $enumResponse->setName($id);
  53. $enumResponse->setItems($items);
  54. return $enumResponse;
  55. }
  56. }