CorsControl.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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' => '0.0.0.0',
  12. 'Access-Control-Allow-Methods' => 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
  13. 'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, Accept, Origin',
  14. 'Access-Control-Allow-Credentials' => 'true',
  15. 'Access-Control-Max-Age' => '86400', // cache de preflight por 24h
  16. ];
  17. // 2) Responde direto a preflight
  18. if ($request->getMethod() === 'OPTIONS') {
  19. return new Response(204, $corsHeaders);
  20. }
  21. // 3) Se o “next” vier como string (nome de classe), instancia‑o:
  22. if (is_string($next) && class_exists($next)) {
  23. $instance = new $next();
  24. // se tiver __invoke, use-o
  25. if (is_callable($instance)) {
  26. $next = $instance;
  27. }
  28. // caso seu controller siga outro padrão PSR-15, adapte aqui:
  29. // elseif (method_exists($instance, 'handle')) {
  30. // $next = [$instance, 'handle'];
  31. // }
  32. else {
  33. throw new \RuntimeException("Controller “{$next}” não é callable");
  34. }
  35. }
  36. // 4) Chama o próximo handler (agora garantidamente callable)
  37. $response = $next($request);
  38. // 5) Injeta os headers CORS na resposta
  39. foreach ($corsHeaders as $h => $v) {
  40. $response = $response->withHeader($h, $v);
  41. }
  42. return $response;
  43. }
  44. }