|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpList\Core\Domain\Messaging\Service; |
| 6 | + |
| 7 | +use GuzzleHttp\Psr7\Utils; |
| 8 | +use PhpList\Core\Domain\Messaging\Exception\AttachmentFileNotFoundException; |
| 9 | +use PhpList\Core\Domain\Messaging\Model\Attachment; |
| 10 | +use PhpList\Core\Domain\Messaging\Model\Dto\DownloadableAttachment; |
| 11 | +use Psr\Http\Message\StreamInterface; |
| 12 | +use Symfony\Component\DependencyInjection\Attribute\Autowire; |
| 13 | +use Symfony\Component\Mime\MimeTypes; |
| 14 | + |
| 15 | +class AttachmentDownloadService |
| 16 | +{ |
| 17 | + public function __construct( |
| 18 | + #[Autowire('%phplist.attachment_repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', |
| 19 | + ) { |
| 20 | + } |
| 21 | + |
| 22 | + public function getDownloadable(Attachment $attachment): DownloadableAttachment |
| 23 | + { |
| 24 | + $filename = $attachment->getFilename(); |
| 25 | + if ($filename === null || $filename === '') { |
| 26 | + throw new AttachmentFileNotFoundException(); |
| 27 | + } |
| 28 | + |
| 29 | + $path = rtrim($this->attachmentRepositoryPath, '/'); |
| 30 | + $filePath = $path . '/' . $filename; |
| 31 | + |
| 32 | + if (!is_file($filePath) || !is_readable($filePath)) { |
| 33 | + throw new AttachmentFileNotFoundException(); |
| 34 | + } |
| 35 | + |
| 36 | + $mimeType = $attachment->getMimeType() |
| 37 | + ?? MimeTypes::getDefault()->guessMimeType($filePath) |
| 38 | + ?? 'application/octet-stream'; |
| 39 | + |
| 40 | + $size = filesize($filePath); |
| 41 | + $size = $size === false ? null : $size; |
| 42 | + |
| 43 | + /** @var StreamInterface $stream */ |
| 44 | + $stream = Utils::streamFor(Utils::tryFopen($filePath, 'rb')); |
| 45 | + |
| 46 | + return new DownloadableAttachment( |
| 47 | + filename: $filename, |
| 48 | + mimeType: $mimeType, |
| 49 | + size: $size, |
| 50 | + content: $stream, |
| 51 | + ); |
| 52 | + } |
| 53 | +} |
0 commit comments