ProductCreateController.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\ProductModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as v;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. class ProductCreateController
  9. {
  10. private ProductModel $model;
  11. public function __construct()
  12. {
  13. $this->model = new ProductModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string)$request->getBody(), true) ?? [];
  18. try {
  19. v::key('company_id', v::intType()->positive())
  20. ->key('product_name', v::stringType()->notEmpty()->alnum(' '))
  21. ->key('product_price', v::number()->positive())
  22. ->key('category_id', v::intType()->positive())
  23. ->key('product_is_kitchen', v::optional(v::boolType()))
  24. ->assert($body);
  25. } catch (ValidationException $e) {
  26. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  27. }
  28. $companyId = $body['company_id'];
  29. $productName = $body['product_name'];
  30. $productPrice = (float) $body['product_price'];
  31. $categoryId = $body['category_id'];
  32. $productIsKitchen = $body['product_is_kitchen'] ?? false;
  33. $created = $this->model->createProduct(
  34. $productName,
  35. $productPrice,
  36. (int)$categoryId,
  37. (int)$companyId,
  38. $productIsKitchen
  39. );
  40. return $created
  41. ? ResponseLib::sendOk(['created' => true])
  42. : ResponseLib::sendFail("Failed to Create Product", [], "E_DATABASE")->withStatus(402);
  43. }
  44. }