SelectStoreTrait.php in Commerce Core 8.2
Namespace
Drupal\commerce_storeFile
modules/store/src/SelectStoreTrait.phpView source
<?php
namespace Drupal\commerce_store;
use Drupal\commerce\PurchasableEntityInterface;
/**
* Provides a method for selecting the correct store for a purchasable entity.
*/
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;
}
}
Traits
Name![]() |
Description |
---|---|
SelectStoreTrait | Provides a method for selecting the correct store for a purchasable entity. |