You are here

public function AddHTTPHeaders::onRespond in HTTP Response Headers 8.2

Same name and namespace in other branches
  1. 8 src/EventSubscriber/AddHTTPHeaders.php \Drupal\http_response_headers\EventSubscriber\AddHTTPHeaders::onRespond()
  2. 2.0.x src/EventSubscriber/AddHTTPHeaders.php \Drupal\http_response_headers\EventSubscriber\AddHTTPHeaders::onRespond()

Sets extra HTTP headers.

File

src/EventSubscriber/AddHTTPHeaders.php, line 40
Contains \Drupal\http_response_headers\EventSubscriber\AddHTTPHeaders.

Class

AddHTTPHeaders
Provides AddHTTPHeaders.

Namespace

Drupal\http_response_headers\EventSubscriber

Code

public function onRespond(FilterResponseEvent $event) {
  if (!$event
    ->isMasterRequest()) {
    return;
  }
  $response = $event
    ->getResponse();
  $headers = $this->entityManager
    ->loadMultiple();
  if (!empty($headers)) {
    foreach ($headers as $key => $header) {
      if (!empty($header
        ->get('name'))) {

        // @TODO Add context rules to header groups to allow
        // certain groups to only be applied in certain contexts.
        if (!empty($header
          ->get('value'))) {

          // Must remove the existing header if settings a new value.
          if ($response->headers
            ->has($header
            ->get('name'))) {
            $response->headers
              ->remove($header
              ->get('name'));
          }
          $response->headers
            ->set($header
            ->get('name'), $header
            ->get('value'));
        }
        else {
          $response->headers
            ->remove($header
            ->get('name'));
        }
      }
    }
  }
}