Model.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. use Symfony\Component\HttpFoundation\Response;
  3. class Model {
  4. protected $data = [];
  5. protected $path;
  6. public function __construct(string $path) {
  7. $this->path = $path;
  8. }
  9. /**
  10. * Flush the in-memory storage to disk. Do not load it first.
  11. */
  12. protected function store() {
  13. $raw = json_encode($this->data, JSON_PRETTY_PRINT);
  14. file_put_contents($this->path, $raw);
  15. }
  16. public function load() {
  17. $raw = file_get_contents($this->path);
  18. $this->data = json_decode($raw, true);
  19. return $this->data;
  20. }
  21. public function save(array $doc) {
  22. $this->load();
  23. if (empty($doc['id'])) {
  24. $id = (int) max(array_keys($this->data)) + 1;
  25. $doc['id'] = $id;
  26. $created = true;
  27. }
  28. else {
  29. $id = (int) $doc['id'];
  30. $created = false;
  31. }
  32. $this->data[$id] = $doc;
  33. $this->store();
  34. return $created;
  35. }
  36. public function delete(int $id) {
  37. $this->load();
  38. if (!isset($this->data[$id])) {
  39. return FALSE;
  40. }
  41. unset($this->data[$id]);
  42. $this->store();
  43. return TRUE;
  44. }
  45. }