custom/static-plugins/EfbStorefront/Subscriber/CustomerPriceSubscriber.php line 38

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Uandi\EFB\Storefront\Subscriber;
  3. use Shopware\Core\Content\Product\SalesChannel\Price\AbstractProductPriceCalculator;
  4. use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  7. use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Uandi\EFB\Storefront\Trait\LockExtensionTrait;
  10. use VioCustomerPrice\Event\CustomerPriceEvent;
  11. class CustomerPriceSubscriber implements EventSubscriberInterface
  12. {
  13.     use LockExtensionTrait;
  14.     private const LOCK self::class . '_lock';
  15.     private SalesChannelRepositoryInterface $productRepository;
  16.     private AbstractProductPriceCalculator $priceCalculator;
  17.     public function __construct(
  18.         SalesChannelRepositoryInterface $productRepository,
  19.         AbstractProductPriceCalculator $priceCalculator
  20.     ) {
  21.         $this->productRepository $productRepository;
  22.         $this->priceCalculator $priceCalculator;
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             CustomerPriceEvent::class => 'recalculateCheapestPrice',
  28.         ];
  29.     }
  30.     public function recalculateCheapestPrice(CustomerPriceEvent $event): void
  31.     {
  32.         $product $event->getProduct();
  33.         $context $event->getContext();
  34.         if ($this->locked($contextself::LOCK)) {
  35.             return;
  36.         }
  37.         if (null === $product->getParentId()) {
  38.             return;
  39.         }
  40.         $variants $this->productRepository->searchIds(
  41.             (new Criteria())->addFilter(new EqualsFilter('active'true))->addFilter(new EqualsFilter('parentId'$product->getParentId())),
  42.             $context
  43.         );
  44.         if ($variants->getTotal() <= 1) {
  45.             return;
  46.         }
  47.         $this->lock($contextself::LOCK);
  48.         $products $this->productRepository->search((new Criteria($variants->getIds()))->addFilter(new EqualsFilter('active'true)), $context);
  49.         $this->unlock($contextself::LOCK);
  50.         $products->sort(function (SalesChannelProductEntity $aSalesChannelProductEntity $b) {
  51.             return ($a->getCalculatedCheapestPrice()->getTotalPrice()
  52.                     - $b->getCalculatedCheapestPrice()->getTotalPrice())
  53.                 * 1000;
  54.         });
  55.         $product->setCalculatedCheapestPrice($products->first()->getCalculatedCheapestPrice());
  56.     }
  57. }