1
0
cms11/app/View/Components/BaseMediaComponent.php

70 lines
2.0 KiB
PHP
Raw Normal View History

<?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);
$variantUrl = $this->variant ? $this->copyFile($this->variant) : 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(array $data)
{
$path = $data['filename'];
$checksum = $data['checksum'];
$targetPath = $this->buildTargetFilePath($path, $checksum);
if (!Storage::disk('public')->exists($targetPath)) {
$content = Storage::disk(env('CONTENT_DISK'))->get($path);
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 $checksum)
{
$extension = pathinfo($originalPath, PATHINFO_EXTENSION);
$pathParts = str_split($checksum, 4);
$pathParts[] = sprintf('%s.%s', $checksum, $extension);
$targetPath = implode('/', $pathParts);
return $targetPath;
}
}