ProductUpdateController.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 ProductUpdateController
  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('update_product_id', v::intType()->positive())
  21. ->key('product_name', v::optional(v::stringType()->notEmpty()), false)
  22. ->key('product_price', v::optional(v::number()->positive()), false)
  23. ->assert($body);
  24. } catch (ValidationException $e) {
  25. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  26. }
  27. // Verifica se pelo menos um dos dois está presente
  28. $hasProductName = isset($body['product_name']) && $body['product_name'] !== null;
  29. $hasProductPrice = isset($body['product_price']) && $body['product_price'] !== null;
  30. if (!$hasProductName && !$hasProductPrice) {
  31. return ResponseLib::sendFail("Missing product_name or product_price for update", [], "E_VALIDATE")->withStatus(400);
  32. }
  33. $companyId = $body['company_id'];
  34. $productId = $body['update_product_id'];
  35. $productName = $hasProductName ? $body['product_name'] : null;
  36. $productPrice = $hasProductPrice ? (float)$body['product_price'] : null;
  37. $updated = $this->model->updateProduct(
  38. (int)$productId,
  39. (int)$companyId,
  40. $productName,
  41. $productPrice
  42. );
  43. return $updated
  44. ? ResponseLib::sendOk(['updated' => true])
  45. : ResponseLib::sendFail("Failed to Update Product or Product Not Found", [], "E_DATABASE")->withStatus(404);
  46. }
  47. }