CprMonitoringGetController.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Psr\Http\Message\ServerRequestInterface;
  5. use Respect\Validation\Exceptions\ValidationException;
  6. use Respect\Validation\Validator as val;
  7. use Services\CprMonitoringService;
  8. class CprMonitoringGetController
  9. {
  10. private CprMonitoringService $service;
  11. public function __construct()
  12. {
  13. $this->service = new CprMonitoringService();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $userId = (int)($request->getAttribute('api_user_id') ?? 0);
  18. $companyId = (int)($request->getAttribute('api_company_id') ?? 0);
  19. if ($userId <= 0 || $companyId <= 0) {
  20. return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
  21. }
  22. $body = json_decode((string)$request->getBody(), true) ?? [];
  23. try {
  24. val::key('id', val::intType()->positive())
  25. ->assert($body);
  26. } catch (ValidationException $e) {
  27. return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
  28. }
  29. $id = (int)$body['id'];
  30. try {
  31. $row = $this->service->getById($id);
  32. } catch (\InvalidArgumentException $e) {
  33. return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
  34. } catch (\Throwable $e) {
  35. return ResponseLib::sendFail('Failed to fetch cpr monitoring: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  36. }
  37. return $row
  38. ? ResponseLib::sendOk($row)
  39. : ResponseLib::sendFail('Cpr monitoring not found', [], 'E_NOT_FOUND')->withStatus(404);
  40. }
  41. }