protected function compileSubgroup(string $directive, $policies = null) : string
{
if ($policies === '*') {
// Don't even waste the overhead adding this to the header
return '';
} elseif (empty($policies)) {
if ($directive === 'plugin-types') {
return '';
}
return $directive . " 'none'; ";
}
$ret = $directive . ' ';
if ($directive === 'plugin-types') {
// Expects MIME types, not URLs
return $ret . \implode(' ', $policies['allow']) . '; ';
}
if (!empty($policies['self'])) {
$ret .= "'self' ";
}
if (!empty($policies['allow'])) {
foreach ($policies['allow'] as $url) {
$url = \filter_var($url, FILTER_SANITIZE_URL);
if ($url !== false) {
if ($this->supportOldBrowsers) {
if (\strpos($url, '://') === false) {
if ($this->isHTTPSConnection() || !empty($this->policies['upgrade-insecure-requests'])) {
// We only want HTTPS connections here.
$ret .= 'https://' . $url . ' ';
} else {
$ret .= 'https://' . $url . ' http://' . $url . ' ';
}
}
}
if ($this->isHTTPSConnection() || !empty($this->policies['upgrade-insecure-requests'])) {
$ret .= \str_replace('http://', 'https://', $url) . ' ';
} else {
$ret .= $url . ' ';
}
}
}
}
if (!empty($policies['hashes'])) {
foreach ($policies['hashes'] as $hash) {
foreach ($hash as $algo => $hashval) {
$ret .= \implode('', ["'", \preg_replace('/[^A-Za-z0-9]/', '', $algo), '-', \preg_replace('/[^A-Za-z0-9\\+\\/=]/', '', $hashval), "' "]);
}
}
}
if (!empty($policies['nonces'])) {
foreach ($policies['nonces'] as $nonce) {
$ret .= \implode('', ["'nonce-", \preg_replace('/[^A-Za-z0-9\\+\\/=]/', '', $nonce), "' "]);
}
}
if (!empty($policies['types'])) {
foreach ($policies['types'] as $type) {
$ret .= $type . ' ';
}
}
if (!empty($policies['unsafe-inline'])) {
$ret .= "'unsafe-inline' ";
}
if (!empty($policies['unsafe-eval'])) {
$ret .= "'unsafe-eval' ";
}
if (!empty($policies['data'])) {
$ret .= "data: ";
}
return \rtrim($ret, ' ') . '; ';
}