You are here

trait SelectStoreTrait in Commerce Core 8.2

Provides a method for selecting the correct store for a purchasable entity.

Hierarchy

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_store
View 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

Namesort descending Modifiers Type Description Overrides
SelectStoreTrait::$currentStore protected property The current store. 1
SelectStoreTrait::selectStore protected function Selects the store for the given purchasable entity.