ShippingMethod.php 11.1 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\commerce_shipping\Entity;

5 6
use Drupal\commerce\ConditionGroup;
use Drupal\commerce\Plugin\Commerce\Condition\ConditionInterface;
7
use Drupal\commerce\Plugin\Commerce\Condition\ParentEntityAwareInterface;
8 9 10
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
11 12 13 14

/**
 * Defines the shipping method entity class.
 *
15
 * @ContentEntityType(
16 17
 *   id = "commerce_shipping_method",
 *   label = @Translation("Shipping method"),
18
 *   label_collection = @Translation("Shipping methods"),
19 20 21 22 23 24 25
 *   label_singular = @Translation("shipping method"),
 *   label_plural = @Translation("shipping methods"),
 *   label_count = @PluralTranslation(
 *     singular = "@count shipping method",
 *     plural = "@count shipping methods",
 *   ),
 *   handlers = {
26
 *     "storage" = "Drupal\commerce_shipping\ShippingMethodStorage",
bojanz's avatar
bojanz committed
27
 *     "access" = "Drupal\entity\EntityAccessControlHandler",
28
 *     "permission_provider" = "Drupal\entity\EntityPermissionProvider",
29 30
 *     "list_builder" = "Drupal\commerce_shipping\ShippingMethodListBuilder",
 *     "form" = {
31
 *       "default" = "Drupal\commerce_shipping\Form\ShippingMethodForm",
32 33
 *       "add" = "Drupal\commerce_shipping\Form\ShippingMethodForm",
 *       "edit" = "Drupal\commerce_shipping\Form\ShippingMethodForm",
34
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
35 36
 *     },
 *     "route_provider" = {
37
 *       "default" = "Drupal\entity\Routing\AdminHtmlRouteProvider",
38
 *     },
39
 *     "translation" = "Drupal\commerce_shipping\ShippingMethodTranslationHandler",
40
 *     "views_data" = "Drupal\commerce\CommerceEntityViewsData",
41
 *   },
42 43
 *   base_table = "commerce_shipping_method",
 *   data_table = "commerce_shipping_method_field_data",
44
 *   admin_permission = "administer commerce_shipping_method",
45
 *   translatable = TRUE,
46 47 48 49 50
 *   translation = {
 *     "content_translation" = {
 *       "access_callback" = "content_translation_translate_access"
 *     },
 *   },
51
 *   entity_keys = {
52 53 54
 *     "id" = "shipping_method_id",
 *     "label" = "name",
 *     "langcode" = "langcode",
55 56 57 58
 *     "uuid" = "uuid",
 *     "status" = "status",
 *   },
 *   links = {
59 60 61
 *     "add-form" = "/admin/commerce/shipping-methods/add",
 *     "edit-form" = "/admin/commerce/shipping-methods/manage/{commerce_shipping_method}",
 *     "delete-form" = "/admin/commerce/shipping-methods/manage/{commerce_shipping_method}/delete",
62 63 64 65 66
 *     "collection" =  "/admin/commerce/shipping-methods",
 *     "drupal:content-translation-overview" = "/admin/commerce/shipping-methods/manage/{commerce_shipping_method}/translations",
 *     "drupal:content-translation-add" = "/admin/commerce/shipping-methods/manage/{commerce_shipping_method}/translations/add/{source}/{target}",
 *     "drupal:content-translation-edit" = "/admin/commerce/shipping-methods/manage/{commerce_shipping_method}/translations/edit/{language}",
 *     "drupal:content-translation-delete" = "/admin/commerce/shipping-methods/manage/{commerce_shipping_method}/translations/delete/{language}",
67 68 69
 *   }
 * )
 */
70
class ShippingMethod extends ContentEntityBase implements ShippingMethodInterface {
71

72 73 74 75 76 77 78 79 80 81
  /**
   * {@inheritdoc}
   */
  public function toUrl($rel = 'canonical', array $options = []) {
    if ($rel == 'canonical') {
      $rel = 'edit-form';
    }
    return parent::toUrl($rel, $options);
  }

82
  /**
83
   * {@inheritdoc}
84
   */
85 86 87
  public function getStores() {
    return $this->get('stores')->referencedEntities();
  }
88 89

  /**
90
   * {@inheritdoc}
91
   */
92 93 94 95
  public function setStores(array $stores) {
    $this->set('stores', $stores);
    return $this;
  }
96 97

  /**
98
   * {@inheritdoc}
99
   */
100 101 102 103 104 105 106
  public function getStoreIds() {
    $store_ids = [];
    foreach ($this->get('stores') as $field_item) {
      $store_ids[] = $field_item->target_id;
    }
    return $store_ids;
  }
107 108

  /**
109
   * {@inheritdoc}
110
   */
111 112 113 114
  public function setStoreIds(array $store_ids) {
    $this->set('stores', $store_ids);
    return $this;
  }
115 116

  /**
117
   * {@inheritdoc}
118
   */
119
  public function getPlugin() {
120 121 122 123 124 125 126
    /** @var \Drupal\commerce\Plugin\Field\FieldType\PluginItemInterface $field_item */
    $field_item = $this->get('plugin')->first();
    /** @var \Drupal\commerce_shipping\Plugin\Commerce\ShippingMethod\ShippingMethodInterface $plugin */
    $plugin = $field_item->getTargetInstance();
    $plugin->setParentEntity($this);

    return $plugin;
127
  }
128 129 130 131

  /**
   * {@inheritdoc}
   */
132 133
  public function getName() {
    return $this->get('name')->value;
134 135 136 137 138
  }

