From 5dc7e3cd69a0f1bd0f50a49990a954bc56a5d9b5 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 16 Feb 2021 14:13:12 -0500 Subject: [PATCH] Fixing null and false attributes --- src/Asset/TagRenderer.php | 8 +++++++- tests/Asset/TagRendererTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/Asset/TagRenderer.php b/src/Asset/TagRenderer.php index a3748a7e..5b6836f7 100644 --- a/src/Asset/TagRenderer.php +++ b/src/Asset/TagRenderer.php @@ -177,12 +177,18 @@ private function getEntrypointLookup(string $buildName): EntrypointLookupInterfa private function convertArrayToAttributes(array $attributesMap): string { + // remove attributes set specifically to false + $attributesMap = array_filter($attributesMap, function($value) { + return $value !== false; + }); + return implode(' ', array_map( function ($key, $value) { // allows for things like defer: true to only render "defer" - if ($value === true) { + if ($value === true || $value === null) { return $key; } + return sprintf('%s="%s"', $key, htmlentities($value)); }, array_keys($attributesMap), diff --git a/tests/Asset/TagRendererTest.php b/tests/Asset/TagRendererTest.php index e4fae3dd..b7008b0f 100644 --- a/tests/Asset/TagRendererTest.php +++ b/tests/Asset/TagRendererTest.php @@ -85,6 +85,35 @@ public function testRenderScriptTagsWithExtraAttributes() ); } + public function testRenderScriptTagsWithFalseyAttributes() + { + $entrypointLookup = $this->createMock(EntrypointLookupInterface::class); + $entrypointLookup->expects($this->once()) + ->method('getJavaScriptFiles') + ->willReturn(['/build/file1.js']); + $entrypointCollection = $this->createMock(EntrypointLookupCollection::class); + $entrypointCollection->expects($this->once()) + ->method('getEntrypointLookup') + ->willReturn($entrypointLookup); + + $packages = $this->createMock(Packages::class); + $packages->expects($this->once()) + ->method('getUrl') + ->willReturnCallback(function ($path) { + return 'http://localhost:8080' . $path; + }); + $renderer = new TagRenderer($entrypointCollection, $packages, [ + 'defer' => false, // false disables the attribute + 'async' => null, // null allows the attribute + ]); + + $output = $renderer->renderWebpackScriptTags('my_entry'); + $this->assertStringContainsString( + '', + $output + ); + } + public function testRenderScriptTagsDispatchesAnEvent() { $entrypointLookup = $this->createMock(EntrypointLookupInterface::class);