Skip to content

Instantly share code, notes, and snippets.

@Muetze42
Last active September 25, 2022 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Muetze42/327605c8ddab313cbfc600b00c6f78e0 to your computer and use it in GitHub Desktop.
Save Muetze42/327605c8ddab313cbfc600b00c6f78e0 to your computer and use it in GitHub Desktop.
Custom Path Generator for „Spatie Media Library“
<?php
namespace App\Support\Spatie;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Support\PathGenerator\PathGenerator;
class CustomPathGenerator implements PathGenerator
{
/*
* Get the path for the given media, relative to the root storage path.
*/
public function getPath(Media $media): string
{
return $this->getBasePath($media).'/';
}
/*
* Get the path for conversions of the given media, relative to the root storage path.
*/
public function getPathForConversions(Media $media): string
{
return $this->getBasePath($media).'/conversions/';
}
/*
* Get the path for responsive images of the given media, relative to the root storage path.
*/
public function getPathForResponsiveImages(Media $media): string
{
return $this->getBasePath($media).'/responsive-images/';
}
/*
* Get a unique base path for the given media.
*/
protected function getBasePath(Media $media): string
{
$prefix = config('media-library.prefix', 'shipment-provider');
if ($prefix !== '') {
return $prefix.'/'.$media->getKey();
}
if (!empty($media->model_type)) {
$key = $media->getKey();
return Str::kebab(Str::plural(class_basename($media->model_type))).'/'.splitSteps($key).'/'.$key;
}
return $media->getKey();
}
}
<?php
if (!function_exists('splitSteps')) {
/**
* Get `main` number to sub sort files in folders
*
* @param int $int
* @param int $steps
* @return int
*/
function splitSteps(int $int, int $steps = 100): int
{
return (int) (floor($int/$steps))*$steps;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment