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

Размер файла: 2Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Models;
  6.  
  7. use Exception;
  8. use Illuminate\Database\Eloquent\Relations\MorphTo;
  9.  
  10. /**
  11. * Class File
  12. *
  13. * @property int id
  14. * @property string relate_type
  15. * @property int relate_id
  16. * @property string hash
  17. * @property string name
  18. * @property int size
  19. * @property int user_id
  20. * @property int created_at
  21. * @property string extension
  22. * @property object relate
  23. */
  24. class File extends BaseModel
  25. {
  26. /**
  27. * Indicates if the model should be timestamped.
  28. *
  29. * @var bool
  30. */
  31. public $timestamps = false;
  32.  
  33. /**
  34. * The attributes that aren't mass assignable.
  35. *
  36. * @var array
  37. */
  38. protected $guarded = [];
  39.  
  40. /**
  41. * Возвращает связанные объекты
  42. *
  43. * @return MorphTo
  44. */
  45. public function relate(): MorphTo
  46. {
  47. return $this->morphTo('relate');
  48. }
  49.  
  50. /**
  51. * Возвращает расширение файла
  52. *
  53. * @return string
  54. */
  55. public function getExtensionAttribute(): string
  56. {
  57. return getExtension($this->hash);
  58. }
  59.  
  60. /**
  61. * Возвращает является ли файл картинкой
  62. *
  63. * @return bool
  64. */
  65. public function isImage(): bool
  66. {
  67. return in_array($this->extension, ['jpg', 'jpeg', 'gif', 'png'], true);
  68. }
  69.  
  70. /**
  71. * Скачивает файл
  72. *
  73. * @return void
  74. */
  75. public function download(): void
  76. {
  77. header('Content-Type: application/octet-stream');
  78. header('Content-Disposition: attachment; filename="' . $this->name . '"');
  79. header('Content-Transfer-Encoding: binary');
  80. header('Content-Length: ' . $this->size);
  81. readfile(HOME . $this->hash);
  82. exit;
  83. }
  84.  
  85. /**
  86. * Удаление записи и загруженных файлов
  87. *
  88. * @return bool|null
  89. * @throws Exception
  90. */
  91. public function delete(): ?bool
  92. {
  93. deleteFile(HOME . $this->hash);
  94.  
  95. return parent::delete();
  96. }
  97. }