Save.php 2.5 KB

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