IdCardRequestProvider.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\State\Provider;
  4. use AltchaOrg\Altcha\V1\Altcha;
  5. use ApiPlatform\Metadata\Get;
  6. use ApiPlatform\Metadata\Operation;
  7. use ApiPlatform\State\ProviderInterface;
  8. use App\ApiResource\CvPdfRequest;
  9. use App\ApiResource\IdCardRequest;
  10. use Path\Exception\FileNotFoundException;
  11. use Path\Exception\IOException;
  12. use Symfony\Component\HttpFoundation\HeaderUtils;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Path\Path;
  15. class IdCardRequestProvider implements ProviderInterface
  16. {
  17. private Altcha $altcha;
  18. public function __construct(
  19. private readonly string $projectDir,
  20. private readonly string $hmacKey,
  21. private readonly string $idAge,
  22. private readonly string $idPlace,
  23. private readonly string $idStatus,
  24. ) {
  25. $this->altcha = new Altcha($this->hmacKey);
  26. }
  27. /**
  28. * @throws IOException
  29. * @throws FileNotFoundException
  30. */
  31. public function provide(Operation $operation, array $uriVariables = [], array $context = []): IdCardRequest
  32. {
  33. if (!$operation instanceof Get) {
  34. throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
  35. }
  36. $filters = $context['filters'] ?? [];
  37. $altchaPayload = $filters['payload'] ?? null;
  38. if ($altchaPayload === null) {
  39. throw new \RuntimeException('missing parameter: payload', Response::HTTP_BAD_REQUEST);
  40. }
  41. try {
  42. $valid = $this->altcha->verifySolution(
  43. urldecode($altchaPayload),
  44. true
  45. );
  46. } catch (\Throwable) {
  47. $valid = false;
  48. }
  49. if (!$valid) {
  50. throw new \RuntimeException('Invalid payload');
  51. }
  52. $photo = (new Path($this->projectDir))
  53. ->append('static', 'profile.min.png')
  54. ->getContent();
  55. $idCardRequest = new IdCardRequest();
  56. $idCardRequest->setPhoto(base64_encode($photo));
  57. $idCardRequest->setPlace($this->idPlace);
  58. $idCardRequest->setAge($this->idAge);
  59. $idCardRequest->setStatus($this->idStatus);
  60. return $idCardRequest;
  61. }
  62. }