custom/plugins/fourtwosixattachments/src/Subscriber/ProductDetailSubscriber.php line 21

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Fourtwosix\Attachments\Subscriber;
  4. use Fourtwosix\Attachments\Core\Content\Product\AttachmentCollection;
  5. use Fourtwosix\Attachments\Core\Content\Product\AttachmentEntity;
  6. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class ProductDetailSubscriber implements EventSubscriberInterface
  9. {
  10.     public static function getSubscribedEvents(): array
  11.     {
  12.         return [
  13.             ProductPageLoadedEvent::class => 'filterAttachments',
  14.         ];
  15.     }
  16.     public function filterAttachments(ProductPageLoadedEvent $event): void
  17.     {
  18.         $languageId $event->getSalesChannelContext()->getLanguageId();
  19.         $customer $event->getSalesChannelContext()->getCustomer();
  20.         $attachments $event->getPage()->getProduct()->getExtensions()['attachments'];
  21.         $this->filterLanguage($attachments$languageId);
  22.         if (empty($customer)) {
  23.             $this->filterPrivate($attachments);
  24.         }
  25.     }
  26.     private function filterPrivate(AttachmentCollection $attachments): void
  27.     {
  28.         /** @var AttachmentEntity $attachment */
  29.         foreach ($attachments as $key => $attachment) {
  30.             if ($attachment->isPrivate()) {
  31.                 $attachments->remove($key);
  32.             }
  33.         }
  34.     }
  35.     private function filterLanguage(AttachmentCollection $attachmentsstring $languageId): void
  36.     {
  37.         /** @var AttachmentEntity $attachment */
  38.         foreach ($attachments as $key => $attachment) {
  39.             if (!array_key_exists($languageId$attachment->getLanguages()->getIds())) {
  40.                 $attachments->remove($key);
  41.             }
  42.         }
  43.     }
  44. }