CspSubscriber.php in Raven: Sentry Integration 8.2
File
src/EventSubscriber/CspSubscriber.php
View source
<?php
namespace Drupal\raven\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\csp\Csp;
use Drupal\csp\CspEvents;
use Drupal\csp\Event\PolicyAlterEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CspSubscriber implements EventSubscriberInterface {
private $configFactory;
public static function getSubscribedEvents() {
if (!class_exists(CspEvents::class)) {
return [];
}
$events[CspEvents::POLICY_ALTER] = [
'onCspPolicyAlter',
];
return $events;
}
public function __construct(ConfigFactoryInterface $configFactory) {
$this->configFactory = $configFactory;
}
public function onCspPolicyAlter(PolicyAlterEvent $alterEvent) {
$config = $this->configFactory
->get('raven.settings');
if (!$config
->get('javascript_error_handler')) {
return;
}
if (!class_exists(\Raven_Client::class)) {
return;
}
try {
$dsn = \Raven_Client::parseDSN(empty($_SERVER['SENTRY_DSN']) ? $config
->get('public_dsn') : $_SERVER['SENTRY_DSN']);
} catch (\InvalidArgumentException $e) {
return;
}
self::fallbackAwareAppendIfEnabled($alterEvent
->getPolicy(), 'connect-src', [
$dsn['server'],
str_replace('/store/', '/envelope/', $dsn['server']),
]);
}
private static function fallbackAwareAppendIfEnabled(Csp $policy, $directive, $value) {
if ($policy
->hasDirective($directive)) {
$policy
->appendDirective($directive, $value);
return;
}
foreach (Csp::getDirectiveFallbackList($directive) as $fallback) {
if ($policy
->hasDirective($fallback)) {
$policy
->setDirective($directive, $policy
->getDirective($fallback));
$policy
->appendDirective($directive, $value);
return;
}
}
}
}