89 lines
2.5 KiB
PHP
89 lines
2.5 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace Lucent\File;
|
||
|
|
|
||
|
|
use Exception;
|
||
|
|
use Illuminate\Log\Logger;
|
||
|
|
use Intervention\Image\ImageManager;
|
||
|
|
use Lucent\Channel\ChannelService;
|
||
|
|
use Lucent\Record\QueryRecord;
|
||
|
|
|
||
|
|
class ImageService
|
||
|
|
{
|
||
|
|
|
||
|
|
private string $notFoundImage = "/not-found.jpg";
|
||
|
|
|
||
|
|
public function __construct(
|
||
|
|
public ImageManager $imageManager,
|
||
|
|
public ChannelService $channelService,
|
||
|
|
public Logger $logger
|
||
|
|
)
|
||
|
|
{
|
||
|
|
}
|
||
|
|
|
||
|
|
public function file(?QueryRecord $record, string $template = ""): string
|
||
|
|
{
|
||
|
|
if (empty($record)) {
|
||
|
|
return $this->notFoundImage;
|
||
|
|
}
|
||
|
|
|
||
|
|
$originalPath = $record->_file->path;
|
||
|
|
$templateUri = $this->findTemplate($originalPath, $template);
|
||
|
|
|
||
|
|
if ($templateUri === false) {
|
||
|
|
$templateUri = $this->createTemplate($originalPath, $template);
|
||
|
|
}
|
||
|
|
return $this->channelService->channel->filesUrl . "/" . $templateUri;
|
||
|
|
}
|
||
|
|
|
||
|
|
private function findTemplate(string $originalPath, string $template): string|false
|
||
|
|
{
|
||
|
|
$templateUri = "templates/" . $template . "/" . $originalPath;
|
||
|
|
$templateFilePath = public_path("storage/" . $templateUri);
|
||
|
|
|
||
|
|
if (file_exists($templateFilePath)) {
|
||
|
|
return $templateUri;
|
||
|
|
}
|
||
|
|
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
private function createTemplate(string $originalPath, string $template): string
|
||
|
|
{
|
||
|
|
$originalFilePath = public_path("storage/" . $originalPath);
|
||
|
|
$templateUri = "/templates/" . $template . "/" . $originalPath;
|
||
|
|
$templateFilePath = public_path("storage/" . $templateUri);
|
||
|
|
if (!file_exists($originalFilePath)) {
|
||
|
|
return $this->notFoundImage;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!file_exists(pathinfo($templateFilePath, PATHINFO_DIRNAME))) {
|
||
|
|
$this->make_dir(pathinfo($templateFilePath, PATHINFO_DIRNAME));
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
$image = $this->imageManager->make($originalFilePath);
|
||
|
|
} catch (Exception $e) {
|
||
|
|
$this->logger->error($e->getMessage());
|
||
|
|
return $this->notFoundImage;
|
||
|
|
}
|
||
|
|
|
||
|
|
$image->filter(new $this->channelService->channel->imageFilters[$template]);
|
||
|
|
try {
|
||
|
|
$image->encode('webp', 75);
|
||
|
|
} catch (Exception $e) {
|
||
|
|
$this->logger->error($e->getMessage());
|
||
|
|
return $this->notFoundImage;
|
||
|
|
}
|
||
|
|
$image->save($templateFilePath);
|
||
|
|
return $templateUri;
|
||
|
|
}
|
||
|
|
|
||
|
|
private function make_dir(string $path): void
|
||
|
|
{
|
||
|
|
is_dir($path) || mkdir($path, 0777, true);
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
}
|