CprQueryController.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. $bodyCompanyId = (int)($body['company_id'] ?? 0);
  21. if ($bodyCompanyId <= 0) {
  22. return ResponseLib::sendFail('company_id is required', [], 'E_VALIDATE')->withStatus(400);
  23. }
  24. $authCompanyId = (int)$request->getAttribute('api_company_id');
  25. if ($authCompanyId !== $bodyCompanyId) {
  26. return ResponseLib::sendFail(
  27. 'Unauthorized company access',
  28. [],
  29. 'E_AUTH'
  30. )->withStatus(403);
  31. }
  32. $cprId = isset($body['cpr_id']) ? (int)$body['cpr_id'] : null;
  33. try {
  34. if ($cprId) {
  35. $record = $this->model->getByIdAndCompany($cprId, $authCompanyId);
  36. if (!$record) {
  37. return ResponseLib::sendFail(
  38. 'CPR not found',
  39. [],
  40. 'E_NOT_FOUND'
  41. )->withStatus(404);
  42. }
  43. return Response::json($record)->withStatus(200);
  44. }
  45. $list = $this->model->listByCompany($authCompanyId);
  46. return Response::json($list)->withStatus(200);
  47. } catch (\Throwable $e) {
  48. return ResponseLib::sendFail(
  49. 'Failed to query CPRs: ' . $e->getMessage(),
  50. [],
  51. 'E_DATABASE'
  52. )->withStatus(500);
  53. }
  54. }
  55. }