| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\CprModel;
- use Models\StatusModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Respect\Validation\Exceptions\ValidationException;
- use Respect\Validation\Validator as val;
- class RegisterCprController
- {
- private CprModel $cprModel;
- private StatusModel $statusModel;
- public function __construct()
- {
- $this->cprModel = new CprModel();
- $this->statusModel = new StatusModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true) ?? [];
- try {
- val::key('cpr_children_codes', val::arrayType()->notEmpty()->each(val::stringType()->notEmpty()))
- ->assert($body);
- } catch (ValidationException $e) {
- return ResponseLib::sendFail(
- 'Validation failed: ' . $e->getFullMessage(),
- [],
- 'E_VALIDATE'
- )->withStatus(400);
- }
- $statusId = $this->statusModel->getIdByStatus('pending');
- if ($statusId === null) {
- return ResponseLib::sendFail('Pending status not found', [], 'E_DATABASE')->withStatus(500);
- }
- try {
- $record = $this->cprModel->create($body, $statusId);
- } catch (\InvalidArgumentException $e) {
- return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
- } catch (\Throwable $e) {
- return ResponseLib::sendFail('Failed to create CPR: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
- }
- return ResponseLib::sendOk($record, 'S_CREATED');
- }
- }
|