| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\ProductModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Respect\Validation\Validator as v;
- use Respect\Validation\Exceptions\ValidationException;
- class ProductUpdateController
- {
- private ProductModel $model;
- public function __construct()
- {
- $this->model = new ProductModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true) ?? [];
- try {
- v::key('company_id', v::intType()->positive())
- ->key('update_product_id', v::intType()->positive())
- ->key('product_name', v::optional(v::stringType()->notEmpty()), false)
- ->key('product_price', v::optional(v::number()->positive()), false)
- ->key('category_id', v::optional(v::intType()->positive()), false) // opcional mas ignorado
- ->key('product_is_kitchen', v::optional(v::boolType()), false)
- ->assert($body);
- } catch (ValidationException $e) {
- return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
- }
- $hasProductName = isset($body['product_name']) && $body['product_name'] !== null;
- $hasProductPrice = isset($body['product_price']) && $body['product_price'] !== null;
- $hasProductIsKitchen = array_key_exists('product_is_kitchen', $body);
- if (!$hasProductName && !$hasProductPrice && !$hasProductIsKitchen) {
- return ResponseLib::sendFail("Missing fields to update", [], "E_VALIDATE")->withStatus(400);
- }
- $companyId = $body['company_id'];
- $productId = $body['update_product_id'];
- $productName = $hasProductName ? $body['product_name'] : null;
- $productPrice = $hasProductPrice ? (float)$body['product_price'] : null;
- $productIsKitchen = $hasProductIsKitchen ? (bool)$body['product_is_kitchen'] : null;
- $updated = $this->model->updateProduct(
- (int)$productId,
- (int)$companyId,
- $productName,
- $productPrice,
- $productIsKitchen
- );
- return $updated
- ? ResponseLib::sendOk(['updated' => true])
- : ResponseLib::sendFail("Failed to Update Product or Product Not Found", [], "E_DATABASE")->withStatus(404);
- }
- }
|