TableCreateController.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\TableModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as v;
  7. use Respect\Validation\Exceptions\NestedValidationException;
  8. class TableCreateController
  9. {
  10. private TableModel $model;
  11. public function __construct()
  12. {
  13. $this->model = new TableModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string)$request->getBody(), true) ?? [];
  18. // ✅ Validação com Respect\Validation (letras, números e espaços permitidos)
  19. try {
  20. v::key('company_id', v::intVal()->positive())
  21. ->key('table_number', v::stringType()->notEmpty()->regex('/^[\pL\pN ]+$/u')->length(1, 10))
  22. ->key('status_id', v::intVal()->positive())
  23. ->assert($body);
  24. } catch (NestedValidationException $e) {
  25. return ResponseLib::sendFail($e->getMessages(), [], "E_VALIDATE")->withStatus(400);
  26. }
  27. $companyId = (int) $body['company_id'];
  28. $tableNumber = (string) $body['table_number'];
  29. $statusId = (int) $body['status_id'];
  30. if (!$this->model->companyExists($companyId)) {
  31. return ResponseLib::sendFail("Invalid company_id", [], "E_VALIDATE")->withStatus(400);
  32. }
  33. if (!$this->model->statusExists($statusId)) {
  34. return ResponseLib::sendFail("Invalid status_id", [], "E_VALIDATE")->withStatus(400);
  35. }
  36. $created = $this->model->createTable($companyId, $tableNumber, $statusId);
  37. return $created
  38. ? ResponseLib::sendOk(['created' => true])
  39. : ResponseLib::sendFail("Failed to create table", [], "E_DATABASE")->withStatus(500);
  40. }
  41. }