2
0

UnitOfWork.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace PhpDevCommunity\PaperORM;
  3. final class UnitOfWork
  4. {
  5. /**
  6. * A list of all pending entity insertions.
  7. *
  8. * @psalm-var array<int, object>
  9. */
  10. private array $entityInsertions = [];
  11. /**
  12. * A list of all pending entity updates.
  13. *
  14. * @psalm-var array<int, object>
  15. */
  16. private array $entityUpdates = [];
  17. /**
  18. * A list of all pending entity deletions.
  19. *
  20. * @psalm-var array<int, object>
  21. */
  22. private array $entityDeletions = [];
  23. public function getEntityInsertions(): array
  24. {
  25. return $this->entityInsertions;
  26. }
  27. public function getEntityUpdates(): array
  28. {
  29. return $this->entityUpdates;
  30. }
  31. public function getEntityDeletions(): array
  32. {
  33. return $this->entityDeletions;
  34. }
  35. public function persist(object $entity): void
  36. {
  37. $this->unsetEntity($entity);
  38. $id = spl_object_id($entity);
  39. if (!$entity->getPrimaryKeyValue()) {
  40. $this->entityInsertions[$id] = $entity;
  41. return;
  42. }
  43. $this->entityUpdates[$id] = $entity;
  44. }
  45. public function remove(object $entity): void
  46. {
  47. $this->unsetEntity($entity);
  48. $id = spl_object_id($entity);
  49. $this->entityDeletions[$id] = $entity;
  50. }
  51. public function unsetEntity(object $entity): void
  52. {
  53. $id = spl_object_id($entity);
  54. if (isset($this->entityUpdates[$id])) {
  55. unset($this->entityUpdates[$id]);
  56. }
  57. if (isset($this->entityInsertions[$id])) {
  58. unset($this->entityInsertions[$id]);
  59. }
  60. if (isset($this->entityDeletions[$id])) {
  61. unset($this->entityDeletions[$id]);
  62. }
  63. }
  64. public function clear(): void
  65. {
  66. $this->entityInsertions = [];
  67. $this->entityUpdates = [];
  68. $this->entityDeletions = [];
  69. }
  70. }