  /**
   * {@inheritdoc}
   */
139 140 141
  public function setName($name) {
    $this->set('name', $name);
    return $this;
142 143
  }

144 145 146 147 148 149 150
  /**
   * {@inheritdoc}
   */
  public function getConditions() {
    $conditions = [];
    foreach ($this->get('conditions') as $field_item) {
      /** @var \Drupal\commerce\Plugin\Field\FieldType\PluginItemInterface $field_item */
151 152 153 154 155
      $condition = $field_item->getTargetInstance();
      if ($condition instanceof ParentEntityAwareInterface) {
        $condition->setParentEntity($this);
      }
      $conditions[] = $condition;
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    }
    return $conditions;
  }

  /**
   * {@inheritdoc}
   */
  public function setConditions(array $conditions) {
    $this->set('conditions', []);
    foreach ($conditions as $condition) {
      if ($condition instanceof ConditionInterface) {
        $this->get('conditions')->appendItem([
          'target_plugin_id' => $condition->getPluginId(),
          'target_plugin_configuration' => $condition->getConfiguration(),
        ]);
      }
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getConditionOperator() {
    return $this->get('condition_operator')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setConditionOperator($condition_operator) {
    $this->set('condition_operator', $condition_operator);
    return $this;
  }

191 192 193
  /**
   * {@inheritdoc}
   */
194 195
  public function getWeight() {
    return (int) $this->get('weight')->value;
196 197 198 199 200
  }

  /**
   * {@inheritdoc}
   */
201 202 203
  public function setWeight($weight) {
    $this->set('weight', $weight);
    return $this;
204 205 206 207 208
  }

  /**
   * {@inheritdoc}
   */
209 210
  public function isEnabled() {
    return (bool) $this->getEntityKey('status');
211 212 213 214 215
  }

  /**
   * {@inheritdoc}
   */
216 217 218
  public function setEnabled($enabled) {
    $this->set('status', (bool) $enabled);
    return $this;
219 220
  }

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  /**
   * {@inheritdoc}
   */
  public function applies(ShipmentInterface $shipment) {
    $conditions = $this->getConditions();
    if (!$conditions) {
      // Shipping methods without conditions always apply.
      return TRUE;
    }
    $order_conditions = array_filter($conditions, function ($condition) {
      /** @var \Drupal\commerce\Plugin\Commerce\Condition\ConditionInterface $condition */
      return $condition->getEntityTypeId() == 'commerce_order';
    });
    $shipment_conditions = array_filter($conditions, function ($condition) {
      /** @var \Drupal\commerce\Plugin\Commerce\Condition\ConditionInterface $condition */
      return $condition->getEntityTypeId() == 'commerce_shipment';
    });
    $order_conditions = new ConditionGroup($order_conditions, $this->getConditionOperator());
    $shipment_conditions = new ConditionGroup($shipment_conditions, $this->getConditionOperator());

    return $order_conditions->evaluate($shipment->getOrder()) && $shipment_conditions->evaluate($shipment);
  }

244
  /**
245
   * Helper callback for uasort() to sort shipping methods by weight and label.
246
   *
247 248 249 250
   * @param \Drupal\commerce_shipping\Entity\ShippingMethodInterface $a
   *   The first shipping method to sort.
   * @param \Drupal\commerce_shipping\Entity\ShippingMethodInterface $b
   *   The second shipping method to sort.
251
   *
252 253
   * @return int
   *   The comparison result for uasort().
254
   */
255 256 257 258 259 260 261
  public static function sort(ShippingMethodInterface $a, ShippingMethodInterface $b) {
    $a_weight = $a->getWeight();
    $b_weight = $b->getWeight();
    if ($a_weight == $b_weight) {
      $a_label = $a->label();
      $b_label = $b->label();
      return strnatcasecmp($a_label, $b_label);
262
    }
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    return ($a_weight < $b_weight) ? -1 : 1;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['stores'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Stores'))
      ->setDescription(t('The stores for which the shipping method is valid.'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_store')
      ->setSetting('handler', 'default')
      ->setDisplayOptions('form', [
        'type' => 'commerce_entity_select',
        'weight' => 0,
      ]);

    $fields['plugin'] = BaseFieldDefinition::create('commerce_plugin_item:commerce_shipping_method')
      ->setLabel(t('Plugin'))
      ->setCardinality(1)
      ->setRequired(TRUE)
288
      ->setTranslatable(TRUE)
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
      ->setDisplayOptions('form', [
        'type' => 'commerce_plugin_radios',
        'weight' => 1,
      ]);

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The shipping method name.'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    $fields['conditions'] = BaseFieldDefinition::create('commerce_plugin_item:commerce_condition')
      ->setLabel(t('Conditions'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setRequired(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'commerce_conditions',
        'weight' => 3,
        'settings' => [
          'entity_types' => ['commerce_order', 'commerce_shipment'],
        ],
      ]);

    $fields['condition_operator'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Condition operator'))
      ->setDescription(t('The condition operator.'))
      ->setRequired(TRUE)
      ->setSetting('allowed_values', [
        'AND' => t('All conditions must pass'),
        'OR' => t('Only one condition must pass'),
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => 4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDefaultValue('AND');

337 338 339 340
    $fields['weight'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Weight'))
      ->setDescription(t('The weight of this shipping method in relation to others.'))
      ->setDefaultValue(0)
341
      ->setDisplayOptions('view', [
342 343 344
        'label' => 'hidden',
        'type' => 'integer',
        'weight' => 0,
345 346
      ])
      ->setDisplayOptions('form', [
347
        'type' => 'hidden',
348
      ]);
349 350 351 352 353 354 355 356 357 358 359 360 361 362

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Enabled'))
      ->setDescription(t('Whether the shipping method is enabled.'))
      ->setDefaultValue(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 20,
      ]);

    return $fields;
363 364 365
  }

}