You are here

protected function CorsResponseEventSubscriberTest::assertValidCorsHeaders in farmOS 2.x

Helper method to test valid CORS headers.

Parameters

\Psr\Http\Message\ResponseInterface $response: The response to check.

string|null $origin: An optional origin to check. If NULL, then the request should have no CORS headers.

1 call to CorsResponseEventSubscriberTest::assertValidCorsHeaders()
CorsResponseEventSubscriberTest::testCorsResponseHeaders in modules/core/api/tests/src/Functional/CorsResponseEventSubscriberTest.php
Test CORS response headers are correctly added.

File

modules/core/api/tests/src/Functional/CorsResponseEventSubscriberTest.php, line 103

Class

CorsResponseEventSubscriberTest
Tests that CORS headers are properly added.

Namespace

Drupal\Tests\farm_api\Functional

Code

protected function assertValidCorsHeaders(ResponseInterface $response, string $origin = NULL) {

  // Cors headers to test.
  $cors_headers = [
    'Access-Control-Allow-Origin' => $origin,
    'Access-Control-Allow-Credentials' => 'true',
    'Access-Control-Allow-Headers' => 'Content-Type,Content-Disposition,Authorization,X-CSRF-Token',
    'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,HEAD,OPTIONS',
    'Vary' => 'Origin',
  ];

  // Check if the response should contain headers.
  $needs_cors = !empty($origin);
  foreach ($cors_headers as $header => $value) {
    $this
      ->assertEquals($needs_cors, $response
      ->hasHeader($header), 'Response has correct CORS headers.');
    if ($needs_cors) {
      $this
        ->assertEquals($value, $response
        ->getHeader($header)[0], 'Response has correct header value.');
    }
  }
}