Cors.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of asm89/stack-cors.
  4. *
  5. * (c) Alexander <iam.asm89@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Asm89\Stack;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpKernel\HttpKernelInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. class Cors implements HttpKernelInterface
  15. {
  16. /**
  17. * @var \Symfony\Component\HttpKernel\HttpKernelInterface
  18. */
  19. private $app;
  20. /**
  21. * @var \Asm89\Stack\CorsService
  22. */
  23. private $cors;
  24. private $defaultOptions = [
  25. 'allowedHeaders' => [],
  26. 'allowedMethods' => [],
  27. 'allowedOrigins' => [],
  28. 'allowedOriginsPatterns' => [],
  29. 'exposedHeaders' => [],
  30. 'maxAge' => 0,
  31. 'supportsCredentials' => false,
  32. ];
  33. public function __construct(HttpKernelInterface $app, array $options = [])
  34. {
  35. $this->app = $app;
  36. $this->cors = new CorsService(array_merge($this->defaultOptions, $options));
  37. }
  38. public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
  39. {
  40. if ($this->cors->isPreflightRequest($request)) {
  41. $response = $this->cors->handlePreflightRequest($request);
  42. return $this->cors->varyHeader($response, 'Access-Control-Request-Method');
  43. }
  44. $response = $this->app->handle($request, $type, $catch);
  45. if ($request->getMethod() === 'OPTIONS') {
  46. $this->cors->varyHeader($response, 'Access-Control-Request-Method');
  47. }
  48. return $this->cors->addActualRequestHeaders($response, $request);
  49. }
  50. }