ProductUpdateController.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. ->key('category_id', v::optional(v::intType()->positive()), false) // opcional mas ignorado
  24. ->key('product_is_kitchen', v::optional(v::boolType()), false)
  25. ->assert($body);
  26. } catch (ValidationException $e) {
  27. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(401);
  28. }
  29. $hasProductName = isset($body['product_name']) && $body['product_name'] !== null;
  30. $hasProductPrice = isset($body['product_price']) && $body['product_price'] !== null;
  31. $hasProductIsKitchen = array_key_exists('product_is_kitchen', $body);
  32. if (!$hasProductName && !$hasProductPrice && !$hasProductIsKitchen) {
  33. return ResponseLib::sendFail("Missing fields to update", [], "E_VALIDATE")->withStatus(400);
  34. }
  35. $companyId = $body['company_id'];
  36. $productId = $body['update_product_id'];
  37. $productName = $hasProductName ? $body['product_name'] : null;
  38. $productPrice = $hasProductPrice ? (float)$body['product_price'] : null;
  39. $productIsKitchen = $hasProductIsKitchen ? (bool)$body['product_is_kitchen'] : null;
  40. $updated = $this->model->updateProduct(
  41. (int)$productId,
  42. (int)$companyId,
  43. $productName,
  44. $productPrice,
  45. $productIsKitchen
  46. );
  47. return $updated
  48. ? ResponseLib::sendOk(['updated' => true])
  49. : ResponseLib::sendFail("Failed to Update Product or Product Not Found", [], "E_DATABASE")->withStatus(204);
  50. }
  51. }