CprQueryController.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Psr\Http\Message\ServerRequestInterface;
  5. use React\Http\Message\Response;
  6. use Models\CprQueryModel;
  7. class CprQueryController
  8. {
  9. private CprQueryModel $model;
  10. public function __construct()
  11. {
  12. $this->model = new CprQueryModel();
  13. }
  14. public function __invoke(ServerRequestInterface $request)
  15. {
  16. $body = json_decode((string)$request->getBody(), true);
  17. if (!is_array($body)) {
  18. return ResponseLib::sendFail('Invalid JSON body', [], 'E_VALIDATE')->withStatus(400);
  19. }
  20. $authCompanyId = (int)($request->getAttribute('api_company_id') ?? 0);
  21. if ($authCompanyId <= 0) {
  22. return ResponseLib::sendFail('Authenticated company not found', [], 'E_VALIDATE')->withStatus(401);
  23. }
  24. $hasGlobalAccess = $authCompanyId === 1;
  25. $cprId = isset($body['cpr_id']) ? (int)$body['cpr_id'] : null;
  26. try {
  27. if ($cprId) {
  28. $record = $hasGlobalAccess
  29. ? $this->model->getById($cprId)
  30. : $this->model->getByIdAndCompany($cprId, $authCompanyId);
  31. if (!$record) {
  32. return ResponseLib::sendFail(
  33. 'CPR not found',
  34. [],
  35. 'E_NOT_FOUND'
  36. )->withStatus(404);
  37. }
  38. return Response::json($record)->withStatus(200);
  39. }
  40. $list = $hasGlobalAccess
  41. ? $this->model->listAll()
  42. : $this->model->listByCompany($authCompanyId);
  43. return Response::json($list)->withStatus(200);
  44. } catch (\Throwable $e) {
  45. return ResponseLib::sendFail(
  46. 'Failed to query CPRs: ' . $e->getMessage(),
  47. [],
  48. 'E_DATABASE'
  49. )->withStatus(500);
  50. }
  51. }
  52. }