OrderItemCreateController.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\OrderItemModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as v;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. class OrderItemCreateController
  9. {
  10. private OrderItemModel $model;
  11. public function __construct()
  12. {
  13. $this->model = new OrderItemModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string)$request->getBody(), true) ?? [];
  18. try {
  19. // company_id, order_id e product_id são obrigatórios para criar um item de pedido
  20. v::key('company_id', v::intType()->positive()) // company_id agora é obrigatório
  21. ->key('order_id', v::intType()->positive())
  22. ->key('product_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 = (int) $body['company_id'];
  28. $orderId = (int) $body['order_id'];
  29. $productId = (int) $body['product_id'];
  30. $created = $this->model->createOrderItem($orderId, $productId, $companyId);
  31. return $created
  32. ? ResponseLib::sendOk(['created' => true, 'order_item_id' => $created])
  33. : ResponseLib::sendFail("Failed to create order item", [], "E_DATABASE")->withStatus(500);
  34. }
  35. }