oc-resizer-plugin/lib/MediaPath.php

135 lines
3.3 KiB
PHP

<?php
namespace Aweos\Resizer\Lib;
use Aweos\Resizer\Compressors\Compressor;
use Aweos\Resizer\Compressors\Factory as CompressorFactory;
use Aweos\Resizer\Models\Setting;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
abstract class MediaPath
{
protected string $path;
abstract public function get(): string;
abstract public function root(): string;
abstract public function publicUrl(): string;
public function __construct(string $path)
{
$this->path = $path;
}
public function normal(): string
{
return preg_replace('|^/*|', '', $this->path);
}
public function compressor(): Compressor
{
return app(CompressorFactory::class)->resolve($this);
}
public function filename(): string
{
return pathinfo($this->root(), PATHINFO_FILENAME);
}
public function exists(): bool
{
return file_exists($this->root());
}
public function type(): ?string
{
if (!$this->exists()) {
return null;
}
return mime_content_type($this->root());
}
public function extension(): string
{
return pathinfo($this->root(), PATHINFO_EXTENSION);
}
public function versionsPath(): string
{
return "uploads/public/c/{$this->normal()}";
}
public function versionsDirPath(): string
{
return pathinfo($this->versionsPath(), PATHINFO_DIRNAME);
}
public function shouldProcess(): bool
{
return null !== collect(Setting::get('folders'))->pluck('folder')->first(
fn ($folder) => starts_with('/'.$this->normal(), $folder.'/')
);
}
public function versions(): Collection
{
$return = collect([]);
$extensionRegex = $this->compressor()->getExtensionRegex();
foreach (Storage::files($this->versionsDirPath()) as $file) {
if (!preg_match_all('|('.preg_quote($this->filename(), '|').')(-[0-9]+x[0-9]+)?(\.'.$extensionRegex.'+)$|', $file, $matches)) {
continue;
}
if ($matches[2][0]) {
[$width, $height] = explode('x', substr($matches[2][0], 1));
}
$path = $this->versionsDirPath().'/'.$matches[0][0];
$return->push(collect([
'path' => $path,
'url' => Storage::url($path),
'filename' => $matches[0][0],
'base' => $matches[1][0],
'size' => $matches[2][0],
'ext' => $matches[3][0],
'width' => $width ?? null,
'height' => $height ?? null,
]));
}
return $return;
}
public function sluggifyPath(): string
{
$fileinfo = pathinfo($this->path);
$filename = $fileinfo['dirname'].'/';
return $filename
.static::sluggifyString($fileinfo['filename'])
.'.'
.$fileinfo['extension'];
}
protected function storagePath(): string
{
return "media/{$this->normal()}";
}
public static function sluggifyString(string $input): string
{
return str_slug(strtr($input, [
'ö' => 'oe',
'ä' => 'ae',
'ü' => 'ue',
'ß' => 'ss',
]));
}
}