trait SelectStoreTrait in Commerce Core 8.2
Provides a method for selecting the correct store for a purchasable entity.
Hierarchy
- trait \Drupal\commerce_store\SelectStoreTrait
2 files declare their use of SelectStoreTrait
- AddToCartForm.php in modules/
cart/ src/ Form/ AddToCartForm.php - PurchasedEntityAvailableConstraintValidator.php in modules/
order/ src/ Plugin/ Validation/ Constraint/ PurchasedEntityAvailableConstraintValidator.php
File
- modules/
store/ src/ SelectStoreTrait.php, line 10
Namespace
Drupal\commerce_storeView source
trait SelectStoreTrait {
/**
* The current store.
*
* @var \Drupal\commerce_store\CurrentStoreInterface
*/
protected $currentStore;
/**
* Selects the store for the given purchasable entity.
*
* If the entity is sold from one store, then that store is selected.
* If the entity is sold from multiple stores, and the current store is
* one of them, then that store is selected.
*
* @param \Drupal\commerce\PurchasableEntityInterface $entity
* The entity being added to cart.
*
* @throws \Exception
* When the entity can't be purchased from the current store.
*
* @return \Drupal\commerce_store\Entity\StoreInterface
* The selected store.
*/
protected function selectStore(PurchasableEntityInterface $entity) {
$stores = $entity
->getStores();
if (count($stores) === 1) {
$store = reset($stores);
}
elseif (count($stores) === 0) {
// Malformed entity.
throw new \Exception('The given entity is not assigned to any store.');
}
else {
$store = $this->currentStore
->getStore();
if (!in_array($store, $stores)) {
// Indicates that the site listings are not filtered properly.
throw new \Exception("The given entity can't be purchased from the current store.");
}
}
return $store;
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
SelectStoreTrait:: |
protected | property | The current store. | 1 |
SelectStoreTrait:: |
protected | function | Selects the store for the given purchasable entity. |