File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/Stock/StockService.php
<?php declare(strict_types=1);
namespace App\Stock;
use App\Products\AbstractProductable;
use App\Products\Product\Product;
use Illuminate\Support\Facades\Log;
/**
* Class StockService
*
* @package App\Stock
*/
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 AbstractProductable $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 AbstractProductable|void
*/
public function stockProductable(AbstractProductable $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);
else if($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 AbstractProductable $productable
*/
protected function stockQuantityBelowZeroForProductable(AbstractProductable $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 AbstractProductable $productable
*/
protected function productableOutOfStock(AbstractProductable $productable)
{
Log::warning('"'.get_class($productable).'" with id "'.$productable->id.'" has ran out of stock');
}
}