Polls.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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\Poll;
  10. use ForkBB\Models\Manager;
  11. use ForkBB\Models\Poll\Poll;
  12. use RuntimeException;
  13. class Polls extends Manager
  14. {
  15. /**
  16. * Ключ модели для контейнера
  17. * @var string
  18. */
  19. protected $cKey = 'Polls';
  20. /**
  21. * Создает новый опрос
  22. */
  23. public function create(array $attrs = []): Poll
  24. {
  25. return $this->c->PollModel->setAttrs($attrs);
  26. }
  27. /**
  28. * Получает опрос по id
  29. */
  30. public function load(int $id): ?Poll
  31. {
  32. if ($this->isset($id)) {
  33. return $this->get($id);
  34. } else {
  35. $data = $this->c->Cache->get("poll{$id}", false);
  36. if (null === $data) {
  37. $poll = null;
  38. } elseif (\is_array($data)) {
  39. $poll = $this->create($data);
  40. } else {
  41. $poll = $this->Load->load($id);
  42. $data = $poll instanceof Poll ? $poll->getAttrs() : null; // ????
  43. $this->c->Cache->set("poll{$id}", $data);
  44. }
  45. $this->set($id, $poll);
  46. return $poll;
  47. }
  48. }
  49. /**
  50. * Обновляет опрос в БД
  51. */
  52. public function update(Poll $poll): Poll
  53. {
  54. $poll = $this->Save->update($poll);
  55. if (true === $poll->itWasModified) {
  56. $this->reset($poll->tid);
  57. }
  58. return $poll;
  59. }
  60. /**
  61. * Добавляет новый опрос в БД
  62. */
  63. public function insert(Poll $poll): int
  64. {
  65. $id = $this->Save->insert($poll);
  66. $this->set($id, $poll);
  67. return $id;
  68. }
  69. /**
  70. * Сбрасывает кеш указанного голосования
  71. */
  72. public function reset(int $id): Polls
  73. {
  74. if (true !== $this->c->Cache->delete("poll{$id}")) {
  75. throw new RuntimeException("Unable to remove key from cache - poll{$id}");
  76. }
  77. return $this;
  78. }
  79. }