OrderItemGetController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. $orderItems = $this->model->getOrderItemsByOrderId($orderId, $companyId, $page);
  35. $productModel = new ProductModel();
  36. foreach ($orderItems as &$item) {
  37. $product = $productModel->getProductById($item['product_id'], $companyId);
  38. $item['product_details'] = $product;
  39. }
  40. if (!empty($orderItems)) {
  41. return ResponseLib::sendOk($orderItems);
  42. }
  43. return ResponseLib::sendFail("No Order Items Found for the Given Data", [], "E_DATABASE")->withStatus(204);
  44. }
  45. }