CalcStat.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\Topic;
  10. use ForkBB\Models\Method;
  11. use ForkBB\Models\Topic\Topic;
  12. use PDO;
  13. use RuntimeException;
  14. class CalcStat extends Method
  15. {
  16. /**
  17. * Пересчитывает статистику темы
  18. */
  19. public function calcStat(): Topic
  20. {
  21. if ($this->model->id < 1) {
  22. throw new RuntimeException('The model does not have ID');
  23. }
  24. if ($this->model->moved_to) {
  25. $numReplies = 0;
  26. } else {
  27. $vars = [
  28. ':tid' => $this->model->id,
  29. ];
  30. $query = 'SELECT COUNT(p.id), MIN(p.id), MAX(p.id)
  31. FROM ::posts AS p
  32. WHERE p.topic_id=?i:tid';
  33. list($count, $minId, $maxId) = $this->c->DB->query($query, $vars)->fetch(PDO::FETCH_NUM);
  34. if (
  35. empty($count)
  36. || empty($minId)
  37. || empty($maxId)
  38. ) {
  39. throw new RuntimeException("Bad topic: {$this->model->id}");
  40. }
  41. $numReplies = $count - 1;
  42. $vars = [
  43. ':ids' => [$minId, $maxId],
  44. ];
  45. $query = 'SELECT p.id, p.poster, p.poster_id, p.posted, p.edited
  46. FROM ::posts AS p
  47. WHERE p.id IN(?ai:ids)';
  48. $result = $this->c->DB->query($query, $vars)->fetchAll(PDO::FETCH_UNIQUE);
  49. $row = $result[$minId];
  50. $this->model->first_post_id = $minId;
  51. $this->model->poster = $row['poster'];
  52. $this->model->poster_id = $row['poster_id'];
  53. $this->model->posted = $row['posted'];
  54. $row = $result[$maxId];
  55. $this->model->last_post_id = $maxId;
  56. $this->model->last_poster = $row['poster'];
  57. $this->model->last_poster_id = $row['poster_id'];
  58. $this->model->last_post = $row['edited'] > $row['posted'] ? $row['edited'] : $row['posted'];
  59. }
  60. $this->model->num_replies = $numReplies;
  61. return $this->model;
  62. }
  63. }