oc-resizer-plugin/classes/FileObserver.php

71 lines
2.0 KiB
PHP

<?php
namespace Aweos\Resizer\Classes;
use Aweos\Resizer\Models\Setting;
use Storage;
class FileObserver
{
public function versionsPath(string $mediaPath): string
{
return "uploads/public/c/{$this->normalizePath($mediaPath)}";
}
public function normalizePath(string $path): string
{
return preg_replace('|^/*|', '', $path);
}
public function fullMediaPath(string $path): string
{
return "media/{$this->normalizePath($path)}";
}
public function shouldProcessFile($file): bool
{
return collect(Setting::get('folders'))->pluck('folder')->first(
fn ($folder) => starts_with($file, $folder.'/')
) !== null;
}
public function delete($path): void
{
$dir = pathinfo($path, PATHINFO_DIRNAME);
$base = $dir.'/'.pathinfo($path, PATHINFO_FILENAME);
Storage::delete("uploads/public/c{$path}");
collect(Storage::files("uploads/public/c{$dir}"))->filter(
fn ($file) => preg_match('|'.preg_quote("uploads/public/c{$base}", '|').'-[0-9]+x[0-9]+\.[a-zA-Z]+$|', $file)
)->each(function ($path) {
Storage::delete($path);
});
if (empty(Storage::allFiles("uploads/public/c{$dir}"))) {
Storage::deleteDirectory("uploads/public/c{$dir}");
}
}
public function rename(string $old, string $new): void
{
$dir = pathinfo($old, PATHINFO_DIRNAME);
$base = pathinfo($old, PATHINFO_FILENAME);
$newBase = pathinfo($new, PATHINFO_FILENAME);
$newDir = pathinfo($new, PATHINFO_DIRNAME);
foreach (Storage::files("uploads/public/c{$dir}") as $file) {
if (!preg_match_all('|'.preg_quote("uploads/public/c{$dir}/{$base}", '|').'(-[0-9]+x[0-9]+)?(\.[a-zA-Z]+)$|', $file, $matches)) {
continue;
}
$size = $matches[1][0];
$ext = $matches[2][0];
Storage::move($file, "uploads/public/c{$newDir}/{$newBase}{$size}{$ext}");
}
}
}