File: D:/HostingSpaces/SBogers10/farmfun.komma.pro/app/Komma/Shop/Stock/StockService.php
<?php
declare(strict_types=1);
namespace App\Komma\Shop\Stock;
use App\Komma\Shop\Products\Product\Product;
use App\Komma\Shop\Products\ProductableInterface;
use Illuminate\Support\Facades\Log;
/**
* Class StockService
*/
class StockService
{
/**
* Stock a productable. If the quantity is positive, that quantity will be added to the stock. Else it will be substracted from the stock.
*
* @param ProductableInterface $productable
* @param int $quantity
* @param bool $dontSave modify the products stock quantity, but dont save it yet when it is true. Otherwise always save it.
* @return ProductableInterface|void
*/
public function stockProductable(ProductableInterface $productable, int $quantity = 1, $dontSave = false)
{
switch (get_class($productable)) {
case Product::class:
/** @var Product $productable */
$before = $productable->stock;
$productable = $this->stockProduct($productable, $quantity, $dontSave);
break;
default:
throw new \InvalidArgumentException('The productable with class "'.get_class($productable).'" is not supported');
}
return $productable;
}
/**
* Stock a product. If the quantity is positive, that quantity will be added to the stock. Else it will be substracted from the stock.
*
* @param Product $product
* @param int $quantity
* @param bool $dontSave modify the products stock quantity, but dont save it yet when it is true. Otherwise always save it.
* @return Product
*/
private function stockProduct(Product &$product, int $quantity, $dontSave = false)
{
$newQuantity = $product->stock + $quantity;
if ($newQuantity < 0) {
$this->stockQuantityBelowZeroForProductable($product);
} elseif ($newQuantity == 0) {
$this->productableOutOfStock($product);
}
$before = $product->stock;
$product->stock = $newQuantity;
if (! $dontSave) {
$product->save();
}
return $product;
}
/**
* Do something when the productables quantity is below zero
*
* @param ProductableInterface $productable
*/
protected function stockQuantityBelowZeroForProductable(productableInterface $productable)
{
Log::warning('The stock quantity of "'.get_class($productable).'" with id "'.$productable->id.'" was set to a value below 0. Was: '.$productable->stock);
}
/**
* Do something when the productables quantity is below zero
*
* @param ProductableInterface $productable
*/
protected function productableOutOfStock(productableInterface $productable)
{
Log::warning('"'.get_class($productable).'" with id "'.$productable->id.'" has ran out of stock');
}
}