Files
myep/src/Controller/Booking/DownloadController.php
T

92 lines
2.7 KiB
PHP

<?php
namespace App\Controller\Booking;
use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification;
use App\Entity\User;
use App\Security\Crypt;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use function Symfony\Component\String\u;
class DownloadController extends AbstractController
{
public function __construct(
private readonly ApiClient $apiClient,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger,
) {
}
#[Route(
path: '/bookings/{id}/documents',
name: 'app_booking_documents',
requirements: ['id' => '\d+'],
defaults: ['fileType' => 'documents']
)]
#[Route(
path: '/bookings/{id}/invoice',
name: 'app_booking_invoice',
requirements: ['id' => '\d+'],
defaults: ['fileType' => 'invoice']
)]
#[IsGranted('ROLE_USER')]
public function documents(int $id, string $fileType): Response
{
/** @var User $user */
$user = $this->getUser();
$email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
$type = match ($fileType) {
'documents' => 'Dokumentdruck',
'invoice' => 'Vorgangdruck',
};
$this->logger->info('Initiated document download', [
'email' => $email,
'document_type' => $fileType,
'booking_id' => $id,
]);
try {
$file = $this
->apiClient
->getDocuments($email, $password, $id, $type);
} catch (ApiClientException $e) {
$file = null;
}
if (null === $file || $file instanceof Notification) {
$this->addFlash('error', 'Keine Dokumente vorhanden oder nicht abrufbar');
return $this->redirectToRoute('app_bookings');
}
$filename = u($file->filename)->ascii();
$response = new StreamedResponse(function () use ($file) {
echo $file->content;
});
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename,
md5($filename)
);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', $file->mimeType);
return $response;
}
}