CorsKernel.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Barryvdh\Cors\Tests;
  3. use Asm89\Stack\CorsService;
  4. use Symfony\Component\HttpKernel\HttpKernelInterface;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. /**
  8. * Fork of asm89/stack-cors
  9. */
  10. class CorsKernel implements HttpKernelInterface
  11. {
  12. /**
  13. * @var \Symfony\Component\HttpKernel\HttpKernelInterface
  14. */
  15. private $app;
  16. /**
  17. * @var \Asm89\Stack\CorsService
  18. */
  19. private $cors;
  20. private $defaultOptions = array(
  21. 'allowedHeaders' => array(),
  22. 'allowedMethods' => array(),
  23. 'allowedOrigins' => array(),
  24. 'exposedHeaders' => false,
  25. 'maxAge' => false,
  26. 'supportsCredentials' => false,
  27. );
  28. public function __construct(HttpKernelInterface $app, array $options = array())
  29. {
  30. $this->app = $app;
  31. $this->cors = new CorsService(array_merge($this->defaultOptions, $options));
  32. }
  33. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  34. {
  35. if (!$this->cors->isCorsRequest($request)) {
  36. return $this->app->handle($request, $type, $catch);
  37. }
  38. if ($this->cors->isPreflightRequest($request)) {
  39. return $this->cors->handlePreflightRequest($request);
  40. }
  41. if (!$this->cors->isActualRequestAllowed($request)) {
  42. return new Response('Not allowed.', 403);
  43. }
  44. $response = $this->app->handle($request, $type, $catch);
  45. return $this->cors->addActualRequestHeaders($response, $request);
  46. }
  47. }