Save.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * This file is part of the ForkBB <https://github.com/forkbb>.
  4. *
  5. * @copyright (c) Visman <mio.visman@yandex.ru, https://github.com/MioVisman>
  6. * @license The MIT License (MIT)
  7. */
  8. declare(strict_types=1);
  9. namespace ForkBB\Models\Report;
  10. use ForkBB\Models\Action;
  11. use ForkBB\Models\Report\Report;
  12. use RuntimeException;
  13. class Save extends Action
  14. {
  15. /**
  16. * Обновляет репорт в БД
  17. */
  18. public function update(Report $report): Report
  19. {
  20. if ($report->id < 1) {
  21. throw new RuntimeException('The model does not have ID');
  22. }
  23. $modified = $report->getModified();
  24. if (empty($modified)) {
  25. return $report;
  26. }
  27. $values = $report->getAttrs();
  28. $fileds = $this->c->dbMap->reports;
  29. $set = $vars = [];
  30. foreach ($modified as $name) {
  31. if (! isset($fileds[$name])) {
  32. continue;
  33. }
  34. $vars[] = $values[$name];
  35. $set[] = $name . '=?' . $fileds[$name];
  36. }
  37. if (empty($set)) {
  38. return $report;
  39. }
  40. $vars[] = $report->id;
  41. $set = \implode(', ', $set);
  42. $query = "UPDATE ::reports
  43. SET {$set}
  44. WHERE id=?i";
  45. $this->c->DB->exec($query, $vars);
  46. $report->resModified();
  47. return $report;
  48. }
  49. /**
  50. * Добавляет новый репорт в БД
  51. */
  52. public function insert(Report $report): int
  53. {
  54. if (null !== $report->id) {
  55. throw new RuntimeException('The model has ID');
  56. }
  57. $report->created = \time();
  58. $attrs = $report->getAttrs();
  59. $fileds = $this->c->dbMap->reports;
  60. $set = $set2 = $vars = [];
  61. foreach ($attrs as $key => $value) {
  62. if (! isset($fileds[$key])) {
  63. continue;
  64. }
  65. $vars[] = $value;
  66. $set[] = $key;
  67. $set2[] = '?' . $fileds[$key];
  68. }
  69. if (empty($set)) {
  70. throw new RuntimeException('The model is empty');
  71. }
  72. $set = \implode(', ', $set);
  73. $set2 = \implode(', ', $set2);
  74. $query = "INSERT INTO ::reports ({$set})
  75. VALUES ({$set2})";
  76. $this->c->DB->exec($query, $vars);
  77. $report->id = (int) $this->c->DB->lastInsertId();
  78. $report->resModified();
  79. if (true !== $this->c->Cache->set('report', $report->id)) {
  80. throw new RuntimeException('Unable to write value to cache - report');
  81. }
  82. return $report->id;
  83. }
  84. }