You are here

class BundlePriceResolver in Commerce Product Bundle 8

Commerce Product Bundle Price Resolver.

This checks if a product bundle entity has an own static price. Otherwise it calculates the bundle price from the referenced bundle items.

Hierarchy

Expanded class hierarchy of BundlePriceResolver

1 file declares its use of BundlePriceResolver
BundlePriceResolverTest.php in tests/src/Kernel/Resolver/BundlePriceResolverTest.php
1 string reference to 'BundlePriceResolver'
commerce_product_bundle.services.yml in ./commerce_product_bundle.services.yml
commerce_product_bundle.services.yml
1 service uses BundlePriceResolver
commerce_product_bundle.bundle_price_resolver in ./commerce_product_bundle.services.yml
Drupal\commerce_product_bundle\Resolver\BundlePriceResolver

File

src/Resolver/BundlePriceResolver.php, line 18

Namespace

Drupal\commerce_product_bundle\Resolver
View source
class BundlePriceResolver implements PriceResolverInterface {

  /**
   * The current store.
   *
   * @var \Drupal\commerce_store\CurrentStoreInterface
   */
  protected $currentStore;

  /**
   * Constructs a new BundlePriceResolver object.
   *
   * @param \Drupal\commerce_store\CurrentStoreInterface $current_store
   *   The current store.
   */
  public function __construct(CurrentStoreInterface $current_store) {
    $this->currentStore = $current_store;
  }

  /**
   * {@inheritdoc}
   */
  public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {

    // We operate on product bundles only. Return fast if we have nothing to do.
    if (!$entity instanceof BundleInterface) {
      return NULL;
    }

    // In case the product bundle has a static price, we return that price.
    // Otherwise we compute a dynamic price from the bundle items.
    $price = $entity
      ->getPrice();
    if (!is_null($price)) {
      return $price;
    }
    else {
      $currency_code = $this->currentStore
        ->getStore()
        ->getDefaultCurrencyCode();
      $bundle_price = new Price('0.00', $currency_code);
      foreach ($entity
        ->getBundleItems() as $item) {
        $bundle_price = $bundle_price
          ->add($item
          ->getUnitPrice());
      }
      return $bundle_price;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BundlePriceResolver::$currentStore protected property The current store.
BundlePriceResolver::resolve public function Resolves a price for the given purchasable entity. Overrides PriceResolverInterface::resolve
BundlePriceResolver::__construct public function Constructs a new BundlePriceResolver object.