You are here

class CspSubscriber in Blazy 8.2

Alter CSP policy for Blazy.

Hierarchy

  • class \Drupal\blazy\EventSubscriber\CspSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface

Expanded class hierarchy of CspSubscriber

1 string reference to 'CspSubscriber'
blazy.services.yml in ./blazy.services.yml
blazy.services.yml
1 service uses CspSubscriber
blazy.csp_subscriber in ./blazy.services.yml
Drupal\blazy\EventSubscriber\CspSubscriber

File

src/EventSubscriber/CspSubscriber.php, line 14

Namespace

Drupal\blazy\EventSubscriber
View source
class CspSubscriber implements EventSubscriberInterface {

  /**
   * The Library Dependency Resolver service.
   *
   * @var \Drupal\Core\Asset\LibraryDependencyResolverInterface
   */
  private $libraryDependencyResolver;

  /**
   * CspSubscriber constructor.
   *
   * @param \Drupal\Core\Asset\LibraryDependencyResolverInterface $libraryDependencyResolver
   *   The Library Dependency Resolver Service.
   */
  public function __construct(LibraryDependencyResolverInterface $libraryDependencyResolver) {
    $this->libraryDependencyResolver = $libraryDependencyResolver;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    if (class_exists(CspEvents::class)) {
      $events[CspEvents::POLICY_ALTER] = [
        'onCspPolicyAlter',
      ];
    }
    return $events;
  }

  /**
   * Alter CSP policy to allow data img-src.
   *
   * @param \Drupal\csp\Event\PolicyAlterEvent $alterEvent
   *   The Policy Alter event.
   */
  public function onCspPolicyAlter(PolicyAlterEvent $alterEvent) : void {
    $policy = $alterEvent
      ->getPolicy();
    $response = $alterEvent
      ->getResponse();
    if ($response instanceof AttachmentsInterface) {
      $attachments = $response
        ->getAttachments();
      $libraries = isset($attachments['library']) ? $this->libraryDependencyResolver
        ->getLibrariesWithDependencies($attachments['library']) : [];
      if (in_array('blazy/load', $libraries)) {
        $policy
          ->fallbackAwareAppendIfEnabled('img-src', [
          'data:',
        ]);
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CspSubscriber::$libraryDependencyResolver private property The Library Dependency Resolver service.
CspSubscriber::getSubscribedEvents public static function Returns an array of event names this subscriber wants to listen to.
CspSubscriber::onCspPolicyAlter public function Alter CSP policy to allow data img-src.
CspSubscriber::__construct public function CspSubscriber constructor.