<?php
namespace App\Action\PressSite\Download;
use App\Action\PressSite\DomainAwareAction;
use App\Enum\PressSite\DomainLanguageEnum;
use App\Service\PressSite\DomainAwareManager;
use App\Service\PressSite\Download\VET\TableHelper;
use App\Util\MappingConstants;
use Sonata\Exporter\Writer\XlsWriter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Twig\Environment;
/**
* Responsible for downloading the VET items table for given product.
*/
class ProductTitlesAction extends DomainAwareAction
{
/**
* The custom helper service responsible for providing the data to export.
*
* @var \App\Service\PressSite\Download\VET\TableHelper
*/
private $downloadHelper;
public function __construct(
Environment $twig,
DomainAwareManager $domainAwareManager,
TableHelper $downloadHelper
) {
parent::__construct($twig, $domainAwareManager);
$this->downloadHelper = $downloadHelper;
}
/**
* Responsible for formatting the data for downloading the VET items.
*
* @param int $id
* The ID of the currently rendered product
*
* @return \Symfony\Component\HttpFoundation\Response
* The generated response object
*/
public function __invoke(int $id): Response
{
$currentSite = $this->getDomainManager()->getCurrentByHostnameAndLocale();
$locale = $currentSite->isBroadcastType()
? DomainLanguageEnum::DANISH
: $currentSite->getLanguageCode();
$data = $this->downloadHelper
->setProductId($id)
->setDomainId($currentSite->getId())
->setIsBroadcastSite($currentSite->isBroadcastType())
->setTitleLanguageCode(MappingConstants::getAlpha3CodeFromVodTitleLanguage($locale))
->getExportData()
;
$response = new StreamedResponse();
$response->setCallback(function () use ($data) {
$writer = new XlsWriter('php://output', false);
$writer->open();
$writer->write($data['headers']);
foreach ($data['collection'] as $row) {
$writer->write($row);
}
$writer->close();
});
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
"{$id}_table.xls"
));
return $response;
}
}