CprMonitoringUpdateController.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 CprMonitoringUpdateController
  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. ->key('preview', val::optional(val::boolType()), false)
  26. ->key('description', val::optional(val::stringType()->notEmpty()->length(1, 5000)), false)
  27. ->key('link', val::optional(val::stringType()->notEmpty()->length(1, 2048)), false)
  28. ->assert($body);
  29. } catch (ValidationException $e) {
  30. return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
  31. }
  32. $id = (int)$body['id'];
  33. $preview = array_key_exists('preview', $body) ? (bool)$body['preview'] : null;
  34. $description = array_key_exists('description', $body) ? (string)$body['description'] : null;
  35. $link = array_key_exists('link', $body) ? (string)$body['link'] : null;
  36. if ($preview === null && $description === null && $link === null) {
  37. return ResponseLib::sendFail('Validation failed: nothing to update', [], 'E_VALIDATE')->withStatus(400);
  38. }
  39. try {
  40. $updated = $this->service->update($id, $preview, $description, $link);
  41. } catch (\InvalidArgumentException $e) {
  42. return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
  43. } catch (\Throwable $e) {
  44. return ResponseLib::sendFail('Failed to update cpr monitoring: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  45. }
  46. return $updated
  47. ? ResponseLib::sendOk($updated, 'S_UPDATED')
  48. : ResponseLib::sendFail('Cpr monitoring Not Found or Not Updated', [], 'E_DATABASE')->withStatus(204);
  49. }
  50. }