CommoditiesGetController.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\CommodityModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as val;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. class CommoditiesGetController
  9. {
  10. public function __invoke(ServerRequestInterface $request)
  11. {
  12. $query = $request->getQueryParams();
  13. try {
  14. val::arrayVal()
  15. ->key('flag', val::optional(val::stringType()), false)
  16. ->assert($query);
  17. } catch (ValidationException $e) {
  18. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  19. }
  20. $flag = null;
  21. if (array_key_exists('flag', $query)) {
  22. $v = (string)$query['flag'];
  23. if ($v === '' || strtolower($v) === 'all') {
  24. $flag = null; // no filter
  25. } else {
  26. $flag = $v;
  27. }
  28. }
  29. $model = new CommodityModel();
  30. $rows = $model->getAll($flag);
  31. if (!$rows) {
  32. return ResponseLib::sendFail('Commodities Not Found', [], 'E_DATABASE')->withStatus(204);
  33. }
  34. return ResponseLib::sendOk($rows);
  35. }
  36. }