From 0d27f32cc9df8776879ff4142a14945c2cba2ad1 Mon Sep 17 00:00:00 2001 From: Garion Herman Date: Tue, 24 Sep 2019 10:36:27 +1200 Subject: [PATCH] FIX Add 'legal empty attributes' to allow empty alt values on imgs In some situations, a caption is used in place of a value in the alt attribute, and in others an image may be cosmetic and not in need of an alt attribute value (though the alt attribute must still be rendered in this case). --- src/View/HTML.php | 15 ++++++++++++++- tests/php/View/HTMLTest.php | 10 ++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/View/HTML.php b/src/View/HTML.php index 220d0e955..7a5d2a72e 100644 --- a/src/View/HTML.php +++ b/src/View/HTML.php @@ -39,6 +39,16 @@ class HTML 'wbr' ]; + /** + * List of attributes that should be rendered even if they contain no value + * + * @config + * @var array + */ + private static $legal_empty_attributes = [ + 'alt', + ]; + /** * Construct and return HTML tag. * @@ -52,10 +62,13 @@ class HTML $tag = strtolower($tag); // Build list of arguments + $legalEmptyAttributes = static::config()->get('legal_empty_attributes'); $preparedAttributes = ''; foreach ($attributes as $attributeKey => $attributeValue) { + $whitelisted = in_array($attributeKey, $legalEmptyAttributes); + // Only set non-empty strings (ensures strlen(0) > 0) - if (strlen($attributeValue) > 0) { + if (strlen($attributeValue) > 0 || $whitelisted) { $preparedAttributes .= sprintf( ' %s="%s"', $attributeKey, diff --git a/tests/php/View/HTMLTest.php b/tests/php/View/HTMLTest.php index e363e3e1a..3c96e2d55 100644 --- a/tests/php/View/HTMLTest.php +++ b/tests/php/View/HTMLTest.php @@ -45,6 +45,16 @@ class HTMLTest extends SapphireTest $this->assertEquals('Some content!', $tag); } + public function testImgTag() + { + $tag = HTML::createTag('img', [ + 'src' => 'example.png', + 'alt' => '', + ]); + + $this->assertEquals('', $tag); + } + public function testVoidContentError() { $this->expectException(InvalidArgumentException::class);