BaseDataPersister.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\DataPersister;
  3. use ApiPlatform\Core\DataPersister\ContextAwareDataPersisterInterface;
  4. abstract class BaseDataPersister implements ContextAwareDataPersisterInterface
  5. {
  6. private ContextAwareDataPersisterInterface $decorated;
  7. protected array $context = [];
  8. public function setDecorated(ContextAwareDataPersisterInterface $decorated): void
  9. {
  10. $this->decorated = $decorated;
  11. }
  12. abstract public function supports($data, array $context = []): bool;
  13. public function persist($data, array $context = [])
  14. {
  15. $this->context = $context;
  16. $data = $this->preProcess($data);
  17. $this->prePersist($data);
  18. $result = $this->decorated->persist($data, $context);
  19. $this->postPersist($data);
  20. return $result;
  21. }
  22. protected function preProcess($data) {
  23. return $data;
  24. }
  25. protected function prePersist($data): void {
  26. }
  27. protected function postPersist($data): void {
  28. }
  29. abstract public function remove($data, array $context = []): void;
  30. protected function isPostRequest(): bool {
  31. return $this->context['collection_operation_name'] ?? null === 'post';
  32. }
  33. protected function isPutRequest(): bool {
  34. return $this->context['item_operation_name'] ?? null === 'put';
  35. }
  36. protected function previousData() {
  37. if (!$this->isPutRequest()) {
  38. return null;
  39. }
  40. return $this->context['previous_data'];
  41. }
  42. }