OrderbookFilterController.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\OrderbookSearchModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Exceptions\ValidationException;
  7. use Respect\Validation\Validator as val;
  8. class OrderbookFilterController
  9. {
  10. private OrderbookSearchModel $searchModel;
  11. public function __construct()
  12. {
  13. $this->searchModel = new OrderbookSearchModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string)$request->getBody(), true) ?? [];
  18. try {
  19. val::key('state', val::stringType()->notEmpty())
  20. ->key('commodity_type', val::stringType()->notEmpty())
  21. ->assert($body);
  22. } catch (ValidationException $e) {
  23. return ResponseLib::sendFail(
  24. 'Validation failed: ' . $e->getFullMessage(),
  25. [],
  26. 'E_VALIDATE'
  27. )->withStatus(400);
  28. }
  29. $state = strtoupper(trim((string)$body['state']));
  30. $commodityType = trim((string)$body['commodity_type']);
  31. try {
  32. $orders = $this->searchModel->searchOpenOrders($state, $commodityType);
  33. } catch (\Throwable $e) {
  34. return ResponseLib::sendFail(
  35. 'Falha ao consultar orderbook: ' . $e->getMessage(),
  36. [],
  37. 'E_DATABASE'
  38. )->withStatus(500);
  39. }
  40. if (!$orders) {
  41. return ResponseLib::sendOk(
  42. [
  43. 'state' => $state,
  44. 'commodity_type' => $commodityType,
  45. 'orders' => [],
  46. ],
  47. 'S_ORDERBOOK_EMPTY'
  48. );
  49. }
  50. return ResponseLib::sendOk([
  51. 'state' => $state,
  52. 'commodity_type' => $commodityType,
  53. 'orders' => $orders,
  54. ], 'S_ORDERBOOK_FILTER');
  55. }
  56. }