View source
<?php
namespace Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow;
use Drupal\commerce\AjaxFormTrait;
use Drupal\commerce\Response\NeedsRedirectException;
use Drupal\commerce_checkout\Event\CheckoutEvents;
use Drupal\commerce_order\Event\OrderEvent;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
abstract class CheckoutFlowBase extends PluginBase implements CheckoutFlowInterface, ContainerFactoryPluginInterface {
use AjaxFormTrait;
protected $entityTypeManager;
protected $eventDispatcher;
protected $order;
protected $parentEntity;
protected $visibleSteps = [];
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EventDispatcherInterface $event_dispatcher, RouteMatchInterface $route_match) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->eventDispatcher = $event_dispatcher;
$this->order = $route_match
->getParameter('commerce_order');
if (array_key_exists('_entity', $configuration)) {
$this->parentEntity = $configuration['_entity'];
unset($configuration['_entity']);
}
$this
->setConfiguration($configuration);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('event_dispatcher'), $container
->get('current_route_match'));
}
public function __sleep() {
if (!empty($this->parentEntity)) {
$this->_parentEntityId = $this->parentEntity
->id();
unset($this->parentEntity);
}
if (!empty($this->order)) {
$this->_orderId = $this->order
->id();
unset($this->order);
}
return parent::__sleep();
}
public function __wakeup() {
parent::__wakeup();
if (!empty($this->_parentEntityId)) {
$checkout_flow_storage = $this->entityTypeManager
->getStorage('commerce_checkout_flow');
$this->parentEntity = $checkout_flow_storage
->load($this->_parentEntityId);
unset($this->_parentEntityId);
}
if (!empty($this->_orderId)) {
$order_storage = $this->entityTypeManager
->getStorage('commerce_order');
$this->order = $order_storage
->load($this->_orderId);
unset($this->_orderId);
}
}
public function getOrder() {
return $this->order;
}
public function getPreviousStepId($step_id) {
$step_ids = array_keys($this
->getSteps());
$previous_step_index = array_search($step_id, $step_ids) - 1;
while (isset($step_ids[$previous_step_index])) {
if (!$this
->isStepVisible($step_ids[$previous_step_index])) {
$previous_step_index--;
continue;
}
return $step_ids[$previous_step_index];
}
return NULL;
}
public function getNextStepId($step_id) {
$step_ids = array_keys($this
->getSteps());
$next_step_index = array_search($step_id, $step_ids) + 1;
while (isset($step_ids[$next_step_index])) {
if (!$this
->isStepVisible($step_ids[$next_step_index])) {
$next_step_index++;
continue;
}
return $step_ids[$next_step_index];
}
return NULL;
}
public function redirectToStep($step_id) {
if (!$this
->isStepVisible($step_id)) {
throw new \InvalidArgumentException(sprintf('Invalid step ID "%s" passed to redirectToStep().', $step_id));
}
$this->order
->set('checkout_step', $step_id);
$this
->onStepChange($step_id);
$this->order
->save();
throw new NeedsRedirectException(Url::fromRoute('commerce_checkout.form', [
'commerce_order' => $this->order
->id(),
'step' => $step_id,
])
->toString());
}
public function getSteps() {
return [
'payment' => [
'label' => $this
->t('Payment'),
'next_label' => $this
->t('Pay and complete purchase'),
'has_sidebar' => FALSE,
'hidden' => TRUE,
],
'complete' => [
'label' => $this
->t('Complete'),
'next_label' => $this
->t('Complete checkout'),
'has_sidebar' => FALSE,
],
];
}
public function getVisibleSteps() {
if (empty($this->visibleSteps)) {
$steps = $this
->getSteps();
foreach ($steps as $step_id => $step) {
if (!$this
->isStepVisible($step_id)) {
unset($steps[$step_id]);
}
}
$this->visibleSteps = $steps;
}
return $this->visibleSteps;
}
protected function isStepVisible($step_id) {
$step_ids = array_keys($this
->getSteps());
return in_array($step_id, $step_ids);
}
public function calculateDependencies() {
return [];
}
public function getConfiguration() {
return $this->configuration;
}
public function setConfiguration(array $configuration) {
$this->configuration = NestedArray::mergeDeep($this
->defaultConfiguration(), $configuration);
}
public function defaultConfiguration() {
return [
'display_checkout_progress' => TRUE,
'display_checkout_progress_breadcrumb_links' => FALSE,
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['display_checkout_progress'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Display checkout progress'),
'#description' => $this
->t('Used by the checkout progress block to determine visibility.'),
'#default_value' => $this->configuration['display_checkout_progress'],
];
$form['display_checkout_progress_breadcrumb_links'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Display checkout progress breadcrumb as links'),
'#description' => $this
->t('Let the checkout progress block render the breadcrumb as links.'),
'#default_value' => $this->configuration['display_checkout_progress_breadcrumb_links'],
];
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
if (!$form_state
->getErrors()) {
$values = $form_state
->getValue($form['#parents']);
$this->configuration = [];
$this->configuration['display_checkout_progress'] = $values['display_checkout_progress'];
$this->configuration['display_checkout_progress_breadcrumb_links'] = $values['display_checkout_progress_breadcrumb_links'];
}
}
public function getBaseFormId() {
return 'commerce_checkout_flow';
}
public function getFormId() {
return 'commerce_checkout_flow_' . $this->pluginId;
}
public function buildForm(array $form, FormStateInterface $form_state, $step_id = NULL) {
if (empty($step_id)) {
throw new \InvalidArgumentException('The $step_id cannot be empty.');
}
if ($form_state
->isRebuilding()) {
$order_storage = $this->entityTypeManager
->getStorage('commerce_order');
$this->order = $order_storage
->load($this->order
->id());
}
$steps = $this
->getSteps();
$form['#tree'] = TRUE;
$form['#step_id'] = $step_id;
$form['#title'] = $steps[$step_id]['label'];
$form['#theme'] = [
'commerce_checkout_form',
];
$form['#attached']['library'][] = 'commerce_checkout/form';
$form['#id'] = Html::getId($form_state
->getBuildInfo()['form_id']);
if ($this
->hasSidebar($step_id)) {
$form['sidebar']['order_summary'] = [
'#theme' => 'commerce_checkout_order_summary',
'#order_entity' => $this->order,
'#checkout_step' => $step_id,
];
}
$form['actions'] = $this
->actions($form, $form_state);
CacheableMetadata::createFromRenderArray($form)
->addCacheableDependency($this->parentEntity)
->addCacheableDependency($this->order)
->applyTo($form);
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($next_step_id = $this
->getNextStepId($form['#step_id'])) {
$this->order
->set('checkout_step', $next_step_id);
$this
->onStepChange($next_step_id);
$form_state
->setRedirect('commerce_checkout.form', [
'commerce_order' => $this->order
->id(),
'step' => $next_step_id,
]);
}
$this->order
->save();
}
protected function onStepChange($step_id) {
if ($step_id == 'payment') {
$this->order
->lock();
}
elseif ($step_id != 'payment') {
$this->order
->unlock();
}
if ($step_id == 'complete' && $this->order
->getState()
->getId() == 'draft') {
$event = new OrderEvent($this->order);
$this->eventDispatcher
->dispatch(CheckoutEvents::COMPLETION, $event);
$this->order
->getState()
->applyTransitionById('place');
}
}
protected function hasSidebar($step_id) {
$steps = $this
->getSteps();
return !empty($steps[$step_id]['has_sidebar']);
}
protected function actions(array $form, FormStateInterface $form_state) {
$steps = $this
->getSteps();
$next_step_id = $this
->getNextStepId($form['#step_id']);
$previous_step_id = $this
->getPreviousStepId($form['#step_id']);
$has_next_step = $next_step_id && isset($steps[$next_step_id]['next_label']);
$has_previous_step = $previous_step_id && isset($steps[$previous_step_id]['previous_label']);
$actions = [
'#type' => 'actions',
'#access' => $has_next_step,
];
if ($has_next_step) {
$actions['next'] = [
'#type' => 'submit',
'#value' => $steps[$next_step_id]['next_label'],
'#button_type' => 'primary',
'#submit' => [
'::submitForm',
],
];
if ($has_previous_step) {
$label = $steps[$previous_step_id]['previous_label'];
$options = [
'attributes' => [
'class' => [
'link--previous',
],
],
];
$actions['next']['#suffix'] = Link::createFromRoute($label, 'commerce_checkout.form', [
'commerce_order' => $this->order
->id(),
'step' => $previous_step_id,
], $options)
->toString();
}
}
return $actions;
}
}