OrderItemGetController.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. } else {
  24. if (isset($body['page'])) {
  25. v::key('page', v::intType()->positive())->assert($body);
  26. }
  27. }
  28. } catch (ValidationException $e) {
  29. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  30. }
  31. $companyId = (int) $body['company_id'];
  32. $orderId = isset($body['order_id']) ? (int) $body['order_id'] : null;
  33. $page = isset($body['page']) ? (int) $body['page'] : 1;
  34. if ($page < 1) {
  35. $page = 1;
  36. }
  37. $orderItems = $this->model->getOrderItemsByOrderId($orderId, $companyId, $page);
  38. $productModel = new ProductModel();
  39. foreach ($orderItems as &$item) {
  40. $product = $productModel->getProductById($item['product_id'], $companyId);
  41. $item['product_details'] = $product;
  42. }
  43. if (!empty($orderItems)) {
  44. return ResponseLib::sendOk($orderItems);
  45. }
  46. return ResponseLib::sendFail("No order items found for the given data", [], "E_DATABASE")->withStatus(404);
  47. }
  48. }