68 lines
1.9 KiB
PHP
68 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\View\Components;
|
|
|
|
use Closure;
|
|
use Illuminate\Contracts\View\View;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\View\Component;
|
|
|
|
abstract class BaseMediaComponent extends Component
|
|
{
|
|
protected string $view;
|
|
|
|
/**
|
|
* Create a new component instance.
|
|
*/
|
|
public function __construct(protected array $data, protected ?array $variant = [], protected ?array $options = [])
|
|
{
|
|
}
|
|
|
|
/**
|
|
* Get the view / contents that represent the component.
|
|
*/
|
|
public function render(): View|Closure|string
|
|
{
|
|
$originalUrl = $this->copyFile($this->data['filename']);
|
|
$variantUrl = $this->variant ? $this->copyFile($this->variant['filename']) : null;
|
|
|
|
return view($this->view, [
|
|
'originalUrl' => $originalUrl,
|
|
'variantUrl' => $variantUrl,
|
|
'originalData' => $this->data,
|
|
'variantData' => $this->variant,
|
|
'options' => $this->options,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Copy a file to public disk and return relative url to use
|
|
*/
|
|
protected function copyFile(string $path)
|
|
{
|
|
$content = Storage::disk(env('CONTENT_DISK'))->get($path);
|
|
$md5 = md5($content);
|
|
$targetPath = $this->buildTargetFilePath($path, $md5);
|
|
|
|
if (!Storage::disk('public')->exists($targetPath)) {
|
|
Storage::disk('public')->put($targetPath, $content);
|
|
}
|
|
|
|
return Str::remove(env('APP_URL'), Storage::disk('public')->url($targetPath));
|
|
}
|
|
|
|
/**
|
|
* Return a path for the target file
|
|
*/
|
|
protected function buildTargetFilePath(string $originalPath, string $md5)
|
|
{
|
|
$extension = pathinfo($originalPath, PATHINFO_EXTENSION);
|
|
$pathParts = str_split($md5, 4);
|
|
$pathParts[] = sprintf('%s.%s', $md5, $extension);
|
|
$targetPath = implode('/', $pathParts);
|
|
|
|
return $targetPath;
|
|
}
|
|
}
|