ProductCreateController.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. ->assert($body);
  24. } catch (ValidationException $e) {
  25. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  26. }
  27. $companyId = $body['company_id'];
  28. $productName = $body['product_name'];
  29. $productPrice = (float) $body['product_price'];
  30. $categoryId = $body['category_id'];
  31. $created = $this->model->createProduct(
  32. $productName,
  33. $productPrice,
  34. (int)$categoryId,
  35. (int)$companyId
  36. );
  37. return $created
  38. ? ResponseLib::sendOk(['created' => true])
  39. : ResponseLib::sendFail("Failed to Create Product", [], "E_DATABASE")->withStatus(402);
  40. }
  41. }