ShipmentWeight.php in Commerce Shipping 8.2
File
src/Plugin/Commerce/Condition/ShipmentWeight.php
View source
<?php
namespace Drupal\commerce_shipping\Plugin\Commerce\Condition;
use Drupal\commerce\Plugin\Commerce\Condition\ConditionBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\physical\Weight;
use Drupal\physical\MeasurementType;
class ShipmentWeight extends ConditionBase {
public function defaultConfiguration() {
return [
'operator' => '>',
'weight' => NULL,
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$weight = $this->configuration['weight'];
$form['operator'] = [
'#type' => 'select',
'#title' => $this
->t('Operator'),
'#options' => $this
->getComparisonOperators(),
'#default_value' => $this->configuration['operator'],
'#required' => TRUE,
];
$form['weight'] = [
'#type' => 'physical_measurement',
'#measurement_type' => MeasurementType::WEIGHT,
'#title' => $this
->t('Weight'),
'#default_value' => $weight,
'#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['weight'] = $values['weight'];
}
public function evaluate(EntityInterface $entity) {
$this
->assertEntity($entity);
$shipment = $entity;
$weight = $shipment
->getWeight();
if (!$weight) {
return FALSE;
}
$condition_unit = $this->configuration['weight']['unit'];
$weight = $weight
->convert($condition_unit);
$condition_weight = new Weight($this->configuration['weight']['number'], $condition_unit);
switch ($this->configuration['operator']) {
case '>=':
return $weight
->greaterThanOrEqual($condition_weight);
case '>':
return $weight
->greaterThan($condition_weight);
case '<=':
return $weight
->lessThanOrEqual($condition_weight);
case '<':
return $weight
->lessThan($condition_weight);
case '==':
return $weight
->equals($condition_weight);
default:
throw new \InvalidArgumentException("Invalid operator {$this->configuration['operator']}");
}
}
}