From 3e1afe7b6d38e9968d400900a62cbe54753973a1 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Thu, 2 Mar 2023 18:40:07 +0000 Subject: [PATCH] dataset camel case bugfix (#434) * test: isolate bug #432 * fix: correct camel case for dataset attributes closes #432 --- src/DOMStringMap.php | 16 ++++++++++++++++ test/phpunit/DOMStringMapFactoryTest.php | 13 +++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/DOMStringMap.php b/src/DOMStringMap.php index b3c3cb34..d745ba18 100644 --- a/src/DOMStringMap.php +++ b/src/DOMStringMap.php @@ -24,11 +24,13 @@ public function __construct( } public function __get(string $name):?string { + $name = $this->correctCamelCase($name); $keyValuePairs = call_user_func($this->getterCallback); return $keyValuePairs[$name] ?? null; } public function __set(string $name, string $value):void { + $name = $this->correctCamelCase($name); $keyValuePairs = call_user_func($this->getterCallback); $keyValuePairs[$name] = $value; call_user_func($this->setterCallback, $keyValuePairs); @@ -46,4 +48,18 @@ public function count():int { $keyValuePairs = call_user_func($this->getterCallback); return count($keyValuePairs); } + + private function correctCamelCase(string $name):string { + preg_match_all( + '/((?:^|[A-Z])[a-z]+)/', + $name, + $matches + ); + + $wordArray = []; + foreach($matches[0] as $word) { + array_push($wordArray, lcfirst($word)); + } + return implode("-", $wordArray); + } } diff --git a/test/phpunit/DOMStringMapFactoryTest.php b/test/phpunit/DOMStringMapFactoryTest.php index 325fcbe2..f49ab2ec 100644 --- a/test/phpunit/DOMStringMapFactoryTest.php +++ b/test/phpunit/DOMStringMapFactoryTest.php @@ -38,6 +38,19 @@ public function testCreateDatasetWithDataAttribute():void { self::assertEquals("php", $domStringMap->language); } + public function testSetCorrectsCamelCase():void { + $document = new HTMLDocument(); + $element = $document->createElement("example-element"); + $domStringMap = DOMStringMapFactory::createDataset($element); + self::assertCount(0, $element->attributes); + $domStringMap->thisIsCamelCase = "test"; + self::assertCount(1, $element->attributes); + $attribute = $element->attributes[0]; + self::assertSame("data-this-is-camel-case", $attribute->name); + self::assertSame("test", $attribute->value); + self::assertSame("test", $element->dataset->thisIsCamelCase); + } + public function testCreateDatasetMutate():void { $attributeArray = [ "id" => "example",