Skip to content

Commit a22f1e5

Browse files
committed
wip
1 parent d91c383 commit a22f1e5

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed
File renamed without changes.

src/SharedData.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,17 @@ public function toJson($options = 0): string
158158
return json_encode($this->get(), $options);
159159
}
160160

161-
public function render(): string
161+
public function render(array $options = []): string
162162
{
163-
return '<script>'
163+
$attributes = $options['attributes'] ?? [];
164+
165+
$attributeStrings = [];
166+
167+
foreach ($attributes as $attributeName => $attributeValue) {
168+
$attributeStrings[] = $attributeName.'="'.htmlentities($attributeValue, ENT_QUOTES, 'UTF-8', false).'"';
169+
}
170+
171+
return (count($attributeStrings) === 0 ? '<script>' : '<script '.implode(' ', $attributeStrings).'>')
164172
.'window["'.$this->getJsNamespace().'"]='.$this->toJson().';'
165173
.'window["sharedDataNamespace"]="'.$this->getJsNamespace().'";'
166174
.($this->getJsHelperEnabled() ? $this->getJsHelper().';' : '')

tests/SharedDataTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,26 @@ public function testRender()
162162
$this->assertSame($expectedHtml, $html);
163163
}
164164

165+
public function testRenderWithAttributes()
166+
{
167+
$this->sharedData->put([
168+
'scalar' => 'scalar-value',
169+
'array' => ['nested' => 'value'],
170+
]);
171+
172+
$this->sharedData->setJsNamespace('customShareDataNamespace');
173+
174+
$this->sharedData->setJsHelperName('customSharedFunctionName');
175+
176+
$this->sharedData->setJsHelperEnabled(true);
177+
178+
$html = $this->sharedData->render(['attributes' => ['nonce' => 'HELLOWORLD">', 'data-hello' => 'world']]);
179+
180+
$expectedHtml = '<script nonce="HELLOWORLD&quot;&gt;" data-hello="world">window["customShareDataNamespace"]={"scalar":"scalar-value","array":{"nested":"value"}};window["sharedDataNamespace"]="customShareDataNamespace";window["customSharedFunctionName"]=function(e){var n=void 0!==arguments[1]?arguments[1]:null;return[window.sharedDataNamespace].concat("string"==typeof e?e.split("."):[]).reduce(function(e,t){return e===n||"object"!=typeof e||void 0===e[t]?n:e[t]},window)};</script>';
181+
182+
$this->assertSame($expectedHtml, $html);
183+
}
184+
165185
public function testToString()
166186
{
167187
$this->sharedData->put('foo', 'bar');

0 commit comments

Comments
 (0)