src/Framework/Security/ContentSecurityPolicy/Computer/PageScriptCSPComputer.php line 25

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Framework\Security\ContentSecurityPolicy\Computer;
  4. use App\Repository\GoogleTagManagerRepository;
  5. class PageScriptCSPComputer
  6. {
  7.     public function __construct(
  8.         private readonly GoogleTagManagerRepository $tagManagerRepository,
  9.     ) {
  10.     }
  11.     public function computeShaSet(): array
  12.     {
  13.         $hashAlgos = ['sha256''sha384''sha512'];
  14.         $supportedAlgos array_filter($hashAlgos, fn (string $algo) => \in_array($algohash_algos(), true));
  15.         $usedAlgo reset($supportedAlgos);
  16.         if (false === $usedAlgo) {
  17.             return [];
  18.         }
  19.         $shaSet = [];
  20.         $scripts $this->tagManagerRepository->getAllScripts();
  21.         foreach ($scripts as $script) {
  22.             $htmlScript = (string) $script->getScript();
  23.             if (!== preg_match_all('/<script[^>]*+>/i'$htmlScript)) {
  24.                 continue;
  25.             }
  26.             preg_match('/^\s*+<script[^>]*+>(?<script>((?s).*))<\/script>\s*+$/i'$htmlScript$matches);
  27.             if (
  28.                 !\array_key_exists('script'$matches)
  29.                 || !\is_string($matches['script'])
  30.                 || '' === $matches['script']) {
  31.                 continue;
  32.             }
  33.             $hash hash($usedAlgo$matches[1], true);
  34.             $shaSet[] = sprintf('%s-%s'$usedAlgobase64_encode($hash));
  35.         }
  36.         return $shaSet;
  37.     }
  38. }