#!/usr/bin/env php \[\n(.*?)^\1\],\n#ms', $content, $matches, PREG_OFFSET_CAPTURE ) !== 1) { fail('Could not find the \'sri\' array in ' . $file); } $indent = $matches[1][0] . ' '; $block = $matches[2][0]; $start = $matches[2][1]; $current = []; preg_match_all('#\'(js/[^\']+)\' *=> \'([^\']*)\',#', $block, $entries, PREG_SET_ORDER); foreach ($entries as $entry) { $current[$entry[1]] = $entry[2]; } // generate the new array content, aligning the arrows $width = max(array_map('strlen', array_keys($hashes))) + 2; $lines = ''; foreach ($hashes as $key => $hash) { $lines .= $indent . str_pad('\'' . $key . '\'', $width) . ' => \'' . $hash . '\',' . "\n"; } // report the differences $changes = 0; foreach ($hashes as $key => $hash) { if (!array_key_exists($key, $current)) { echo 'added: ', $key, PHP_EOL; ++$changes; } elseif ($current[$key] !== $hash) { echo 'updated: ', $key, PHP_EOL; ++$changes; } } foreach (array_diff_key($current, $hashes) as $key => $hash) { echo 'removed: ', $key, PHP_EOL; ++$changes; } if ($lines === $block) { echo 'SRI hashes are up to date.', PHP_EOL; exit(0); } if ($check) { fail('SRI hashes in ' . $file . ' are outdated, run bin/sri to update them.', 1); } if ($changes === 0) { echo 'reformatted the \'sri\' array', PHP_EOL; } $content = substr($content, 0, $start) . $lines . substr($content, $start + strlen($block)); if (file_put_contents($file, $content) === false) { fail('Could not write ' . $file); } /** * print an error to STDERR and exit * * @param string $message * @param int $code */ function fail(string $message, int $code = 2): void { fwrite(STDERR, $message . PHP_EOL); exit($code); }