ProductVariation.php 16.9 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\commerce_product\Entity;

5
use Drupal\commerce\Entity\CommerceContentEntityBase;
6
use Drupal\commerce\EntityHelper;
7
use Drupal\commerce\EntityOwnerTrait;
8
use Drupal\commerce_price\Price;
9
use Drupal\Core\Cache\Cache;
bojanz's avatar
bojanz committed
10
use Drupal\Core\Entity\EntityChangedTrait;
11
use Drupal\Core\Entity\EntityPublishedTrait;
12
use Drupal\Core\Entity\EntityStorageInterface;
13
use Drupal\Core\Entity\EntityTypeInterface;
14
use Drupal\Core\Field\BaseFieldDefinition;
15
use Drupal\Core\Url;
16
use Symfony\Component\Routing\Exception\RouteNotFoundException;
17 18

/**
bojanz's avatar
bojanz committed
19
 * Defines the product variation entity class.
20 21 22 23
 *
 * @ContentEntityType(
 *   id = "commerce_product_variation",
 *   label = @Translation("Product variation"),
24
 *   label_collection = @Translation("Product variations"),
25 26
 *   label_singular = @Translation("product variation"),
 *   label_plural = @Translation("product variations"),
27 28 29 30
 *   label_count = @PluralTranslation(
 *     singular = "@count product variation",
 *     plural = "@count product variations",
 *   ),
31
 *   bundle_label = @Translation("Product variation type"),
32
 *   handlers = {
33
 *     "event" = "Drupal\commerce_product\Event\ProductVariationEvent",
34
 *     "storage" = "Drupal\commerce_product\ProductVariationStorage",
35
 *     "storage_schema" = "Drupal\commerce\CommerceContentEntityStorageSchema",
bojanz's avatar
bojanz committed
36 37
 *     "access" = "Drupal\commerce_product\ProductVariationAccessControlHandler",
 *     "permission_provider" = "Drupal\commerce_product\ProductVariationPermissionProvider",
38
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
39
 *     "list_builder" = "Drupal\commerce_product\ProductVariationListBuilder",
40
 *     "views_data" = "Drupal\commerce_product\ProductVariationViewsData",
41
 *     "form" = {
42 43 44 45 46
 *       "add" = "Drupal\commerce_product\Form\ProductVariationForm",
 *       "edit" = "Drupal\commerce_product\Form\ProductVariationForm",
 *       "duplicate" = "Drupal\commerce_product\Form\ProductVariationForm",
 *       "delete" = "Drupal\commerce_product\Form\ProductVariationDeleteForm",
 *     },
47 48 49
 *     "local_task_provider" = {
 *       "default" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
 *     },
50 51
 *     "route_provider" = {
 *       "default" = "Drupal\commerce_product\ProductVariationRouteProvider",
52
 *     },
bojanz's avatar
bojanz committed
53
 *     "inline_form" = "Drupal\commerce_product\Form\ProductVariationInlineForm",
54 55
 *     "translation" = "Drupal\content_translation\ContentTranslationHandler"
 *   },
56
 *   admin_permission = "administer commerce_product",
57 58 59 60
 *   fieldable = TRUE,
 *   field_indexes = {
 *     "sku"
 *   },
61
 *   translatable = TRUE,
62 63 64 65 66
 *   translation = {
 *     "content_translation" = {
 *       "access_callback" = "content_translation_translate_access"
 *     },
 *   },
67 68 69 70
 *   base_table = "commerce_product_variation",
 *   data_table = "commerce_product_variation_field_data",
 *   entity_keys = {
 *     "id" = "variation_id",
71
 *     "bundle" = "type",
72 73
 *     "langcode" = "langcode",
 *     "uuid" = "uuid",
74
 *     "label" = "title",
75
 *     "published" = "status",
76 77
 *     "owner" = "uid",
 *     "uid" = "uid",
78
 *   },
79 80 81 82 83 84
 *   links = {
 *     "add-form" = "/product/{commerce_product}/variations/add",
 *     "edit-form" = "/product/{commerce_product}/variations/{commerce_product_variation}/edit",
 *     "duplicate-form" = "/product/{commerce_product}/variations/{commerce_product_variation}/duplicate",
 *     "delete-form" = "/product/{commerce_product}/variations/{commerce_product_variation}/delete",
 *     "collection" = "/product/{commerce_product}/variations",
85 86 87 88
 *     "drupal:content-translation-overview" = "/product/{commerce_product}/variations/{commerce_product_variation}/translations",
 *     "drupal:content-translation-add" = "/product/{commerce_product}/variations/{commerce_product_variation}/translations/add/{source}/{target}",
 *     "drupal:content-translation-edit" = "/product/{commerce_product}/variations/{commerce_product_variation}/translations/edit/{language}",
 *     "drupal:content-translation-delete" = "/product/{commerce_product}/variations/{commerce_product_variation}/translations/delete/{language}",
89
 *   },
90 91 92 93
 *   bundle_entity_type = "commerce_product_variation_type",
 *   field_ui_base_route = "entity.commerce_product_variation_type.edit_form",
 * )
 */
