ShippingMethod.php 12.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
use Drupal\Core\Entity\ContentEntityBase;
9
use Drupal\Core\Entity\EntityChangedTrait;
10
11
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
12
13
14
15

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

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

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

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

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

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

  /**
119
   * {@inheritdoc}
120
   */
121
  public function getPlugin() {
122
123
124
125
126
127
128
    /** @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;
129
  }
130
131
132
133

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

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

146
147
148
149
150
151
152
  /**
   * {@inheritdoc}
   */
  public function getConditions() {
    $conditions = [];
    foreach ($this->get('conditions') as $field_item) {
      /** @var \Drupal\commerce\Plugin\Field\FieldType\PluginItemInterface $field_item */
153
154
155
156
157
      $condition = $field_item->getTargetInstance();
      if ($condition instanceof ParentEntityAwareInterface) {
        $condition->setParentEntity($this);
      }
      $conditions[] = $condition;
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
191
192
    }
    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;
  }

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

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

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

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

223
224
225
226
  /**
   * {@inheritdoc}
   */
  public function applies(ShipmentInterface $shipment) {
227
228
229
230
    // First, check if the shipping method applies for the given shipment.
    if ($this->getPlugin() && !$this->getPlugin()->applies($shipment)) {
      return FALSE;
    }
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    $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);
  }

250
  /**
251
   * Helper callback for uasort() to sort shipping methods by weight and label.
252
   *
253
254
255
256
   * @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.
257
   *
258
259
   * @return int
   *   The comparison result for uasort().
260
   */
261
262
263
264
265
266
267
  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);
268
    }
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    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)
294
      ->setTranslatable(TRUE)
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
      ->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);

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
    $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');

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

    $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,
      ]);

368
369
370
371
372
373
374
375
376
377
378
379
    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time when the shipping method was created.'))
      ->setTranslatable(TRUE)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time when the shipping method was last edited.'))
      ->setTranslatable(TRUE);

380
    return $fields;
381
382
  }

383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

398
}