You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

86 lines
2.6 KiB

<?php
namespace Etu\Controller;
use Etu\Helpers\Inventory as InventoryHelper;
use Monolog\Logger;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class Inventory
{
/** @var InventoryHelper */
private $inventoryHelper;
/** @var Logger */
private $logger;
public function __construct(Logger $logger, InventoryHelper $inventoryHelper)
{
$this->logger = $logger;
$this->inventoryHelper = $inventoryHelper;
}
public function get(Request $request, Response $response, array $args)
{
$item = $this->inventoryHelper->get($args['item']);
// No such item
if (!$item) {
return $response->withJson(['status' => 'item not found'], 404);
}
$this->logger->info('Selected {item} from database and current stock is {stock}', [
'id' => $item->item_id,
'item' => $item->item_name,
'stock' => $item->item_stock,
]);
// If we're out of items
if ((int) $item->item_stock <= 0) {
return $response->withJson(['status' => 'out of stock', 'stock' => 0]);
}
return $response->withJson(['status' => 'in stock', 'stock' => (int) $item->item_stock]);
}
public function delete(Request $request, Response $response, array $args)
{
$item = $this->inventoryHelper->get($args['item']);
// No such item
if (!$item) {
return $response->withJson(['status' => 'item not found'], 404);
}
// Amount not avaiable
if ((int) $item->item_stock < (int) $args['amount']) {
return $response->withJson([
'status' => 'requested amount not available',
'available_amount' => $item->item_stock,
]);
}
if ((int) $args['amount'] < 1) {
return $response->withJson(['status' => 'invalid amount value'], 400);
}
// Set new amount in database
$this->inventoryHelper->setAmount($item->item_name, ($item->item_stock - $args['amount']));
return $response->withJson(['status' => 'success']);
}
public function put(Request $request, Response $response, array $args)
{
$item = $this->inventoryHelper->get($args['item']);
// No such item
if (!$item) {
$this->inventoryHelper->addItem($args['item'], $args['amount']);
} else {
$this->inventoryHelper->setAmount($item->item_name, ($item->item_stock + $args['amount']));
}
return $response->withJson(['status' => 'success']);
}
}