<?php

namespace Drupal\commerce_store;

use Drupal\commerce\EntityHelper;
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();
      $store_ids = EntityHelper::extractIds($stores);
      if (!in_array($store->id(), $store_ids, TRUE)) {
        // Indicates that the site listings are not filtered properly.
        throw new \Exception("The given entity can't be purchased from the current store.");
      }
    }
    // @todo check if throwing an exception is the right thing to do and whether
    // we should improve the error message otherwise.
    if (!$store->isPublished()) {
      throw new \Exception("The given entity can't be purchased from the current store.");
    }

    return $store;
  }

}
