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

Размер файла: 2.67Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Models;
  6.  
  7. use App\Traits\UploadTrait;
  8. use Exception;
  9. use Illuminate\Database\Eloquent\Collection;
  10. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  11. use Illuminate\Database\Eloquent\Relations\MorphMany;
  12. use Illuminate\Support\HtmlString;
  13.  
  14. /**
  15. * Class Item
  16. *
  17. * @property int id
  18. * @property int board_id
  19. * @property string title
  20. * @property string text
  21. * @property int user_id
  22. * @property int price
  23. * @property string phone
  24. * @property int created_at
  25. * @property int updated_at
  26. * @property int expires_at
  27. * @property Board category
  28. * @property Collection files
  29. */
  30. class Item extends BaseModel
  31. {
  32. use UploadTrait;
  33.  
  34. public const BOARD_PAGINATE = 10;
  35.  
  36. /**
  37. * Indicates if the model should be timestamped.
  38. *
  39. * @var bool
  40. */
  41. public $timestamps = false;
  42.  
  43. /**
  44. * The attributes that aren't mass assignable.
  45. *
  46. * @var array
  47. */
  48. protected $guarded = [];
  49.  
  50. /**
  51. * Директория загрузки файлов
  52. *
  53. * @var string
  54. */
  55. public $uploadPath = '/uploads/boards';
  56.  
  57. /**
  58. * Morph name
  59. *
  60. * @var string
  61. */
  62. public static $morphName = 'items';
  63.  
  64. /**
  65. * Возвращает категорию объявлений
  66. *
  67. * @return BelongsTo
  68. */
  69. public function category(): BelongsTo
  70. {
  71. return $this->belongsTo(Board::class, 'board_id')->withDefault();
  72. }
  73.  
  74. /**
  75. * Возвращает загруженные файлы
  76. */
  77. public function files(): MorphMany
  78. {
  79. return $this->morphMany(File::class, 'relate');
  80. }
  81.  
  82. /**
  83. * Возвращает путь к первому файлу
  84. *
  85. * @return HtmlString|null имя файла
  86. */
  87. public function getFirstImage(): ?HtmlString
  88. {
  89. $image = $this->files->first();
  90.  
  91. $path = $image->hash ?? null;
  92.  
  93. return resizeImage($path, ['alt' => $this->title, 'class' => 'img-fluid']);
  94. }
  95.  
  96. /**
  97. * Возвращает сокращенный текст объявления
  98. *
  99. * @param int $words
  100. * @return HtmlString
  101. */
  102. public function shortText(int $words = 50): HtmlString
  103. {
  104. if (strlen($this->text) > $words) {
  105. $this->text = bbCodeTruncate($this->text, $words);
  106. }
  107.  
  108. return new HtmlString($this->text);
  109. }
  110.  
  111. /**
  112. * Удаление объявления и загруженных файлов
  113. *
  114. * @return bool|null
  115. * @throws Exception
  116. */
  117. public function delete(): ?bool
  118. {
  119. $this->files->each(static function (File $file) {
  120. $file->delete();
  121. });
  122.  
  123. return parent::delete();
  124. }
  125. }