Skip to content

Commit

Permalink
MOL-1297: Fix payment method cache in production
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitalij Mik committed Feb 15, 2024
1 parent 1914194 commit c6598c6
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Resources/config/services/subscriber.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,12 @@
<argument type="service" id="mollie_payments.logger"/>
<tag name="kernel.event_subscriber"/>
</service>

<service id="Kiener\MolliePayments\Subscriber\PaymentMethodRouteCacheKeySubscriber">
<argument type="service" id="Shopware\Core\Checkout\Cart\SalesChannel\CartService"/>
<tag name="kernel.event_subscriber"/>
</service>


</services>
</container>
60 changes: 60 additions & 0 deletions src/Subscriber/PaymentMethodRouteCacheKeySubscriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);

namespace Kiener\MolliePayments\Subscriber;

use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Core\Checkout\Payment\Event\PaymentMethodRouteCacheKeyEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class PaymentMethodRouteCacheKeySubscriber implements EventSubscriberInterface
{
/**
* @var CartService
*/
private $cartService;

public function __construct(CartService $cartService)
{
$this->cartService = $cartService;
}

public static function getSubscribedEvents(): array
{
return [
PaymentMethodRouteCacheKeyEvent::class => 'onInvalidateCache'
];
}

/**
* shopware caches the payment methods only based on criteria. we add the cart price, currency and billing address id
* @param PaymentMethodRouteCacheKeyEvent $event
* @return void
*/
public function onInvalidateCache(PaymentMethodRouteCacheKeyEvent $event)
{
$context = $event->getContext();

$customer = $context->getCustomer();
if ($customer === null) {
return;
}
$billingAddress = $customer->getActiveBillingAddress();
$billingAddressId = '';
if ($billingAddress !== null) {
$billingAddressId = $billingAddress->getId();
}

$cart = $this->cartService->getCart($context->getToken(), $context);

$cacheParts = $event->getParts();

$cacheParts[] = md5(implode([
$cart->getPrice()->getTotalPrice(),
$context->getCurrency()->getIsoCode(),
$billingAddressId
]));

$event->setParts($cacheParts);
}
}

0 comments on commit c6598c6

Please sign in to comment.