custom/plugins/SwagPayPal/src/Checkout/ExpressCheckout/ExpressCheckoutSubscriber.php line 132

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. /*
  3.  * (c) shopware AG <info@shopware.com>
  4.  * For the full copyright and license information, please view the LICENSE
  5.  * file that was distributed with this source code.
  6.  */
  7. namespace Swag\PayPal\Checkout\ExpressCheckout;
  8. use Psr\Log\LoggerInterface;
  9. use Shopware\Core\Checkout\Customer\CustomerEvents;
  10. use Shopware\Core\Content\Cms\Events\CmsPageLoadedEvent;
  11. use Shopware\Core\Framework\Event\DataMappingEvent;
  12. use Shopware\Core\Framework\Struct\ArrayStruct;
  13. use Shopware\Core\Framework\Validation\BuildValidationEvent;
  14. use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntitySearchResultLoadedEvent;
  15. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  16. use Shopware\Core\System\SystemConfig\SystemConfigService;
  17. use Shopware\Storefront\Event\SwitchBuyBoxVariantEvent;
  18. use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoadedEvent;
  19. use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
  20. use Shopware\Storefront\Page\Checkout\Offcanvas\OffcanvasCartPageLoadedEvent;
  21. use Shopware\Storefront\Page\Checkout\Register\CheckoutRegisterPageLoadedEvent;
  22. use Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent;
  23. use Shopware\Storefront\Page\PageLoadedEvent;
  24. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  25. use Shopware\Storefront\Page\Search\SearchPageLoadedEvent;
  26. use Shopware\Storefront\Pagelet\PageletLoadedEvent;
  27. use Shopware\Storefront\Pagelet\Wishlist\GuestWishlistPageletLoadedEvent;
  28. use Swag\CmsExtensions\Storefront\Pagelet\Quickview\QuickviewPageletLoadedEvent;
  29. use Swag\PayPal\Checkout\Cart\Service\ExcludedProductValidator;
  30. use Swag\PayPal\Checkout\ExpressCheckout\Service\ExpressCheckoutDataServiceInterface;
  31. use Swag\PayPal\Checkout\ExpressCheckout\Service\ExpressCustomerService;
  32. use Swag\PayPal\Checkout\Payment\PayPalPaymentHandler;
  33. use Swag\PayPal\Setting\Exception\PayPalSettingsInvalidException;
  34. use Swag\PayPal\Setting\Service\SettingsValidationServiceInterface;
  35. use Swag\PayPal\Setting\Settings;
  36. use Swag\PayPal\Util\PaymentMethodUtil;
  37. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  38. class ExpressCheckoutSubscriber implements EventSubscriberInterface
  39. {
  40.     public const PAYPAL_EXPRESS_CHECKOUT_BUTTON_DATA_EXTENSION_ID 'payPalEcsButtonData';
  41.     private ExpressCheckoutDataServiceInterface $expressCheckoutDataService;
  42.     private SettingsValidationServiceInterface $settingsValidationService;
  43.     private SystemConfigService $systemConfigService;
  44.     private PaymentMethodUtil $paymentMethodUtil;
  45.     private ExcludedProductValidator $excludedProductValidator;
  46.     private LoggerInterface $logger;
  47.     public function __construct(
  48.         ExpressCheckoutDataServiceInterface $service,
  49.         SettingsValidationServiceInterface $settingsValidationService,
  50.         SystemConfigService $systemConfigService,
  51.         PaymentMethodUtil $paymentMethodUtil,
  52.         ExcludedProductValidator $excludedProductValidator,
  53.         LoggerInterface $logger
  54.     ) {
  55.         $this->expressCheckoutDataService $service;
  56.         $this->settingsValidationService $settingsValidationService;
  57.         $this->systemConfigService $systemConfigService;
  58.         $this->paymentMethodUtil $paymentMethodUtil;
  59.         $this->excludedProductValidator $excludedProductValidator;
  60.         $this->logger $logger;
  61.     }
  62.     public static function getSubscribedEvents(): array
  63.     {
  64.         return [
  65.             CheckoutCartPageLoadedEvent::class => 'addExpressCheckoutDataToPage',
  66.             CheckoutRegisterPageLoadedEvent::class => 'addExpressCheckoutDataToPage',
  67.             NavigationPageLoadedEvent::class => 'addExpressCheckoutDataToPage',
  68.             OffcanvasCartPageLoadedEvent::class => 'addExpressCheckoutDataToPage',
  69.             ProductPageLoadedEvent::class => 'addExpressCheckoutDataToPage',
  70.             SearchPageLoadedEvent::class => 'addExpressCheckoutDataToPage',
  71.             'sales_channel.product.search.result.loaded' => 'addExcludedProductsToSearchResult',
  72.             QuickviewPageletLoadedEvent::class => 'addExpressCheckoutDataToPagelet',
  73.             GuestWishlistPageletLoadedEvent::class => 'addExpressCheckoutDataToPagelet',
  74.             SwitchBuyBoxVariantEvent::class => 'addExpressCheckoutDataToBuyBoxSwitch',
  75.             'framework.validation.address.create' => 'disableAddressValidation',
  76.             'framework.validation.customer.create' => 'disableCustomerValidation',
  77.             CheckoutConfirmPageLoadedEvent::class => 'onCheckoutConfirmLoaded',
  78.             CustomerEvents::MAPPING_REGISTER_CUSTOMER => 'addPayerIdToCustomer',
  79.         ];
  80.     }
  81.     /**
  82.      * @param CheckoutCartPageLoadedEvent|CheckoutRegisterPageLoadedEvent|NavigationPageLoadedEvent|OffcanvasCartPageLoadedEvent|ProductPageLoadedEvent|SearchPageLoadedEvent $event
  83.      */
  84.     public function addExpressCheckoutDataToPage(PageLoadedEvent $event): void
  85.     {
  86.         $addProductToCart $event instanceof ProductPageLoadedEvent
  87.             || $event instanceof NavigationPageLoadedEvent
  88.             || $event instanceof SearchPageLoadedEvent;
  89.         $expressCheckoutButtonData $this->getExpressCheckoutButtonData($event->getSalesChannelContext(), \get_class($event), $addProductToCart);
  90.         if ($expressCheckoutButtonData === null) {
  91.             return;
  92.         }
  93.         if ($event instanceof ProductPageLoadedEvent
  94.             && $this->excludedProductValidator->isProductExcluded($event->getPage()->getProduct(), $event->getSalesChannelContext())) {
  95.             return;
  96.         }
  97.         if (!$addProductToCart
  98.             && \method_exists($event->getPage(), 'getCart')
  99.             && $this->excludedProductValidator->cartContainsExcludedProduct($event->getPage()->getCart(), $event->getSalesChannelContext())) {
  100.             return;
  101.         }
  102.         $event->getPage()->addExtension(
  103.             self::PAYPAL_EXPRESS_CHECKOUT_BUTTON_DATA_EXTENSION_ID,
  104.             $expressCheckoutButtonData
  105.         );
  106.         $this->logger->debug('Added data to page {page}', ['page' => \get_class($event)]);
  107.     }
  108.     public function addExpressCheckoutDataToPagelet(PageletLoadedEvent $event): void
  109.     {
  110.         $expressCheckoutButtonData $this->getExpressCheckoutButtonData($event->getSalesChannelContext(), \get_class($event), true);
  111.         if ($expressCheckoutButtonData === null) {
  112.             return;
  113.         }
  114.         if ($event instanceof QuickviewPageletLoadedEvent
  115.             && $this->excludedProductValidator->isProductExcluded($event->getPagelet()->getProduct(), $event->getSalesChannelContext())) {
  116.             return;
  117.         }
  118.         $event->getPagelet()->addExtension(
  119.             self::PAYPAL_EXPRESS_CHECKOUT_BUTTON_DATA_EXTENSION_ID,
  120.             $expressCheckoutButtonData
  121.         );
  122.     }
  123.     public function addExpressCheckoutDataToBuyBoxSwitch(SwitchBuyBoxVariantEvent $event): void
  124.     {
  125.         $salesChannelContext $event->getSalesChannelContext();
  126.         $expressCheckoutButtonData $this->getExpressCheckoutButtonData($salesChannelContext, \get_class($event), true);
  127.         if ($expressCheckoutButtonData === null) {
  128.             return;
  129.         }
  130.         $event->getProduct()->addExtension(
  131.             self::PAYPAL_EXPRESS_CHECKOUT_BUTTON_DATA_EXTENSION_ID,
  132.             $expressCheckoutButtonData
  133.         );
  134.     }
  135.     public function addExcludedProductsToSearchResult(SalesChannelEntitySearchResultLoadedEvent $event): void
  136.     {
  137.         if (!$this->checkSettings($event->getSalesChannelContext(), \get_class($event))) {
  138.             return;
  139.         }
  140.         $productIds = [];
  141.         foreach ($event->getResult()->getEntities() as $product) {
  142.             $productIds[] = $product->getId();
  143.             $productIds[] = $product->getParentId();
  144.         }
  145.         $excluded $this->excludedProductValidator->findExcludedProducts(\array_filter($productIds), $event->getSalesChannelContext());
  146.         foreach ($event->getResult()->getEntities() as $product) {
  147.             if (\in_array($product->getId(), $excludedtrue) || ($product->getParentId() && \in_array($product->getParentId(), $excludedtrue))) {
  148.                 $product->addExtension(ExcludedProductValidator::PRODUCT_EXCLUDED_FOR_PAYPAL, new ArrayStruct());
  149.             }
  150.         }
  151.     }
  152.     public function disableAddressValidation(BuildValidationEvent $event): void
  153.     {
  154.         if (!$event->getContext()->hasExtension(ExpressCustomerService::EXPRESS_CHECKOUT_ACTIVE)) {
  155.             return;
  156.         }
  157.         $event->getDefinition()->set('additionalAddressLine1')
  158.                                ->set('additionalAddressLine2')
  159.                                ->set('phoneNumber');
  160.     }
  161.     public function disableCustomerValidation(BuildValidationEvent $event): void
  162.     {
  163.         if (!$event->getContext()->hasExtension(ExpressCustomerService::EXPRESS_CHECKOUT_ACTIVE)) {
  164.             return;
  165.         }
  166.         $event->getDefinition()->set('birthdayDay')
  167.                                ->set('birthdayMonth')
  168.                                ->set('birthdayYear');
  169.     }
  170.     public function addPayerIdToCustomer(DataMappingEvent $event): void
  171.     {
  172.         if (!$event->getContext()->hasExtension(ExpressCustomerService::EXPRESS_CHECKOUT_ACTIVE)) {
  173.             return;
  174.         }
  175.         $input $event->getInput();
  176.         $output $event->getOutput();
  177.         $output['customFields'][ExpressCustomerService::EXPRESS_PAYER_ID] = $input->get(ExpressCustomerService::EXPRESS_PAYER_ID);
  178.         $event->setOutput($output);
  179.     }
  180.     public function onCheckoutConfirmLoaded(CheckoutConfirmPageLoadedEvent $event): void
  181.     {
  182.         if ($event->getRequest()->query->has(PayPalPaymentHandler::PAYPAL_EXPRESS_CHECKOUT_ID) === false) {
  183.             return;
  184.         }
  185.         $confirmPage $event->getPage();
  186.         $payPalPaymentMethodId $this->paymentMethodUtil->getPayPalPaymentMethodId($event->getContext());
  187.         if ($payPalPaymentMethodId === null) {
  188.             return;
  189.         }
  190.         $paymentMethods $confirmPage->getPaymentMethods();
  191.         if ($paymentMethods->has($payPalPaymentMethodId) === false) {
  192.             return;
  193.         }
  194.         $filtered $paymentMethods->filterByProperty('id'$payPalPaymentMethodId);
  195.         $confirmPage->setPaymentMethods($filtered);
  196.         $this->logger->debug('Removed other payment methods from selection for Express Checkout');
  197.     }
  198.     private function getExpressCheckoutButtonData(
  199.         SalesChannelContext $salesChannelContext,
  200.         string $eventName,
  201.         bool $addProductToCart false
  202.     ): ?ExpressCheckoutButtonData {
  203.         if (!$this->checkSettings($salesChannelContext$eventName)) {
  204.             return null;
  205.         }
  206.         return $this->expressCheckoutDataService->buildExpressCheckoutButtonData(
  207.             $salesChannelContext,
  208.             $addProductToCart
  209.         );
  210.     }
  211.     private function checkSettings(SalesChannelContext $contextstring $eventName): bool
  212.     {
  213.         if ($this->paymentMethodUtil->isPaypalPaymentMethodInSalesChannel($context) === false) {
  214.             return false;
  215.         }
  216.         try {
  217.             $this->settingsValidationService->validate($context->getSalesChannelId());
  218.         } catch (PayPalSettingsInvalidException $e) {
  219.             return false;
  220.         }
  221.         if ($this->expressOptionForEventEnabled($context->getSalesChannelId(), $eventName) === false) {
  222.             return false;
  223.         }
  224.         return true;
  225.     }
  226.     private function expressOptionForEventEnabled(string $salesChannelIdstring $eventName): bool
  227.     {
  228.         switch ($eventName) {
  229.             case ProductPageLoadedEvent::class:
  230.             case QuickviewPageletLoadedEvent::class:
  231.                 return $this->systemConfigService->getBool(Settings::ECS_DETAIL_ENABLED$salesChannelId);
  232.             case OffcanvasCartPageLoadedEvent::class:
  233.                 return $this->systemConfigService->getBool(Settings::ECS_OFF_CANVAS_ENABLED$salesChannelId);
  234.             case CheckoutRegisterPageLoadedEvent::class:
  235.                 return $this->systemConfigService->getBool(Settings::ECS_LOGIN_ENABLED$salesChannelId);
  236.             case CheckoutCartPageLoadedEvent::class:
  237.                 return $this->systemConfigService->getBool(Settings::ECS_CART_ENABLED$salesChannelId);
  238.             case NavigationPageLoadedEvent::class:
  239.             case CmsPageLoadedEvent::class:
  240.             case SearchPageLoadedEvent::class:
  241.             case GuestWishlistPageletLoadedEvent::class:
  242.             case SwitchBuyBoxVariantEvent::class:
  243.             case SalesChannelEntitySearchResultLoadedEvent::class:
  244.                 return $this->systemConfigService->getBool(Settings::ECS_LISTING_ENABLED$salesChannelId);
  245.             default:
  246.                 return false;
  247.         }
  248.     }
  249. }