Resizable.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Dcat\Admin\Traits;
  3. use Illuminate\Support\Facades\Storage;
  4. use Illuminate\Support\Str;
  5. trait Resizable
  6. {
  7. /**
  8. * Method for returning specific thumbnail for model.
  9. *
  10. * @param string $type
  11. * @param string $attribute
  12. *
  13. * @return string|null
  14. */
  15. public function thumbnail($type, $attribute = 'image', $disk = null)
  16. {
  17. // Return empty string if the field not found
  18. if (! isset($this->attributes[$attribute])) {
  19. return '';
  20. }
  21. // We take image from posts field
  22. $image = $this->attributes[$attribute];
  23. $thumbnail = $this->getThumbnailPath($image, $type);
  24. return Storage::disk($disk ?: config('admin.upload.disk'))->exists($thumbnail) ? $thumbnail : null;
  25. }
  26. /**
  27. * Generate thumbnail URL.
  28. *
  29. * @param $image
  30. * @param $type
  31. *
  32. * @return string
  33. */
  34. public function getThumbnailPath($image, $type)
  35. {
  36. // We need to get extension type ( .jpeg , .png ...)
  37. $ext = pathinfo($image, PATHINFO_EXTENSION);
  38. // We remove extension from file name so we can append thumbnail type
  39. $name = Str::replaceLast('.'.$ext, '', $image);
  40. // We merge original name + type + extension
  41. return $name.'-'.$type.'.'.$ext;
  42. }
  43. }