EntityProcessor.php 2.2 KB

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