Save.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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\Forum;
  10. use ForkBB\Models\Action;
  11. use ForkBB\Models\Forum\Forum;
  12. use RuntimeException;
  13. class Save extends Action
  14. {
  15. /**
  16. * Обновляет раздел в БД
  17. */
  18. public function update(Forum $forum): Forum
  19. {
  20. if ($forum->id < 1) {
  21. throw new RuntimeException('The model does not have ID');
  22. }
  23. $modified = $forum->getModified();
  24. if (empty($modified)) {
  25. return $forum;
  26. }
  27. $values = $forum->getAttrs();
  28. $fileds = $this->c->dbMap->forums;
  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 $forum;
  39. }
  40. $vars[] = $forum->id;
  41. $query = 'UPDATE ::forums
  42. SET ' . \implode(', ', $set) . ' WHERE id=?i';
  43. $this->c->DB->exec($query, $vars);
  44. // модификация категории у потомков при ее изменении
  45. if (
  46. \in_array('cat_id', $modified)
  47. && $forum->descendants
  48. ) {
  49. foreach ($forum->descendants as $f) {
  50. $f->__cat_id = $values['cat_id'];
  51. }
  52. $vars = [
  53. ':ids' => \array_keys($forum->descendants),
  54. ':category' => $values['cat_id'],
  55. ];
  56. $query = 'UPDATE ::forums
  57. SET cat_id=?i:category
  58. WHERE id IN (?ai:ids)';
  59. $this->c->DB->exec($query, $vars);
  60. }
  61. $forum->resModified();
  62. return $forum;
  63. }
  64. /**
  65. * Добавляет новый раздел в БД
  66. */
  67. public function insert(Forum $forum): int
  68. {
  69. if (null !== $forum->id) {
  70. throw new RuntimeException('The model has ID');
  71. }
  72. $attrs = $forum->getAttrs();
  73. $fileds = $this->c->dbMap->forums;
  74. $set = $set2 = $vars = [];
  75. foreach ($attrs as $key => $value) {
  76. if (! isset($fileds[$key])) {
  77. continue;
  78. }
  79. $vars[] = $value;
  80. $set[] = $key;
  81. $set2[] = '?' . $fileds[$key];
  82. }
  83. if (empty($set)) {
  84. throw new RuntimeException('The model is empty');
  85. }
  86. $query = 'INSERT INTO ::forums (' . \implode(', ', $set) . ')
  87. VALUES (' . \implode(', ', $set2) . ')';
  88. $this->c->DB->exec($query, $vars);
  89. $forum->id = (int) $this->c->DB->lastInsertId();
  90. $forum->resModified();
  91. return $forum->id;
  92. }
  93. }