EntityProcessor.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\State\Processor;
  4. use ApiPlatform\Metadata\Delete;
  5. use ApiPlatform\Metadata\Operation;
  6. use ApiPlatform\State\ProcessorInterface;
  7. use App\Service\OnChange\OnChangeContext;
  8. use App\Service\OnChange\OnChangeDefault;
  9. use App\Service\OnChange\OnChangeInterface;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Contracts\Service\Attribute\Required;
  12. /**
  13. * Classe de base pour les Processor classiques, proposant des hook pre et post persist,
  14. * ainsi que certaines méthodes liées au contexte de la mise à jour.
  15. */
  16. class EntityProcessor implements ProcessorInterface
  17. {
  18. // <-- dependencies injections
  19. protected ProcessorInterface $persistProcessor;
  20. protected OnChangeInterface $onChange;
  21. public function __construct(
  22. OnChangeDefault $onChange,
  23. ) {
  24. $this->onChange = $onChange;
  25. }
  26. #[Required]
  27. public function setProcessorInterface(ProcessorInterface $persistProcessor): void
  28. {
  29. $this->persistProcessor = $persistProcessor;
  30. }
  31. /**
  32. * Persiste l'entité et déclenche les différents hooks de la classe OnChangeInterface définie par le data persister.
  33. *
  34. * @param mixed[] $uriVariables
  35. * @param mixed[] $context
  36. */
  37. public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): object
  38. {
  39. if ($operation instanceof Delete) {
  40. throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
  41. }
  42. $onChangeContext = new OnChangeContext($context);
  43. $this->onChange->validate($data, $onChangeContext);
  44. $data = $this->onChange->preProcess($data, $onChangeContext);
  45. $this->onChange->beforeChange($data, $onChangeContext);
  46. $result = $this->persistProcessor->process($data, $operation, $uriVariables, $context);
  47. $this->onChange->onChange($data, $onChangeContext);
  48. return $result;
  49. }
  50. }