Commit f04be4d0 authored by cornifex's avatar cornifex Committed by bojanz

Issue #2827747 by cornifex: Refactor commerce_cart_commerce_order_presave()...

Issue #2827747 by cornifex: Refactor commerce_cart_commerce_order_presave() into a transition event subscriber
parent 6f44d942
......@@ -107,20 +107,6 @@ function commerce_cart_commerce_order_delete(OrderInterface $order) {
}
}
/**
* Implements hook_ENTITY_TYPE_update().
*/
function commerce_cart_commerce_order_presave(OrderInterface $order) {
if (!$order->isNew() && $order->cart->value == TRUE) {
$place_transition = $order->getState()->getWorkflow()->getTransition('place');
$from_states = $place_transition->getFromStates();
$to_state = $place_transition->getToState()->getId();
if (in_array($order->original->state->value, array_keys($from_states)) && $order->state->value == $to_state) {
\Drupal::service('commerce_cart.cart_provider')->finalizeCart($order, FALSE);
}
}
}
/**
* Implements hook_form_FORM_ID_alter() for 'entity_form_display_edit_form'.
*
......
......@@ -20,3 +20,9 @@ services:
commerce_cart.order_item_matcher:
class: Drupal\commerce_cart\OrderItemMatcher
arguments: ['@event_dispatcher']
commerce_cart.order_subscriber:
class: Drupal\commerce_cart\EventSubscriber\OrderEventSubscriber
arguments: ['@commerce_cart.cart_provider']
tags:
- { name: event_subscriber }
<?php
namespace Drupal\commerce_cart\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\commerce_cart\CartProviderInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
class OrderEventSubscriber implements EventSubscriberInterface {
/**
* The cart provider.
*
* @var \Drupal\commerce_cart\CartProviderInterface
*/
protected $cartProvider;
/**
* Constructs a new OrderEventSubscriber object.
*
* @param \Drupal\commerce_cart\CartProviderInterface $cart_provider
* The cart provider.
*/
public function __construct(CartProviderInterface $cart_provider) {
$this->cartProvider = $cart_provider;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = ['commerce_order.place.pre_transition' => 'finalizeCart'];
return $events;
}
/**
* Finalizes the cart when the order is placed.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The workflow transition event.
*/
public function finalizeCart(WorkflowTransitionEvent $event) {
$order = $event->getEntity();
if ($order->cart->value == TRUE) {
$this->cartProvider->finalizeCart($order, FALSE);
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment