Files
lucent-laravel/src/File/ImageService.php
T

90 lines
2.5 KiB
PHP
Raw Normal View History

2023-10-02 23:10:49 +03:00
<?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;
}
2023-11-08 13:55:53 +02:00
$image = $image->filter(new $this->channelService->channel->imageFilters[$template]);
2023-10-02 23:10:49 +03:00
try {
2023-11-08 13:55:53 +02:00
$image = $this->imageManager->make((string)$image->encode('webp', 75));
2023-10-07 21:18:18 +03:00
$image->save($templateFilePath);
2023-10-02 23:10:49 +03:00
} catch (Exception $e) {
$this->logger->error($e->getMessage());
return $this->notFoundImage;
}
2023-10-07 21:18:18 +03:00
2023-10-02 23:10:49 +03:00
return $templateUri;
}
private function make_dir(string $path): void
{
is_dir($path) || mkdir($path, 0777, true);
}
}