53 lines
1.4 KiB
PHP
53 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Element\UseCases\GetElementPdf;
|
|
|
|
use App\Exceptions\NotFoundException;
|
|
use App\Shared\Files\StoredFileReader;
|
|
|
|
class GetElementPdf
|
|
{
|
|
private const PDF_FOLDERS = ['short', 'long'];
|
|
|
|
private const PDF_MIME_TYPE = 'application/pdf';
|
|
|
|
public function __construct(private StoredFileReader $storedFileReader)
|
|
{
|
|
}
|
|
|
|
/**
|
|
* @throws NotFoundException
|
|
*/
|
|
public function execute(GetElementPdfRequest $request): GetElementPdfResult
|
|
{
|
|
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->storedFileReader->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;
|
|
}
|
|
}
|