condition_plugins_commerce-8.x-1.x-dev/src/Plugin/Condition/OrderPaymentGateway.php
src/Plugin/Condition/OrderPaymentGateway.php
<?php namespace Drupal\condition_plugins_commerce\Plugin\Condition; use Drupal\condition_plugins_commerce\Plugin\ConditionBase; use Drupal\Core\Form\FormStateInterface; /** * Provides the payment gateway condition for orders. * * @Condition( * id = "condition_plugins_commerce_order_has_payment_gateway", * label = @Translation("Order has payment gateway"), * context_definitions = { * "commerce_order" = @ContextDefinition("entity:commerce_order", label = @Translation("Order")) * } * ) */ class OrderPaymentGateway extends ConditionBase { /** * {@inheritdoc} */ public function defaultConfiguration() { return [ 'payment_gateways' => [], ] + parent::defaultConfiguration(); } /** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form = parent::buildConfigurationForm($form, $form_state); $form['payment_gateways'] = [ '#type' => 'commerce_entity_select', '#title' => $this->t('Payment gateways'), '#default_value' => $this->configuration['payment_gateways'], '#target_type' => 'commerce_payment_gateway', '#hide_single_entity' => FALSE, '#multiple' => TRUE, ]; return $form; } /** * {@inheritdoc} */ public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { $values = $form_state->getValue($form['#parents']); if (is_array($values) && !empty($values['payment_gateways'])) { $this->configuration['payment_gateways'] = array_filter($values['payment_gateways']); parent::submitConfigurationForm($form, $form_state); } } /** * {@inheritdoc} */ public function summary() { $t_args = [ '@comparison' => !empty($this->configuration['status']) ? $this->t('Do not return') : $this->t('Return'), '@value' => empty($this->configuration['payment_gateways']) ? $this->t('empty') : implode(', ', $this->configuration['payment_gateways']), ]; return $this->t('@comparison true if payment gateway is @value.', $t_args); } /** * {@inheritdoc} */ public function evaluate() { /** @var \Drupal\commerce_order\Entity\OrderInterface $commerce_order */ $commerce_order = $this->getContextValue('commerce_order'); if ($commerce_order->get('payment_gateway')->isEmpty()) { // The payment gateway is not known yet, the condition cannot pass. return FALSE; } // Avoiding ->target_id to allow the condition to be unit tested, // because Prophecy doesn't support magic properties. $payment_gateway_item = $commerce_order->get('payment_gateway')->first()->getValue(); $payment_gateway_id = $payment_gateway_item['target_id']; return in_array($payment_gateway_id, $this->configuration['payment_gateways']); } }