ProductCreateController.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\CategoryModel;
  5. use Models\ProductModel;
  6. use Models\DescriptionModel;
  7. use Psr\Http\Message\ServerRequestInterface;
  8. use Respect\Validation\Validator as v;
  9. use Respect\Validation\Exceptions\ValidationException;
  10. class ProductCreateController
  11. {
  12. private ProductModel $productModel;
  13. private DescriptionModel $descriptionModel;
  14. public function __construct()
  15. {
  16. $this->productModel = new ProductModel();
  17. $this->descriptionModel = new DescriptionModel();
  18. }
  19. public function __invoke(ServerRequestInterface $request)
  20. {
  21. $body = json_decode((string)$request->getBody(), true) ?? [];
  22. try {
  23. v::key('company_id', v::intType()->positive())
  24. ->key('product_name', v::stringType()->notEmpty()->alnum(' '))
  25. ->key('product_price', v::number()->positive())
  26. ->key('category_id', v::intType()->positive())
  27. ->key('product_is_kitchen', v::optional(v::boolType()))
  28. ->assert($body);
  29. if (array_key_exists('description_text', $body)) {
  30. v::stringType()->notEmpty()->length(1, 70)->assert($body['description_text']);
  31. }
  32. } catch (ValidationException $e) {
  33. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  34. }
  35. $companyId = $body['company_id'];
  36. $productName = $body['product_name'];
  37. $productPrice = (float) $body['product_price'];
  38. $categoryId = $body['category_id'];
  39. $productIsKitchen = $body['product_is_kitchen'] ?? false;
  40. $descriptionText = $body['description_text'] ?? null;
  41. $productId = $this->productModel->createProduct(
  42. $productName,
  43. $productPrice,
  44. (int)$categoryId,
  45. (int)$companyId,
  46. $productIsKitchen
  47. );
  48. if (!$productId) {
  49. return ResponseLib::sendFail("Failed to Create Product", [], "E_DATABASE")->withStatus(402);
  50. }
  51. if ($descriptionText !== null) {
  52. $descriptionCreated = $this->descriptionModel->addDescription(
  53. (int)$productId,
  54. (int)$companyId,
  55. $descriptionText
  56. );
  57. if (!$descriptionCreated) {
  58. return ResponseLib::sendFail("Product created, but failed to create description.", [], "E_DATABASE")->withStatus(500);
  59. }
  60. }
  61. return ResponseLib::sendOk(['created' => true, 'product_id' => $productId]);
  62. }
  63. }