2024-04-20 23:27:47 +02:00
|
|
|
<?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.
|
|
|
|
*/
|
2024-04-23 22:57:09 +02:00
|
|
|
public function __construct(protected array $data, protected ?array $variant = [], protected ?array $options = [])
|
2024-04-20 23:27:47 +02:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the view / contents that represent the component.
|
|
|
|
*/
|
|
|
|
public function render(): View|Closure|string
|
|
|
|
{
|
2024-05-05 15:12:12 +02:00
|
|
|
$originalUrl = $this->copyFile($this->data);
|
|
|
|
$variantUrl = $this->variant ? $this->copyFile($this->variant) : null;
|
2024-04-20 23:27:47 +02:00
|
|
|
|
|
|
|
return view($this->view, [
|
|
|
|
'originalUrl' => $originalUrl,
|
|
|
|
'variantUrl' => $variantUrl,
|
|
|
|
'originalData' => $this->data,
|
|
|
|
'variantData' => $this->variant,
|
2024-04-23 22:57:09 +02:00
|
|
|
'options' => $this->options,
|
2024-04-20 23:27:47 +02:00
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Copy a file to public disk and return relative url to use
|
|
|
|
*/
|
2024-05-05 15:12:12 +02:00
|
|
|
protected function copyFile(array $data)
|
2024-04-20 23:27:47 +02:00
|
|
|
{
|
2024-05-05 15:12:12 +02:00
|
|
|
$path = $data['filename'];
|
|
|
|
$checksum = $data['checksum'];
|
|
|
|
$targetPath = $this->buildTargetFilePath($path, $checksum);
|
2024-04-20 23:27:47 +02:00
|
|
|
|
|
|
|
if (!Storage::disk('public')->exists($targetPath)) {
|
2024-05-05 15:12:12 +02:00
|
|
|
$content = Storage::disk(env('CONTENT_DISK'))->get($path);
|
|
|
|
|
2024-04-20 23:27:47 +02:00
|
|
|
Storage::disk('public')->put($targetPath, $content);
|
|
|
|
}
|
|
|
|
|
|
|
|
return Str::remove(env('APP_URL'), Storage::disk('public')->url($targetPath));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return a path for the target file
|
|
|
|
*/
|
2024-05-05 15:12:12 +02:00
|
|
|
protected function buildTargetFilePath(string $originalPath, string $checksum)
|
2024-04-20 23:27:47 +02:00
|
|
|
{
|
|
|
|
$extension = pathinfo($originalPath, PATHINFO_EXTENSION);
|
2024-05-05 15:12:12 +02:00
|
|
|
$pathParts = str_split($checksum, 4);
|
|
|
|
$pathParts[] = sprintf('%s.%s', $checksum, $extension);
|
2024-04-20 23:27:47 +02:00
|
|
|
$targetPath = implode('/', $pathParts);
|
|
|
|
|
|
|
|
return $targetPath;
|
|
|
|
}
|
|
|
|
}
|