Save.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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\Topic;
  10. use ForkBB\Models\Action;
  11. use ForkBB\Models\Topic\Topic;
  12. use RuntimeException;
  13. class Save extends Action
  14. {
  15. /**
  16. * Обновляет тему в БД
  17. */
  18. public function update(Topic $topic): Topic
  19. {
  20. if ($topic->id < 1) {
  21. throw new RuntimeException('The model does not have ID');
  22. }
  23. $modified = $topic->getModified();
  24. if (empty($modified)) {
  25. return $topic;
  26. }
  27. $values = $topic->getAttrs();
  28. $fileds = $this->c->dbMap->topics;
  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 $topic;
  39. }
  40. $vars[] = $topic->id;
  41. $set = \implode(', ', $set);
  42. $query = "UPDATE ::topics
  43. SET {$set}
  44. WHERE id=?i";
  45. $this->c->DB->exec($query, $vars);
  46. $topic->resModified();
  47. return $topic;
  48. }
  49. /**
  50. * Добавляет новую тему в БД
  51. */
  52. public function insert(Topic $topic): int
  53. {
  54. if (null !== $topic->id) {
  55. throw new RuntimeException('The model has ID');
  56. }
  57. $attrs = $topic->getAttrs();
  58. $fileds = $this->c->dbMap->topics;
  59. $set = $set2 = $vars = [];
  60. foreach ($attrs as $key => $value) {
  61. if (! isset($fileds[$key])) {
  62. continue;
  63. }
  64. $vars[] = $value;
  65. $set[] = $key;
  66. $set2[] = '?' . $fileds[$key];
  67. }
  68. if (empty($set)) {
  69. throw new RuntimeException('The model is empty');
  70. }
  71. $set = \implode(', ', $set);
  72. $set2 = \implode(', ', $set2);
  73. $query = "INSERT INTO ::topics ({$set})
  74. VALUES ({$set2})";
  75. $this->c->DB->exec($query, $vars);
  76. $topic->id = (int) $this->c->DB->lastInsertId();
  77. $topic->resModified();
  78. return $topic->id;
  79. }
  80. }