Просмотр файла app/Models/Comment.php

Размер файла: 2.76Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Models;
  6.  
  7. use App\Services\Str;
  8. use MotorORM\Builder;
  9. use MotorORM\Collection;
  10.  
  11. /**
  12. * Class Guestbook
  13. *
  14. * @property int $id
  15. * @property string $user_id
  16. * @property string $story_id
  17. * @property string $text
  18. * @property int $rating
  19. * @property int $created_at
  20. *
  21. * @property-read User $user
  22. * @property-read Story $story
  23. * @property-read Poll $poll
  24. * @property-read Collection<Poll> $polls
  25. */
  26. class Comment extends Model
  27. {
  28. protected string $filePath = __DIR__ . '/../../database/comments.csv';
  29.  
  30. /**
  31. * The attributes that should be cast.
  32. */
  33. protected array $casts = [
  34. 'rating' => 'int',
  35. ];
  36.  
  37. /**
  38. * Возвращает связь пользователя
  39. *
  40. * return Builder
  41. */
  42. public function user(): Builder
  43. {
  44. return $this->HasOne(User::class, 'id', 'user_id');
  45. }
  46.  
  47. /**
  48. * Возвращает связь статьи
  49. *
  50. * return Builder
  51. */
  52. public function story(): Builder
  53. {
  54. return $this->HasOne(Story::class, 'id', 'story_id');
  55. }
  56.  
  57. /**
  58. * Возвращает связь голосования пользователя
  59. *
  60. * @return Builder
  61. */
  62. public function poll(): Builder
  63. {
  64. return $this->hasOne(Poll::class, 'entity_id')
  65. ->where('user_id', getUser('id'))
  66. ->where('entity_name', 'comment');
  67. }
  68.  
  69. /**
  70. * Возвращает связь голосований
  71. *
  72. * @return Builder
  73. */
  74. public function polls(): Builder
  75. {
  76. return $this->hasMany(Poll::class, 'entity_id')
  77. ->where('entity_name', 'comment');
  78. }
  79.  
  80. /**
  81. * Возвращает сокращенный текст комментария
  82. *
  83. * @param int $words
  84. *
  85. * @return string
  86. */
  87. public function shortText(int $words = 30): string
  88. {
  89. if (Str::wordCount($this->text) > $words) {
  90. return bbCodeTruncate($this->text, $words);
  91. }
  92.  
  93. return bbCode($this->text);
  94. }
  95.  
  96. /**
  97. * Get format rating
  98. *
  99. * @return string Форматированное число
  100. */
  101. public function getRating(): string
  102. {
  103. if ($this->rating > 0) {
  104. $rating = '<span style="color:#00aa00">+' . $this->rating . '</span>';
  105. } elseif ($this->rating < 0) {
  106. $rating = '<span style="color:#ff0000">' . $this->rating . '</span>';
  107. } else {
  108. $rating = '<span>0</span>';
  109. }
  110.  
  111. return $rating;
  112. }
  113.  
  114. /**
  115. * Delete comment
  116. *
  117. * @return int
  118. */
  119. public function delete(): int
  120. {
  121. // delete polls
  122. foreach ($this->polls as $poll) {
  123. $poll->delete();
  124. }
  125.  
  126. return parent::delete();
  127. }
  128. }