Rabbi_Gerzi/backend/app/Element/UseCases/GetElementPdf/GetElementPdf.php

63 lines
1.7 KiB
PHP

<?php
namespace App\Element\UseCases\GetElementPdf;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
use App\Shared\Files\Filesystem;
class GetElementPdf
{
private const PDF_FOLDERS = ['short', 'long'];
private const PDF_MIME_TYPE = 'application/pdf';
public function __construct(private Filesystem $filesystem)
{
}
/**
* @throws BadRequestException
* @throws NotFoundException
*/
public function execute(GetElementPdfRequest $request): GetElementPdfResult
{
if ($request->folder === null) {
throw new BadRequestException('folder is required');
}
if ($request->fileName === null) {
throw new BadRequestException('fileName is required');
}
if (!$this->isAllowedPdfFolder($request->folder)) {
throw new NotFoundException('PDF not found');
}
if (!$this->isValidPdfFileName($request->fileName)) {
throw new NotFoundException('PDF not found');
}
$path = "element-pdfs/$request->folder/$request->fileName";
$contents = $this->filesystem->read($path);
if ($contents === null) {
throw new NotFoundException('PDF not found');
}
return new GetElementPdfResult(
contents: $contents,
fileName: $request->fileName,
mimeType: self::PDF_MIME_TYPE,
);
}
private function isAllowedPdfFolder(string $folder): bool
{
return in_array($folder, self::PDF_FOLDERS, true);
}
private function isValidPdfFileName(string $fileName): bool
{
return preg_match('/^[A-Za-z0-9._-]+\.pdf$/', $fileName) === 1;
}
}