Save.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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\PM;
  10. use ForkBB\Models\Method;
  11. use ForkBB\Models\DataModel;
  12. use ForkBB\Models\PM\Cnst;
  13. use ForkBB\Models\PM\PPost;
  14. use ForkBB\Models\PM\PTopic;
  15. use ForkBB\Models\PM\PRnd;
  16. use InvalidArgumentException;
  17. use RuntimeException;
  18. class Save extends Method
  19. {
  20. public function update(DataModel $model): DataModel
  21. {
  22. if ($model->id < 1) {
  23. throw new RuntimeException('The model does not have ID');
  24. }
  25. if ($model instanceof PPost) {
  26. $table = 'pm_posts';
  27. } elseif ($model instanceof PTopic) {
  28. $table = 'pm_topics';
  29. } else {
  30. throw new InvalidArgumentException('Bad model');
  31. }
  32. $modified = $model->getModified();
  33. if (empty($modified)) {
  34. return $model;
  35. }
  36. $values = $model->getAttrs();
  37. $fileds = $this->c->dbMap->{$table};
  38. $set = $vars = [];
  39. foreach ($modified as $name) {
  40. if (! isset($fileds[$name])) {
  41. continue;
  42. }
  43. $vars[] = $values[$name];
  44. $set[] = $name . '=?' . $fileds[$name];
  45. }
  46. if (empty($set)) {
  47. return $model;
  48. }
  49. $vars[] = $model->id;
  50. $set = \implode(', ', $set);
  51. $query = "UPDATE ::{$table} SET {$set} WHERE id=?i";
  52. $this->c->DB->exec($query, $vars);
  53. $model->resModified();
  54. return $model;
  55. }
  56. public function insert(DataModel $model): int
  57. {
  58. if (null !== $model->id) {
  59. throw new RuntimeException('The model has ID');
  60. }
  61. if ($model instanceof PPost) {
  62. $table = 'pm_posts';
  63. } elseif ($model instanceof PTopic) {
  64. $table = 'pm_topics';
  65. } else {
  66. throw new InvalidArgumentException('Bad model');
  67. }
  68. $attrs = $model->getAttrs();
  69. $fileds = $this->c->dbMap->{$table};
  70. $set = $set2 = $vars = [];
  71. foreach ($attrs as $key => $value) {
  72. if (! isset($fileds[$key])) {
  73. continue;
  74. }
  75. $vars[] = $value;
  76. $set[] = $key;
  77. $set2[] = '?' . $fileds[$key];
  78. }
  79. if (empty($set)) {
  80. throw new RuntimeException('The model is empty');
  81. }
  82. $set = \implode(', ', $set);
  83. $set2 = \implode(', ', $set2);
  84. $query = "INSERT INTO ::{$table} ({$set}) VALUES ({$set2})";
  85. $this->c->DB->exec($query, $vars);
  86. $model->id = (int) $this->c->DB->lastInsertId();
  87. $model->resModified();
  88. return $model->id;
  89. }
  90. }