RegisterController.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\UserModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as val;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. class RegisterController
  9. {
  10. private UserModel $userModel;
  11. public function __construct()
  12. {
  13. $this->userModel = new UserModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string) $request->getBody(), true) ?? [];
  18. $companyId = (int)($request->getAttribute('api_company_id') ?? 0);
  19. if ($companyId <= 0) {
  20. return ResponseLib::sendFail('Authenticated company not found', [], 'E_VALIDATE')->withStatus(401);
  21. }
  22. try {
  23. val::key('username', val::stringType()->notEmpty()->length(1, 100))
  24. ->key('email', val::email())
  25. ->key('password', val::stringType()->length(8, null))
  26. ->key('phone', val::stringType()->notEmpty()->length(1, 50))
  27. ->key('address', val::stringType()->notEmpty()->length(1, 255))
  28. ->key('city', val::stringType()->notEmpty()->length(1, 100))
  29. ->key('state', val::stringType()->notEmpty()->length(1, 100))
  30. ->key('zip', val::stringType()->notEmpty()->length(1, 20))
  31. ->key('country', val::stringType()->notEmpty()->length(1, 100))
  32. ->key('birthdate', val::intType())
  33. ->key('cpf', val::stringType()->notEmpty()->length(1, 50))
  34. ->assert($body);
  35. } catch (ValidationException $e) {
  36. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  37. }
  38. $body['company_id'] = $companyId;
  39. $body['kyc'] = 0;
  40. $body['role_id'] = 2;
  41. $userData = $this->userModel->createUser($body);
  42. if (!$userData) {
  43. return ResponseLib::sendFail("Email already exists or creation failed", [], "E_VALIDATE")->withStatus(400);
  44. }
  45. return ResponseLib::sendOk($userData, "S_CREATED");
  46. }
  47. }