94
class ProductVariation extends CommerceContentEntityBase implements ProductVariationInterface {
95

bojanz's avatar
bojanz committed
96
  use EntityChangedTrait;
97
  use EntityOwnerTrait;
98
  use EntityPublishedTrait;
99

100 101 102 103 104 105 106 107 108
  /**
   * {@inheritdoc}
   */
  protected function urlRouteParameters($rel) {
    $uri_route_parameters = parent::urlRouteParameters($rel);
    $uri_route_parameters['commerce_product'] = $this->getProductId();
    return $uri_route_parameters;
  }

109 110 111 112
  /**
   * {@inheritdoc}
   */
  public function toUrl($rel = 'canonical', array $options = []) {
113 114 115 116 117 118 119
    // Product variation URLs depend on the parent product.
    if (!$this->getProductId()) {
      // RouteNotFoundException tells EntityBase::uriRelationships()
      // to skip this product variation's link relationships.
      throw new RouteNotFoundException();
    }

120 121
    // StringFormatter assumes 'revision' is always a valid link template.
    if (in_array($rel, ['canonical', 'revision'])) {
122 123 124 125
      $route_name = 'entity.commerce_product.canonical';
      $route_parameters = [
        'commerce_product' => $this->getProductId(),
      ];
126
      $options += [
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        '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);
    }
  }

142 143 144 145
  /**
   * {@inheritdoc}
   */
  public function getProduct() {
146
    return $this->getTranslatedReferencedEntity('product_id');
147 148 149 150 151 152 153 154 155
  }

  /**
   * {@inheritdoc}
   */
  public function getProductId() {
    return $this->get('product_id')->target_id;
  }

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  /**
   * {@inheritdoc}
   */
  public function getSku() {
    return $this->get('sku')->value;
  }

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

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

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

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
  /**
   * {@inheritdoc}
   */
  public function getListPrice() {
    if (!$this->get('list_price')->isEmpty()) {
      return $this->get('list_price')->first()->toPrice();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setListPrice(Price $list_price) {
    return $this->set('list_price', $list_price);
  }

bojanz's avatar
bojanz committed
202 203 204 205
  /**
   * {@inheritdoc}
   */
  public function getPrice() {
206 207 208
    if (!$this->get('price')->isEmpty()) {
      return $this->get('price')->first()->toPrice();
    }
bojanz's avatar
bojanz committed
209 210
  }

211 212 213 214 215 216 217 218
  /**
   * {@inheritdoc}
   */
  public function setPrice(Price $price) {
    $this->set('price', $price);
    return $this;
  }

219 220 221
  /**
   * {@inheritdoc}
   */
222
  public function isActive() {
223
    return (bool) $this->getEntityKey('published');
224 225 226 227 228
  }

  /**
   * {@inheritdoc}
   */
229
  public function setActive($active) {
230
    $this->set('status', (bool) $active);
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    return $this;
  }

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

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

249 250 251 252 253 254 255 256
  /**
   * {@inheritdoc}
   */
  public function getStores() {
    $product = $this->getProduct();
    return $product ? $product->getStores() : [];
  }

257 258 259
  /**
   * {@inheritdoc}
   */
260 261
  public function getOrderItemTypeId() {
    // The order item type is a bundle-level setting.
262
    $type_storage = $this->entityTypeManager()->getStorage('commerce_product_variation_type');
263
    $type_entity = $type_storage->load($this->bundle());
264

265
    return $type_entity->getOrderItemTypeId();
266 267
  }

bojanz's avatar
bojanz committed
268 269 270
  /**
   * {@inheritdoc}
   */
271
  public function getOrderItemTitle() {
272 273 274 275 276 277
    $label = $this->label();
    if (!$label) {
      $label = $this->generateTitle();
    }

    return $label;
bojanz's avatar
bojanz committed
278 279
  }

280 281 282 283 284 285 286 287 288
  /**
   * {@inheritdoc}
   */
  public 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');
  }

289 290 291
  /**
   * {@inheritdoc}
   */
292
  public function getAttributeValueIds() {
293
    $attribute_ids = [];
294 295
    foreach ($this->getAttributeFieldNames() as $field_name) {
      $field = $this->get($field_name);
296
      if (!$field->isEmpty()) {
297
        $attribute_ids[$field_name] = $field->target_id;
298 299 300 301 302 303 304 305 306
      }
    }

    return $attribute_ids;
  }

  /**
   * {@inheritdoc}
   */
307
  public function getAttributeValueId($field_name) {
308 309
    $attribute_field_names = $this->getAttributeFieldNames();
    if (!in_array($field_name, $attribute_field_names)) {
310 311 312 313 314 315
      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;
316 317
    }

318 319 320 321 322 323 324 325
    return $attribute_id;
  }

  /**
   * {@inheritdoc}
   */
  public function getAttributeValues() {
    $attribute_values = [];
326
    foreach ($this->getAttributeFieldNames() as $field_name) {
327
      $field = $this->get($field_name);
328
      if (!$field->isEmpty() && $field->entity) {
329 330 331 332
        $attribute_values[$field_name] = $field->entity;
      }
    }

333
    return $this->ensureTranslations($attribute_values);
334 335 336 337 338 339
  }

  /**
   * {@inheritdoc}
   */
  public function getAttributeValue($field_name) {
340 341
    $attribute_field_names = $this->getAttributeFieldNames();
    if (!in_array($field_name, $attribute_field_names)) {
342 343
      throw new \InvalidArgumentException(sprintf('Unknown attribute field name "%s".', $field_name));
    }
344
    $attribute_value = $this->getTranslatedReferencedEntity($field_name);
345
    return $attribute_value;
346 347
  }

348 349 350 351 352 353 354
  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['store']);
  }

355 356
  /**
   * {@inheritdoc}
357 358 359 360 361 362 363 364 365 366 367 368
   */
  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}
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
   */
  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);
    }
  }

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
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);

    // Ensure there's a reference on the parent product.
    $product = $this->getProduct();
    if ($product && !$product->hasVariation($this)) {
      $product->addVariation($this);
      $product->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage, $entities);

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface[] $entities */
    foreach ($entities as $variation) {
      // Remove the reference from the parent product.
      $product = $variation->getProduct();
      if ($product && $product->hasVariation($variation)) {
        $product->removeVariation($variation);
        $product->save();
      }
    }
  }

