ProductCreateController.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\ProductModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class ProductCreateController
  7. {
  8. private ProductModel $model;
  9. public function __construct()
  10. {
  11. $this->model = new ProductModel();
  12. }
  13. public function __invoke(ServerRequestInterface $request)
  14. {
  15. $body = json_decode((string)$request->getBody(), true) ?? [];
  16. $companyId = $body['company_id'] ?? null;
  17. $productName = $body['product_name'] ?? null;
  18. $productPrice = $body['product_price'] ?? null;
  19. $categoryId = $body['category_id'] ?? null;
  20. if (!$companyId || !$productName || !$productPrice || !$categoryId) {
  21. return ResponseLib::sendFail("Missing product_name, product_price, category_id or company_id", [], "E_VALIDATE")->withStatus(400);
  22. }
  23. $created = $this->model->createProduct(
  24. $productName,
  25. (float)$productPrice,
  26. (int)$categoryId,
  27. (int)$companyId
  28. );
  29. return $created ? ResponseLib::sendOk(['created' => true]) : ResponseLib::sendFail("Failed to Create Product", [], "E_DATABASE")->withStatus(402);
  30. }
  31. }