View source
<?php
namespace Drupal\commerce_product\Entity;
use Drupal\commerce\Entity\CommerceContentEntityBase;
use Drupal\commerce\EntityHelper;
use Drupal\commerce\EntityOwnerTrait;
use Drupal\commerce_price\Price;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Url;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
class ProductVariation extends CommerceContentEntityBase implements ProductVariationInterface {
use EntityChangedTrait;
use EntityOwnerTrait;
use EntityPublishedTrait;
protected function urlRouteParameters($rel) {
$uri_route_parameters = parent::urlRouteParameters($rel);
$uri_route_parameters['commerce_product'] = $this
->getProductId();
return $uri_route_parameters;
}
public function toUrl($rel = 'canonical', array $options = []) {
if (!$this
->getProductId()) {
throw new RouteNotFoundException();
}
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(),
'language' => $this
->language(),
];
return new Url($route_name, $route_parameters, $options);
}
else {
return parent::toUrl($rel, $options);
}
}
public function getProduct() {
return $this
->getTranslatedReferencedEntity('product_id');
}
public function getProductId() {
return $this
->get('product_id')->target_id;
}
public function getSku() {
return $this
->get('sku')->value;
}
public function setSku($sku) {
$this
->set('sku', $sku);
return $this;
}
public function getTitle() {
return $this
->get('title')->value;
}
public function setTitle($title) {
$this
->set('title', $title);
return $this;
}
public function getListPrice() {
if (!$this
->get('list_price')
->isEmpty()) {
return $this
->get('list_price')
->first()
->toPrice();
}
}
public function setListPrice(Price $list_price) {
return $this
->set('list_price', $list_price);
}
public function getPrice() {
if (!$this
->get('price')
->isEmpty()) {
return $this
->get('price')
->first()
->toPrice();
}
}
public function setPrice(Price $price) {
$this
->set('price', $price);
return $this;
}
public function isActive() {
return (bool) $this
->getEntityKey('published');
}
public function setActive($active) {
$this
->set('status', (bool) $active);
return $this;
}
public function getCreatedTime() {
return $this
->get('created')->value;
}
public function setCreatedTime($timestamp) {
$this
->set('created', $timestamp);
return $this;
}
public function getStores() {
$product = $this
->getProduct();
return $product ? $product
->getStores() : [];
}
public function getOrderItemTypeId() {
$type_storage = $this
->entityTypeManager()
->getStorage('commerce_product_variation_type');
$type_entity = $type_storage
->load($this
->bundle());
return $type_entity
->getOrderItemTypeId();
}
public function getOrderItemTitle() {
$label = $this
->label();
if (!$label) {
$label = $this
->generateTitle();
}
return $label;
}
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');
}
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;
}
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;
}
public function getAttributeValues() {
$attribute_values = [];
foreach ($this
->getAttributeFieldNames() as $field_name) {
$field = $this
->get($field_name);
if (!$field
->isEmpty() && $field->entity) {
$attribute_values[$field_name] = $field->entity;
}
}
return $this
->ensureTranslations($attribute_values);
}
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 = $this
->getTranslatedReferencedEntity($field_name);
return $attribute_value;
}
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), [
'store',
]);
}
public function getCacheTagsToInvalidate() {
$tags = parent::getCacheTagsToInvalidate();
return Cache::mergeTags($tags, [
'commerce_product:' . $this
->getProductId(),
'commerce_product_variation_view',
]);
}
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
$variation_type = $this
->entityTypeManager()
->getStorage('commerce_product_variation_type')
->load($this
->bundle());
if ($variation_type
->shouldGenerateTitle()) {
$title = $this
->generateTitle();
$this
->setTitle($title);
}
}
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
$product = $this
->getProduct();
if ($product && !$product
->hasVariation($this)) {
$product
->addVariation($this);
$product
->save();
}
}
public static function postDelete(EntityStorageInterface $storage, array $entities) {
parent::postDelete($storage, $entities);
foreach ($entities as $variation) {
$product = $variation
->getProduct();
if ($product && $product
->hasVariation($variation)) {
$product
->removeVariation($variation);
$product
->save();
}
}
}
protected function generateTitle() {
if (!$this
->getProductId()) {
return '';
}
$product_title = $this
->getProduct()
->getTitle();
if ($attribute_values = $this
->getAttributeValues()) {
$attribute_labels = EntityHelper::extractLabels($attribute_values);
$title = $product_title . ' - ' . implode(', ', $attribute_labels);
}
else {
$title = $product_title;
}
return $title;
}
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::ownerBaseFieldDefinitions($entity_type);
$fields += static::publishedBaseFieldDefinitions($entity_type);
$fields['uid']
->setLabel(t('Author'))
->setDescription(t('The variation author.'))
->setDisplayConfigurable('form', TRUE);
$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('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('form', [
'type' => 'string_textfield',
'weight' => -5,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$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);
$fields['price'] = BaseFieldDefinition::create('commerce_price')
->setLabel(t('Price'))
->setDescription(t('The price'))
->setRequired(TRUE)
->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']
->setLabel(t('Published'))
->setDisplayOptions('form', [
'type' => 'boolean_checkbox',
'settings' => [
'display_label' => TRUE,
],
'weight' => 90,
])
->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;
}
public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
$fields = [];
$variation_type = ProductVariationType::load($bundle);
if ($variation_type && $variation_type
->shouldGenerateTitle()) {
$fields['title'] = clone $base_field_definitions['title'];
$fields['title']
->setRequired(FALSE);
$fields['title']
->setDisplayConfigurable('form', FALSE);
}
return $fields;
}
}