Skip to content

Commit

Permalink
Created price hook from a lineItem perspective
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Willem Rigters committed Sep 18, 2024
1 parent 02407fa commit c612554
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
14 changes: 14 additions & 0 deletions docs/dynamic-pricing.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,20 @@ SimpleCommerce::productVariantPriceHook(function (Order $order, Product $product
});
```

Another alternative method is available to calculate from a lineItem perspective.

```php
use DuncanMcClean\SimpleCommerce\Orders\LineItem;

SimpleCommerce::lineItemPriceHook(function (LineItem $lineItem) {
if ($lineItem->product()->get('sale')) {
return $lineItem->product()->get('price') * 0.9; // 10% discount
}

return $lineItem->product()->get('price');
});
```

:::note Note!
These methods will not make any change to the price displayed to customers or stored in your products. They're only used when 'calculating' line items (eg. when an item is added to the cart, quantity changed, etc).
:::
2 changes: 2 additions & 0 deletions src/Orders/Calculator/LineItemCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ public function handle(Order $order, Closure $next)
if ($product->purchasableType() === ProductType::Product) {
if (SimpleCommerce::$productPriceHook) {
$productPrice = (SimpleCommerce::$productPriceHook)($order, $product);
} elseif (SimpleCommerce::$lineItemPriceHook) {
$productPrice = (SimpleCommerce::$lineItemPriceHook)($lineItem);
} else {
$productPrice = $product->price();
}
Expand Down
9 changes: 9 additions & 0 deletions src/SimpleCommerce.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class SimpleCommerce

public static $productVariantPriceHook;

public static $lineItemPriceHook;

public static function version(): string
{
if (app()->environment('testing')) {
Expand Down Expand Up @@ -200,4 +202,11 @@ public static function productVariantPriceHook(Closure $callback): self

return new static;
}

public static function lineItemPriceHook(Closure $callback): self
{
static::$lineItemPriceHook = $callback;

return new static;
}
}

0 comments on commit c612554

Please sign in to comment.