You are here

public function Csp::getHeaderValue in Content-Security-Policy 8

Get the header value.

Return value

string The header value.

1 call to Csp::getHeaderValue()
Csp::__toString in src/Csp.php
Create the string header representation.

File

src/Csp.php, line 381

Class

Csp
A CSP Header.

Namespace

Drupal\csp

Code

public function getHeaderValue() {
  $output = [];
  $optimizedDirectives = [];
  foreach ($this->directives as $name => $value) {
    if (empty($value) && self::DIRECTIVES[$name] !== self::DIRECTIVE_SCHEMA_OPTIONAL_TOKEN_LIST) {
      continue;
    }
    if (self::DIRECTIVES[$name] === self::DIRECTIVE_SCHEMA_BOOLEAN || self::DIRECTIVES[$name] === self::DIRECTIVE_SCHEMA_OPTIONAL_TOKEN_LIST && empty($value)) {
      $output[] = $name;
      continue;
    }
    if (in_array(self::DIRECTIVES[$name], [
      self::DIRECTIVE_SCHEMA_SOURCE_LIST,
      self::DIRECTIVE_SCHEMA_ANCESTOR_SOURCE_LIST,
    ])) {
      $value = self::reduceSourceList($value);
    }
    $optimizedDirectives[$name] = $value;
  }
  foreach ($optimizedDirectives as $name => $value) {
    foreach (self::getDirectiveFallbackList($name) as $fallbackDirective) {
      if (isset($optimizedDirectives[$fallbackDirective])) {
        if ($optimizedDirectives[$fallbackDirective] === $value) {

          // Omit directive if it matches nearest defined directive in its
          // fallback list.
          unset($optimizedDirectives[$name]);
          continue 2;
        }
        else {

          // If directive doesn't match nearest defined fallback, further
          // fallback directives must not be checked.
          break;
        }
      }
    }

    // Optimize attribute directives if they don't match a fallback.
    if (strstr($name, '-attr')) {
      $optimizedDirectives[$name] = self::reduceAttrSourceList($value);
    }
  }

  // Workaround Firefox bug in handling default-src.
  $optimizedDirectives = self::ff1313937($optimizedDirectives);
  $optimizedDirectives = self::sortDirectives($optimizedDirectives);
  foreach ($optimizedDirectives as $name => $value) {
    $output[] = $name . ' ' . implode(' ', $value);
  }
  return implode('; ', $output);
}