126 lines
2.9 KiB
PHP
126 lines
2.9 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 MediaLibrary;
|
|
use Storage;
|
|
|
|
class MediaPath
|
|
{
|
|
|
|
private string $path;
|
|
|
|
public function __construct(string $path)
|
|
{
|
|
$this->path = $path;
|
|
}
|
|
|
|
public function root(): string
|
|
{
|
|
return Storage::path($this->storagePath());
|
|
}
|
|
|
|
public function storagePath(): string
|
|
{
|
|
return "media/{$this->normal()}";
|
|
}
|
|
|
|
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->path, 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->path, PATHINFO_EXTENSION);
|
|
}
|
|
|
|
public function versionsPath(): string
|
|
{
|
|
return "uploads/public/c/{$this->normal()}";
|
|
}
|
|
|
|
public function versionsDirPath(): string
|
|
{
|
|
return pathinfo("uploads/public/c/{$this->normal()}", PATHINFO_DIRNAME);
|
|
}
|
|
|
|
public function publicUrl(): string
|
|
{
|
|
return MediaLibrary::instance()->findFiles($this->path)[0]->publicUrl;
|
|
}
|
|
|
|
public function get(): string
|
|
{
|
|
return MediaLibrary::instance()->get($this->path);
|
|
}
|
|
|
|
public function shouldProcess(): bool
|
|
{
|
|
return collect(Setting::get('folders'))->pluck('folder')->first(
|
|
fn ($folder) => starts_with('/'.$this->normal(), $folder.'/')
|
|
) !== null;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
}
|