<?php
declare(strict_types=1);
namespace Fourtwosix\Attachments\Subscriber;
use Fourtwosix\Attachments\Core\Content\Product\AttachmentCollection;
use Fourtwosix\Attachments\Core\Content\Product\AttachmentEntity;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductDetailSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'filterAttachments',
];
}
public function filterAttachments(ProductPageLoadedEvent $event): void
{
$languageId = $event->getSalesChannelContext()->getLanguageId();
$customer = $event->getSalesChannelContext()->getCustomer();
$attachments = $event->getPage()->getProduct()->getExtensions()['attachments'];
$this->filterLanguage($attachments, $languageId);
if (empty($customer)) {
$this->filterPrivate($attachments);
}
}
private function filterPrivate(AttachmentCollection $attachments): void
{
/** @var AttachmentEntity $attachment */
foreach ($attachments as $key => $attachment) {
if ($attachment->isPrivate()) {
$attachments->remove($key);
}
}
}
private function filterLanguage(AttachmentCollection $attachments, string $languageId): void
{
/** @var AttachmentEntity $attachment */
foreach ($attachments as $key => $attachment) {
if (!array_key_exists($languageId, $attachment->getLanguages()->getIds())) {
$attachments->remove($key);
}
}
}
}