OrderItemQuantity.php in Commerce Core 8.2
File
modules/promotion/src/Plugin/Commerce/Condition/OrderItemQuantity.php
View source
<?php
namespace Drupal\commerce_promotion\Plugin\Commerce\Condition;
use Drupal\commerce\ConditionGroup;
use Drupal\commerce\Plugin\Commerce\Condition\ConditionBase;
use Drupal\commerce\Plugin\Commerce\Condition\ParentEntityAwareInterface;
use Drupal\commerce\Plugin\Commerce\Condition\ParentEntityAwareTrait;
use Drupal\commerce_price\Calculator;
use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\OrderItemPromotionOfferInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
class OrderItemQuantity extends ConditionBase implements ParentEntityAwareInterface {
use ParentEntityAwareTrait;
public function defaultConfiguration() {
return [
'operator' => '>',
'quantity' => 1,
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['operator'] = [
'#type' => 'select',
'#title' => $this
->t('Operator'),
'#options' => $this
->getComparisonOperators(),
'#default_value' => $this->configuration['operator'],
'#required' => TRUE,
];
$form['quantity'] = [
'#type' => 'number',
'#title' => $this
->t('Quantity'),
'#default_value' => $this->configuration['quantity'],
'#min' => 1,
'#required' => TRUE,
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$values = $form_state
->getValue($form['#parents']);
$this->configuration['operator'] = $values['operator'];
$this->configuration['quantity'] = $values['quantity'];
}
public function evaluate(EntityInterface $entity) {
$this
->assertEntity($entity);
$order = $entity;
$promotion = $this->parentEntity;
$offer = $promotion
->getOffer();
$quantity = '0';
foreach ($order
->getItems() as $order_item) {
if ($offer instanceof OrderItemPromotionOfferInterface) {
$condition_group = new ConditionGroup($offer
->getConditions(), $offer
->getConditionOperator());
if (!$condition_group
->evaluate($order_item)) {
continue;
}
}
$quantity = Calculator::add($quantity, $order_item
->getQuantity());
}
switch ($this->configuration['operator']) {
case '>=':
return $quantity >= $this->configuration['quantity'];
case '>':
return $quantity > $this->configuration['quantity'];
case '<=':
return $quantity <= $this->configuration['quantity'];
case '<':
return $quantity < $this->configuration['quantity'];
case '==':
return $quantity == $this->configuration['quantity'];
default:
throw new \InvalidArgumentException("Invalid operator {$this->configuration['operator']}");
}
}
}