Просмотр файла app/Traits/UploadTrait.php

Размер файла: 2.5Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Traits;
  6.  
  7. use App\Models\File;
  8. use Illuminate\Http\UploadedFile;
  9. use Intervention\Image\Constraint;
  10. use Intervention\Image\ImageManagerStatic as Image;
  11.  
  12. trait UploadTrait
  13. {
  14. /**
  15. * Загружает изображение
  16. *
  17. * @param UploadedFile $file Объект изображения
  18. * @param bool $record
  19. *
  20. * @return array
  21. */
  22. public function uploadFile(UploadedFile $file, bool $record = true): array
  23. {
  24. $mime = $file->getClientMimeType();
  25. $extension = strtolower($file->getClientOriginalExtension());
  26. $basename = getBodyName($file->getClientOriginalName());
  27. $basename = utfSubstr($basename, 0, 50) . '.' . $extension;
  28. $filename = uniqueName($extension);
  29. $path = $this->uploadPath . '/' . $filename;
  30. $fullPath = public_path($path);
  31. $isImage = in_array($extension, ['jpg', 'jpeg', 'gif', 'png'], true);
  32.  
  33. if ($isImage) {
  34. $img = Image::make($file);
  35.  
  36. if ($img->getWidth() <= 100 && $img->getHeight() <= 100) {
  37. $file->move(public_path($this->uploadPath), $filename);
  38. } else {
  39. $img->resize(setting('screensize'), setting('screensize'), static function (Constraint $constraint) {
  40. $constraint->aspectRatio();
  41. $constraint->upsize();
  42. });
  43.  
  44. if (setting('copyfoto')) {
  45. $img->insert(public_path('assets/img/images/watermark.png'), 'bottom-right', 10, 10);
  46. }
  47.  
  48. $img->save($fullPath);
  49. }
  50. } else {
  51. $file->move(public_path($this->uploadPath), $filename);
  52. }
  53.  
  54. $filesize = filesize($fullPath);
  55.  
  56. if ($record) {
  57. $upload = File::query()->create([
  58. 'relate_id' => $this->id ?? 0,
  59. 'relate_type' => $this->getMorphClass(),
  60. 'hash' => $path,
  61. 'name' => $basename,
  62. 'size' => $filesize,
  63. 'user_id' => getUser('id'),
  64. 'created_at' => SITETIME,
  65. ]);
  66. }
  67.  
  68. return [
  69. 'id' => $upload->id ?? 0,
  70. 'path' => $path,
  71. 'name' => $basename,
  72. 'extension' => $extension,
  73. 'mime' => $mime,
  74. 'size' => formatSize($filesize),
  75. 'type' => $isImage ? 'image' : 'file',
  76. ];
  77. }
  78. }