Skip to content

Instantly share code, notes, and snippets.

@belzaaron
Last active February 25, 2022 22:10
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 belzaaron/bff713e7a73a489784745b7efa2b085e to your computer and use it in GitHub Desktop.
Save belzaaron/bff713e7a73a489784745b7efa2b085e to your computer and use it in GitHub Desktop.
This provides a model-level control for URL generator classes for spatie/laravel-medialibrary. See PR: https://github.com/spatie/laravel-medialibrary/pull/2809. Tested on: spatie/laravel-medialibrary version: 10.1.1
/**
* Get the classpath of the url generator used by the model.
*
* @return string
*/
public function getUrlGeneratorClass(): string
{
return \App\Services\SpatieMediaLibrary\SomeUrlGenerator::class;
}
<?php
namespace App\Services\SpatieMediaLibrary;
use DateTimeInterface;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\Support\UrlGenerator\DefaultUrlGenerator;
use Spatie\MediaLibrary\Support\UrlGenerator\UrlGenerator;
class ModelUrlGeneratorResolver extends DefaultUrlGenerator
{
public function getUrl(): string
{
return $this->resolveGeneratorFromModelType()->getUrl();
}
public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string
{
return $this->resolveGeneratorFromModelType()->getDisk()->temporaryUrl($this->resolveGeneratorFromModelType()->getPathRelativeToRoot(), $expiration, $options);
}
public function getBaseMediaDirectoryUrl(): string
{
return $this->resolveGeneratorFromModelType()->getDisk()->url('/');
}
public function getPath(): string
{
return $this->resolveGeneratorFromModelType()->getRootOfDisk().$this->resolveGeneratorFromModelType()->getPathRelativeToRoot();
}
public function getResponsiveImagesDirectoryUrl(): string
{
$base = Str::finish($this->resolveGeneratorFromModelType()->getBaseMediaDirectoryUrl(), '/');
$path = $this->pathGenerator->resolveGeneratorFromModelType()->getPathForResponsiveImages($this->media);
return Str::finish(url($base.$path), '/');
}
protected function getRootOfDisk(): string
{
return config("filesystems.disks.{$this->resolveGeneratorFromModelType()->getDiskName()}.root") . '/';
}
/**
* Resolve the generator from the model type.
*
* @return UrlGenerator
*/
public function resolveGeneratorFromModelType(): UrlGenerator
{
$generator = DefaultUrlGenerator::class;
if (method_exists($this->media->model, 'getUrlGeneratorClass')) {
$generator = $this->media->model->getUrlGeneratorClass();
}
return tap(new $generator($this->config), function (UrlGenerator $generator) {
if (! is_null($this->conversion)) {
$generator->setConversion($this->conversion);
}
return $generator->setPathGenerator($this->pathGenerator)
->setMedia($this->media);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment