Skip to content

Commit 2f4773b

Browse files
committed
Helpers::getNonce() accepts optional $attr parameter to return HTML attribute string
1 parent 14eb8fc commit 2f4773b

3 files changed

Lines changed: 4 additions & 3 deletions

File tree

src/Tracy/Dumper/Dumper.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ public static function renderAssets(): void
171171

172172
$sent = true;
173173

174-
$nonceAttr = ($nonce = Helpers::getNonce()) ? ' nonce="' . Helpers::escapeHtml($nonce) . '"' : '';
174+
$nonceAttr = Helpers::getNonce(attr: true);
175175
$s = (Debugger::$showBar ? '' : file_get_contents(__DIR__ . '/../assets/reset.css'))
176176
. file_get_contents(__DIR__ . '/../assets/toggle.css')
177177
. file_get_contents(__DIR__ . '/assets/dumper-light.css')

src/Tracy/Helpers.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,10 @@ public static function isCli(): bool
333333

334334

335335
/** @internal */
336-
public static function getNonce(): ?string
336+
public static function getNonce(bool $attr = false): ?string
337337
{
338338
return preg_match('#^Content-Security-Policy(?:-Report-Only)?:.*\sscript-src(?:-elem)?\s+(?:[^;]+\s)?\'nonce-([\w+/]+=*)\'#mi', implode("\n", headers_list()), $m)
339-
? $m[1]
339+
? ($attr ? ' nonce="' . self::escapeHtml($m[1]) . '"' : $m[1])
340340
: null;
341341
}
342342

tests/Tracy/Helpers.getNonce().phpt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ test('no CSP header', function () {
2323
test('script-src with nonce', function () {
2424
header("Content-Security-Policy: script-src 'nonce-abc123='");
2525
Assert::same('abc123=', Helpers::getNonce());
26+
Assert::same(' nonce="abc123="', Helpers::getNonce(attr: true));
2627
});
2728

2829

0 commit comments

Comments
 (0)