RegisterCprController.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\CprModel;
  5. use Models\StatusModel;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. use Respect\Validation\Validator as val;
  9. class RegisterCprController
  10. {
  11. private CprModel $cprModel;
  12. private StatusModel $statusModel;
  13. public function __construct()
  14. {
  15. $this->cprModel = new CprModel();
  16. $this->statusModel = new StatusModel();
  17. }
  18. public function __invoke(ServerRequestInterface $request)
  19. {
  20. $body = json_decode((string)$request->getBody(), true) ?? [];
  21. try {
  22. val::key('cpr_children_codes', val::arrayType()->notEmpty()->each(val::stringType()->notEmpty()))
  23. ->assert($body);
  24. } catch (ValidationException $e) {
  25. return ResponseLib::sendFail(
  26. 'Validation failed: ' . $e->getFullMessage(),
  27. [],
  28. 'E_VALIDATE'
  29. )->withStatus(400);
  30. }
  31. $statusId = $this->statusModel->getIdByStatus('pending');
  32. if ($statusId === null) {
  33. return ResponseLib::sendFail('Pending status not found', [], 'E_DATABASE')->withStatus(500);
  34. }
  35. try {
  36. $record = $this->cprModel->create($body, $statusId);
  37. } catch (\InvalidArgumentException $e) {
  38. return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
  39. } catch (\Throwable $e) {
  40. return ResponseLib::sendFail('Failed to create CPR: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  41. }
  42. return ResponseLib::sendOk($record, 'S_CREATED');
  43. }
  44. }