Load.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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\Action;
  11. use ForkBB\Models\Poll\Poll;
  12. use InvalidArgumentException;
  13. class Load extends Action
  14. {
  15. /**
  16. * Загружает опрос из БД
  17. */
  18. public function load(int $id): ?Poll
  19. {
  20. if ($id < 1) {
  21. throw new InvalidArgumentException('Expected a positive poll id');
  22. }
  23. $vars = [
  24. ':tid' => $id,
  25. ];
  26. $query = 'SELECT question_id, field_id, qna_text, votes
  27. FROM ::poll
  28. WHERE tid=?i:tid
  29. ORDER BY question_id, field_id';
  30. $stmt = $this->c->DB->query($query, $vars);
  31. $i = 0;
  32. $data = [
  33. 'tid' => $id,
  34. 'question' => [],
  35. 'answer' => [],
  36. 'vote' => [],
  37. 'type' => [],
  38. 'total' => [],
  39. ];
  40. while ($row = $stmt->fetch()) {
  41. $qid = $row['question_id'];
  42. $fid = $row['field_id'];
  43. if (0 === $fid) {
  44. list($type, $question) = \explode('|', $row['qna_text'], 2);
  45. $data['question'][$qid] = $question;
  46. $data['type'][$qid] = (int) $type;
  47. $data['total'][$qid] = $row['votes'];
  48. } else {
  49. $data['answer'][$qid][$fid] = $row['qna_text'];
  50. $data['vote'][$qid][$fid] = $row['votes'];
  51. }
  52. ++$i;
  53. }
  54. if (0 === $i) {
  55. return null;
  56. } else {
  57. return $this->manager->create($data);
  58. }
  59. }
  60. }