415 416 417 418 419 420 421
  /**
   * Generates the variation title based on attribute values.
   *
   * @return string
   *   The generated value.
   */
  protected function generateTitle() {
422 423 424 425 426 427
    if (!$this->getProductId()) {
      // Title generation is not possible before the parent product is known.
      return '';
    }

    $product_title = $this->getProduct()->getTitle();
428
    if ($attribute_values = $this->getAttributeValues()) {
429
      $attribute_labels = EntityHelper::extractLabels($attribute_values);
430
      $title = $product_title . ' - ' . implode(', ', $attribute_labels);
431 432 433
    }
    else {
      // When there are no attribute fields, there's only one variation.
434
      $title = $product_title;
435 436 437 438 439
    }

    return $title;
  }

440 441 442
  /**
   * {@inheritdoc}
   */
443
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
bojanz's avatar
bojanz committed
444
    $fields = parent::baseFieldDefinitions($entity_type);
445
    $fields += static::ownerBaseFieldDefinitions($entity_type);
446
    $fields += static::publishedBaseFieldDefinitions($entity_type);
447

448
    $fields['uid']
449 450 451
      ->setLabel(t('Author'))
      ->setDescription(t('The variation author.'))
      ->setDisplayConfigurable('form', TRUE);
452

453 454 455 456 457
    // 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')
458 459
      ->setReadOnly(TRUE)
      ->setDisplayConfigurable('view', TRUE);
460

461 462
    $fields['sku'] = BaseFieldDefinition::create('string')
      ->setLabel(t('SKU'))
463
      ->setDescription(t('The unique, machine-readable identifier for a variation.'))
464
      ->setRequired(TRUE)
465
      ->addConstraint('ProductVariationSku')
466
      ->setSetting('display_description', TRUE)
467 468 469 470 471 472 473
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t('The variation title.'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    $fields['list_price'] = BaseFieldDefinition::create('commerce_price')
      ->setLabel(t('List price'))
      ->setDescription(t('The list price.'))
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'commerce_price_default',
        'weight' => -1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'commerce_list_price',
        'weight' => -1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

505
    $fields['price'] = BaseFieldDefinition::create('commerce_price')
bojanz's avatar
bojanz committed
506
      ->setLabel(t('Price'))
507
      ->setDescription(t('The price'))
508
      ->setRequired(TRUE)
bojanz's avatar
bojanz committed
509 510
      ->setDisplayOptions('view', [
        'label' => 'above',
511
        'type' => 'commerce_price_default',
bojanz's avatar
bojanz committed
512 513 514
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
515
        'type' => 'commerce_price_default',
bojanz's avatar
bojanz committed
516 517 518 519
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
520

521 522
    $fields['status']
      ->setLabel(t('Published'))
523 524
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
525 526 527 528
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 90,
529
      ])
530 531 532 533
      ->setDisplayConfigurable('form', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
534
      ->setDescription(t('The time when the variation was created.'))
535 536 537 538 539
      ->setTranslatable(TRUE)
      ->setDisplayConfigurable('form', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
540
      ->setDescription(t('The time when the variation was last edited.'))
541 542 543 544 545
      ->setTranslatable(TRUE);

    return $fields;
  }

546 547 548 549 550 551
  /**
   * {@inheritdoc}
   */
  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = [];
552 553 554 555
    /** @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()) {
556 557 558
      // 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.
559
      $fields['title'] = clone $base_field_definitions['title'];
560 561 562 563 564 565 566
      $fields['title']->setRequired(FALSE);
      $fields['title']->setDisplayConfigurable('form', FALSE);
    }

    return $fields;
  }

567
}