CprMonitoringCreateController.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 CprMonitoringCreateController
  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('cpr_id', val::intType()->positive())
  25. ->key('description', val::stringType()->notEmpty()->length(1, 5000))
  26. ->key('link', val::stringType()->notEmpty()->length(1, 2048))
  27. ->key('preview', val::boolType(), false)
  28. ->assert($body);
  29. } catch (ValidationException $e) {
  30. return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
  31. }
  32. $cprId = (int)$body['cpr_id'];
  33. $preview = isset($body['preview']) ? (bool)$body['preview'] : false;
  34. $description = (string)$body['description'];
  35. $link = (string)$body['link'];
  36. try {
  37. $created = $this->service->create($cprId, $preview, $description, $link);
  38. } catch (\InvalidArgumentException $e) {
  39. return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
  40. } catch (\PDOException $e) {
  41. if (($e->getCode() ?? '') === '23503') {
  42. return ResponseLib::sendFail('CPR not found', ['cpr_id' => $cprId], 'E_NOT_FOUND')->withStatus(404);
  43. }
  44. return ResponseLib::sendFail('Failed to create cpr monitoring: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  45. } catch (\Throwable $e) {
  46. return ResponseLib::sendFail('Failed to create cpr monitoring: ' . $e->getMessage(), [], 'E_INTERNAL')->withStatus(500);
  47. }
  48. return ResponseLib::sendOk($created, 'S_CREATED');
  49. }
  50. }