OrderItemGetController.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\OrderItemModel;
  5. use Models\ProductModel;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. use Respect\Validation\Validator as v;
  8. use Respect\Validation\Exceptions\ValidationException;
  9. class OrderItemGetController
  10. {
  11. private OrderItemModel $model;
  12. public function __construct()
  13. {
  14. $this->model = new OrderItemModel();
  15. }
  16. public function __invoke(ServerRequestInterface $request)
  17. {
  18. $body = json_decode((string)$request->getBody(), true) ?? [];
  19. try {
  20. v::key('company_id', v::intType()->positive())->assert($body);
  21. if (isset($body['order_id'])) {
  22. v::key('order_id', v::intType()->positive())->assert($body);
  23. }
  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 = isset($body['order_id']) ? (int) $body['order_id'] : null;
  29. $orderItems = $this->model->getOrderItemsByOrderId($orderId, $companyId);
  30. $productModel = new ProductModel();
  31. foreach ($orderItems as &$item) {
  32. $product = $productModel->getProductById($item['product_id'], $companyId);
  33. $item['product_details'] = $product;
  34. }
  35. if (!empty($orderItems)) {
  36. return ResponseLib::sendOk($orderItems);
  37. }
  38. return ResponseLib::sendFail("No order items found for the given data", [], "E_DATABASE")->withStatus(404);
  39. }
  40. }