-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathProductVariation.php
More file actions
516 lines (459 loc) · 14.2 KB
/
ProductVariation.php
File metadata and controls
516 lines (459 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
<?php
namespace Drupal\commerce_product\Entity;
use Drupal\commerce\EntityHelper;
use Drupal\commerce_price\Price;
use Drupal\commerce_product\Event\ProductEvents;
use Drupal\commerce_product\Event\ProductVariationTitleGenerateEvent;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Url;
use Drupal\user\UserInterface;
/**
* Defines the product variation entity class.
*
* @ContentEntityType(
* id = "commerce_product_variation",
* label = @Translation("Product variation"),
* label_singular = @Translation("product variation"),
* label_plural = @Translation("product variations"),
* label_count = @PluralTranslation(
* singular = "@count product variation",
* plural = "@count product variations",
* ),
* bundle_label = @Translation("Product variation type"),
* handlers = {
* "event" = "Drupal\commerce_product\Event\ProductVariationEvent",
* "storage" = "Drupal\commerce_product\ProductVariationStorage",
* "access" = "Drupal\commerce\EmbeddedEntityAccessControlHandler",
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
* "views_data" = "Drupal\views\EntityViewsData",
* "form" = {
* "default" = "Drupal\Core\Entity\ContentEntityForm",
* },
* "inline_form" = "Drupal\commerce_product\Form\ProductVariationInlineForm",
* "translation" = "Drupal\content_translation\ContentTranslationHandler"
* },
* admin_permission = "administer commerce_product",
* fieldable = TRUE,
* translatable = TRUE,
* content_translation_ui_skip = TRUE,
* base_table = "commerce_product_variation",
* data_table = "commerce_product_variation_field_data",
* entity_keys = {
* "id" = "variation_id",
* "bundle" = "type",
* "langcode" = "langcode",
* "uuid" = "uuid",
* "label" = "title",
* "status" = "status",
* },
* bundle_entity_type = "commerce_product_variation_type",
* field_ui_base_route = "entity.commerce_product_variation_type.edit_form",
* )
*/
class ProductVariation extends ContentEntityBase implements ProductVariationInterface {
use EntityChangedTrait;
/**
* {@inheritdoc}
*/
public function toUrl($rel = 'canonical', array $options = []) {
// StringFormatter assumes 'revision' is always a valid link template.
if (in_array($rel, ['canonical', 'revision'])) {
$route_name = 'entity.commerce_product.canonical';
$route_parameters = [
'commerce_product' => $this->getProductId(),
];
$options = [
'query' => [
'v' => $this->id(),
],
'entity_type' => 'commerce_product',
'entity' => $this->getProduct(),
// Display links by default based on the current language.
'language' => $this->language(),
];
return new Url($route_name, $route_parameters, $options);
}
else {
return parent::toUrl($rel, $options);
}
}
/**
* {@inheritdoc}
*/
public function getProduct() {
return $this->get('product_id')->entity;
}
/**
* {@inheritdoc}
*/
public function getProductId() {
return $this->get('product_id')->target_id;
}
/**
* {@inheritdoc}
*/
public function getSku() {
return $this->get('sku')->value;
}
/**
* {@inheritdoc}
*/
public function setSku($sku) {
$this->set('sku', $sku);
return $this;
}
/**
* {@inheritdoc}
*/
public function getTitle() {
return $this->get('title')->value;
}
/**
* {@inheritdoc}
*/
public function setTitle($title) {
$this->set('title', $title);
return $this;
}
/**
* {@inheritdoc}
*/
public function getPrice() {
if (!$this->get('price')->isEmpty()) {
return $this->get('price')->first()->toPrice();
}
}
/**
* {@inheritdoc}
*/
public function setPrice(Price $price) {
$this->set('price', $price);
return $this;
}
/**
* {@inheritdoc}
*/
public function isActive() {
return (bool) $this->getEntityKey('status');
}
/**
* {@inheritdoc}
*/
public function setActive($active) {
$this->set('status', (bool) $active);
return $this;
}
/**
* {@inheritdoc}
*/
public function getCreatedTime() {
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function setCreatedTime($timestamp) {
$this->set('created', $timestamp);
return $this;
}
/**
* {@inheritdoc}
*/
public function getOwner() {
return $this->get('uid')->entity;
}
/**
* {@inheritdoc}
*/
public function setOwner(UserInterface $account) {
$this->set('uid', $account->id());
return $this;
}
/**
* {@inheritdoc}
*/
public function getOwnerId() {
return $this->get('uid')->target_id;
}
/**
* {@inheritdoc}
*/
public function setOwnerId($uid) {
$this->set('uid', $uid);
return $this;
}
/**
* {@inheritdoc}
*/
public function getStores() {
$product = $this->getProduct();
return $product ? $product->getStores() : [];
}
/**
* {@inheritdoc}
*/
public function getOrderItemTypeId() {
// The order item type is a bundle-level setting.
$type_storage = $this->entityTypeManager()->getStorage('commerce_product_variation_type');
$type_entity = $type_storage->load($this->bundle());
return $type_entity->getOrderItemTypeId();
}
/**
* {@inheritdoc}
*/
public function getOrderItemTitle() {
$label = $this->label();
if (!$label) {
$label = $this->generateTitle();
}
return $label;
}
/**
* {@inheritdoc}
*/
public function getAttributeValueIds() {
$attribute_ids = [];
foreach ($this->getAttributeFieldNames() as $field_name) {
$field = $this->get($field_name);
if (!$field->isEmpty()) {
$attribute_ids[$field_name] = $field->target_id;
}
}
return $attribute_ids;
}
/**
* {@inheritdoc}
*/
public function getAttributeValueId($field_name) {
$attribute_field_names = $this->getAttributeFieldNames();
if (!in_array($field_name, $attribute_field_names)) {
throw new \InvalidArgumentException(sprintf('Unknown attribute field name "%s".', $field_name));
}
$attribute_id = NULL;
$field = $this->get($field_name);
if (!$field->isEmpty()) {
$attribute_id = $field->target_id;
}
return $attribute_id;
}
/**
* {@inheritdoc}
*/
public function getAttributeValues() {
$attribute_values = [];
foreach ($this->getAttributeFieldNames() as $field_name) {
$field = $this->get($field_name);
if (!$field->isEmpty()) {
$attribute_values[$field_name] = $field->entity;
}
}
return $attribute_values;
}
/**
* {@inheritdoc}
*/
public function getAttributeValue($field_name) {
$attribute_field_names = $this->getAttributeFieldNames();
if (!in_array($field_name, $attribute_field_names)) {
throw new \InvalidArgumentException(sprintf('Unknown attribute field name "%s".', $field_name));
}
$attribute_value = NULL;
$field = $this->get($field_name);
if (!$field->isEmpty()) {
$attribute_value = $field->entity;
}
return $attribute_value;
}
/**
* Gets the names of the entity's attribute fields.
*
* @return string[]
* The attribute field names.
*/
protected function getAttributeFieldNames() {
$attribute_field_manager = \Drupal::service('commerce_product.attribute_field_manager');
$field_map = $attribute_field_manager->getFieldMap($this->bundle());
return array_column($field_map, 'field_name');
}
/**
* {@inheritdoc}
*/
public function getCacheTagsToInvalidate() {
$tags = parent::getCacheTagsToInvalidate();
// Invalidate the variations view builder and product caches.
return Cache::mergeTags($tags, [
'commerce_product:' . $this->getProductId(),
'commerce_product_variation_view',
]);
}
/**
* {@inheritdoc}
*/
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
/** @var \Drupal\commerce_product\Entity\ProductVariationTypeInterface $variation_type */
$variation_type = $this->entityTypeManager()
->getStorage('commerce_product_variation_type')
->load($this->bundle());
if ($variation_type->shouldGenerateTitle()) {
$title = $this->generateTitle();
$this->setTitle($title);
}
}
/**
* Generates the variation title based on attribute values.
*
* @return string
* The generated value.
*/
protected function generateTitle() {
if (!$this->getProductId()) {
// Title generation is not possible before the parent product is known.
return '';
}
$product_title = $this->getProduct()->getTitle();
if ($attribute_values = $this->getAttributeValues()) {
$attribute_labels = EntityHelper::extractLabels($attribute_values);
$title = $product_title . ' - ' . implode(', ', $attribute_labels);
}
else {
// When there are no attribute fields, there's only one variation.
$title = $product_title;
}
/** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher */
$event_dispatcher = \Drupal::service('event_dispatcher');
$event = new ProductVariationTitleGenerateEvent($title, $this);
$event_dispatcher->dispatch(ProductEvents::PRODUCT_VARIATION_TITLE_GENERATE, $event);
$title = $event->getTitle();
return $title;
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Author'))
->setDescription(t('The variation author.'))
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setDefaultValueCallback('Drupal\commerce_product\Entity\ProductVariation::getCurrentUserId')
->setTranslatable(TRUE)
->setDisplayConfigurable('form', TRUE);
// The product backreference, populated by Product::postSave().
$fields['product_id'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Product'))
->setDescription(t('The parent product.'))
->setSetting('target_type', 'commerce_product')
->setReadOnly(TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['sku'] = BaseFieldDefinition::create('string')
->setLabel(t('SKU'))
->setDescription(t('The unique, machine-readable identifier for a variation.'))
->setRequired(TRUE)
->addConstraint('ProductVariationSku')
->setSetting('display_description', TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -4,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -4,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['title'] = BaseFieldDefinition::create('string')
->setLabel(t('Title'))
->setDescription(t('The variation title.'))
->setRequired(TRUE)
->setTranslatable(TRUE)
->setSettings([
'default_value' => '',
'max_length' => 255,
])
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -5,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
// The price is not required because it's not guaranteed to be used
// for storage (there might be a price per currency, role, country, etc).
$fields['price'] = BaseFieldDefinition::create('commerce_price')
->setLabel(t('Price'))
->setDescription(t('The variation price'))
->setDisplayOptions('view', [
'label' => 'above',
'type' => 'commerce_price_default',
'weight' => 0,
])
->setDisplayOptions('form', [
'type' => 'commerce_price_default',
'weight' => 0,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['status'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Active'))
->setDescription(t('Whether the variation is active.'))
->setDefaultValue(TRUE)
->setTranslatable(TRUE)
->setDisplayOptions('form', [
'type' => 'boolean_checkbox',
'weight' => 99,
])
->setDisplayConfigurable('form', TRUE);
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Created'))
->setDescription(t('The time when the variation was created.'))
->setTranslatable(TRUE)
->setDisplayConfigurable('form', TRUE);
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setDescription(t('The time when the variation was last edited.'))
->setTranslatable(TRUE);
return $fields;
}
/**
* {@inheritdoc}
*/
public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
$fields = [];
/** @var \Drupal\commerce_product\Entity\ProductVariationTypeInterface $variation_type */
$variation_type = ProductVariationType::load($bundle);
// $variation_type could be NULL if the method is invoked during uninstall.
if ($variation_type && $variation_type->shouldGenerateTitle()) {
// The title is always generated, the field needs to be hidden.
// The widget is hidden in commerce_product_field_widget_form_alter()
// since setDisplayOptions() can't affect existing form displays.
$fields['title'] = clone $base_field_definitions['title'];
$fields['title']->setRequired(FALSE);
$fields['title']->setDisplayConfigurable('form', FALSE);
}
return $fields;
}
/**
* Default value callback for 'uid' base field definition.
*
* @see ::baseFieldDefinitions()
*
* @return array
* An array of default values.
*/
public static function getCurrentUserId() {
return [\Drupal::currentUser()->id()];
}
}