CspSubscriber.php in Raven: Sentry Integration 3.x
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 Sentry\Dsn;
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(Dsn::class)) {
return;
}
try {
$dsn = Dsn::createFromString(empty($_SERVER['SENTRY_DSN']) ? $config
->get('public_dsn') : $_SERVER['SENTRY_DSN']);
} catch (\InvalidArgumentException $e) {
return;
}
self::fallbackAwareAppendIfEnabled($alterEvent
->getPolicy(), 'connect-src', [
$dsn
->getStoreApiEndpointUrl(),
$dsn
->getEnvelopeApiEndpointUrl(),
]);
}
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;
}
}
}
}