oc-resizer-plugin/classes/UploadStorage.php

95 lines
2.8 KiB
PHP
Raw Normal View History

2020-10-25 20:53:10 +01:00
<?php
namespace Aweos\Resizer\Classes;
use Queue;
use Storage;
class UploadStorage {
public $disk = 'uploads';
public $file;
public $data;
public $strategy = FirstLetterStrategy::class;
public function storeFileFromUpload($uploadedFile, $data) {
$this->file = $uploadedFile;
$this->data = $data;
$fileName = $this->getStrategy()->sourceFileBasename($this->file, $this->data);
$sourcePath = $this->getStrategy()->sourcePath($fileName);
$fileName = $this->transformFileName($sourcePath, $fileName).'.'.$this->file->getClientOriginalExtension();
$uploadedFile->storeAs($sourcePath, $fileName, $this->disk);
Queue::push(CompressJob::class, [
'path' => $sourcePath,
'filename' => $fileName,
'disk' => $this->disk,
'strategy' => $this->strategy,
'crop' => $this->data['crop']
]);
2020-10-25 23:02:13 +01:00
return $sourcePath.'/'.$fileName;
}
public function getFileData($filename) {
$realname = preg_replace('/^source/', 'cropped', $filename);
return [
'url' => $this->storage()->url($realname),
'type' => $this->storage()->mimeType($filename),
'size' => $this->storage()->size($filename),
'name' => pathinfo($filename, PATHINFO_BASENAME)
];
}
public function removeFile($filename) {
$sourcePath = $this->getStrategy()->sourcePath($filename).'/'.$filename;
$croppedPath = $this->getStrategy()->croppedPath().'/'.$filename;
if (!Storage::disk($this->disk)->exists($sourcePath)) {
return;
}
if (Storage::disk($this->disk)->exists($croppedPath)) {
Storage::disk($this->disk)->delete($croppedPath);
}
collect(Storage::disk($this->disk)->files($this->getStrategy()->publicPath($filename)))->filter(function($file) use ($filename) {
return preg_match($this->getStrategy()->versionRegex($filename), pathinfo($file, PATHINFO_BASENAME));
})->each(function($file) {
Storage::disk($this->disk)->delete($file);
});
Storage::disk($this->disk)->delete($sourcePath);
2020-10-25 20:53:10 +01:00
}
private function storage() {
return Storage::disk($this->disk);
}
private function transformFileName($path, $basename) {
if (count(glob($this->storage()->path($path).'/'.$basename.'*')) == 0) {
return $basename;
}
$i = 1;
while(count(glob($this->storage()->path($path).'/'.$basename.'-'.$i.'*')) != 0) {
$i++;
}
return $basename.'-'.$i;
}
private function originalExtension() {
return $this->file->getClientOriginalExtension();
}
private function getStrategy() {
return app($this->strategy);
}
}