ShipmentAddress.php in Commerce Shipping 8.2
File
src/Plugin/Commerce/Condition/ShipmentAddress.php
View source
<?php
namespace Drupal\commerce_shipping\Plugin\Commerce\Condition;
use CommerceGuys\Addressing\Zone\Zone;
use Drupal\commerce\Plugin\Commerce\Condition\ConditionBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
class ShipmentAddress extends ConditionBase {
public function defaultConfiguration() {
return [
'zone' => NULL,
'negate' => NULL,
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['zone'] = [
'#type' => 'address_zone',
'#default_value' => $this->configuration['zone'],
'#required' => TRUE,
];
$form['negate'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Negate'),
'#description' => $this
->t('If checked, the value(s) selected should not match.'),
'#default_value' => $this->configuration['negate'],
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$values = $form_state
->getValue($form['#parents']);
foreach ($values['zone']['territories'] as &$territory) {
unset($territory['remove']);
}
unset($values['zone']['label']);
$this->configuration['zone'] = $values['zone'];
$this->configuration['negate'] = $values['negate'];
}
public function evaluate(EntityInterface $entity) {
$this
->assertEntity($entity);
$shipment = $entity;
$shipping_profile = $shipment
->getShippingProfile();
if (!$shipping_profile) {
return FALSE;
}
$address = $shipping_profile
->get('address')
->first();
if (!$address) {
return FALSE;
}
$zone = new Zone([
'id' => 'shipping',
'label' => 'N/A',
] + $this->configuration['zone']);
if ($this->configuration['negate']) {
return !$zone
->match($address);
}
return $zone
->match($address);
}
}