<?php declare(strict_types=1);
namespace ZweiPunktCurchod\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* class AddPdfInfosToView
*
* Determines the PDF information stored on the product
*/
class AddPdfInfosToView implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private EntityRepositoryInterface $mediaRepo;
/**
* @param EntityRepositoryInterface $mediaRepo
*/
public function __construct(
EntityRepositoryInterface $mediaRepo
) {
$this->mediaRepo = $mediaRepo;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductPageLoadedEvent'
];
}
/**
* @param ProductPageLoadedEvent $event
*
* Determines the PDF information stored on the product
* from the free text fields and passes it on to view
*/
public function onProductPageLoadedEvent(
ProductPageLoadedEvent $event
) {
// Determines the free text fields of the product
$customFields = $event->getPage()->getProduct()->getCustomFields();
// If there are no free text fields, nothing else needs to be done
if (empty($customFields)) {
return;
}
// Determines the pdf ids stored in the free text fields if any are available
$pdfFields = [];
foreach ($customFields as $index => $field) {
if (str_contains($index, 'custom_datenblatt_pdf_1')) {
$pdfFields[] = $field;
}
}
// If no Ids were found, it is not necessary to search for a media file.
if (empty($pdfFields)) {
return;
}
// The search criteria are set.
// All entries are to be determined whose id are contained in the pdfFields array.
$criteria = new Criteria();
$criteria->addFilter(
new EqualsAnyFilter('id', $pdfFields)
);
// The media information is searched
$medias = $this->mediaRepo->search($criteria, $event->getContext());
// If no media information is found,
// nothing needs to be passed to the view.
if (0 == $medias->getTotal()) {
return;
}
// The url and the name of the media are determined
$data = [];
foreach ($medias as $index => $media) {
$data[$index] = [
'url' => $media->getUrl(),
'name' => $media->getFileName()
];
}
// The required media data are passed to the view and can be found under page.pdfInformations
$event->getPage()->assign(['pdfInformations' => $data]);
}
}