Posts.php 2.5 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\Post;
  10. use ForkBB\Models\Manager;
  11. use ForkBB\Models\Post\Post;
  12. class Posts extends Manager
  13. {
  14. /**
  15. * Ключ модели для контейнера
  16. * @var string
  17. */
  18. protected $cKey = 'Posts';
  19. /**
  20. * Создает новую модель сообщения
  21. */
  22. public function create(array $attrs = []): Post
  23. {
  24. return $this->c->PostModel->setAttrs($attrs);
  25. }
  26. /**
  27. * Получает сообщение по id
  28. * Получает сообщение по id и tid темы (с проверкой вхождения)
  29. */
  30. public function load(int $id, int $tid = null): ?Post
  31. {
  32. if ($this->isset($id)) {
  33. $post = $this->get($id);
  34. if (
  35. $post instanceof Post
  36. && null !== $tid
  37. && $post->topic_id !== $tid
  38. ) {
  39. return null;
  40. }
  41. } else {
  42. $post = $this->Load->load($id, $tid);
  43. $this->set($id, $post);
  44. }
  45. return $post;
  46. }
  47. /**
  48. * Получает массив сообщений по ids
  49. */
  50. public function loadByIds(array $ids, bool $withTopics = true): array
  51. {
  52. $result = [];
  53. $data = [];
  54. foreach ($ids as $id) {
  55. if ($this->isset($id)) {
  56. $result[$id] = $this->get($id);
  57. } else {
  58. $result[$id] = null;
  59. $data[] = $id;
  60. $this->set($id, null);
  61. }
  62. }
  63. if (empty($data)) {
  64. return $result;
  65. }
  66. foreach ($this->Load->loadByIds($data, $withTopics) as $post) {
  67. if ($post instanceof Post) {
  68. $result[$post->id] = $post;
  69. $this->set($post->id, $post);
  70. }
  71. }
  72. return $result;
  73. }
  74. /**
  75. * Обновляет сообщение в БД
  76. */
  77. public function update(Post $post): Post
  78. {
  79. return $this->Save->update($post);
  80. }
  81. /**
  82. * Добавляет новое сообщение в БД
  83. */
  84. public function insert(Post $post): int
  85. {
  86. $id = $this->Save->insert($post);
  87. $this->set($id, $post);
  88. return $id;
  89. }
  90. }