CorsControl.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Middlewares;
  3. use Psr\Http\Message\ServerRequestInterface;
  4. use React\Http\Message\Response;
  5. class CorsControl
  6. {
  7. public function __invoke(ServerRequestInterface $request, $next)
  8. {
  9. // 1) Configurações CORS completamente abertas:
  10. $corsHeaders = [
  11. 'Access-Control-Allow-Origin' => '*',
  12. 'Access-Control-Allow-Methods' => 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
  13. 'Access-Control-Allow-Headers' => '*',
  14. 'Access-Control-Max-Age' => '86400', // cache de preflight por 24h
  15. ];
  16. // 2) Responde direto a preflight
  17. if ($request->getMethod() === 'OPTIONS') {
  18. return new Response(204, $corsHeaders);
  19. }
  20. // 3) Se o “next” vier como string (nome de classe), instancia‑o:
  21. if (is_string($next) && class_exists($next)) {
  22. $instance = new $next();
  23. // se tiver __invoke, use-o
  24. if (is_callable($instance)) {
  25. $next = $instance;
  26. }
  27. // caso seu controller siga outro padrão PSR-15, adapte aqui:
  28. // elseif (method_exists($instance, 'handle')) {
  29. // $next = [$instance, 'handle'];
  30. // }
  31. else {
  32. throw new \RuntimeException("Controller “{$next}” não é callable");
  33. }
  34. }
  35. // 4) Chama o próximo handler (agora garantidamente callable)
  36. $response = $next($request);
  37. // 5) Injeta os headers CORS na resposta
  38. foreach ($corsHeaders as $h => $v) {
  39. $response = $response->withHeader($h, $v);
  40. }
  41. return $response;
  42. }
  43. }