Skip to content

Commit 3e1afe7

Browse files
author
Greg Bowler
authored
dataset camel case bugfix (#434)
* test: isolate bug #432 * fix: correct camel case for dataset attributes closes #432
1 parent 1f3a429 commit 3e1afe7

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

src/DOMStringMap.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,13 @@ public function __construct(
2424
}
2525

2626
public function __get(string $name):?string {
27+
$name = $this->correctCamelCase($name);
2728
$keyValuePairs = call_user_func($this->getterCallback);
2829
return $keyValuePairs[$name] ?? null;
2930
}
3031

3132
public function __set(string $name, string $value):void {
33+
$name = $this->correctCamelCase($name);
3234
$keyValuePairs = call_user_func($this->getterCallback);
3335
$keyValuePairs[$name] = $value;
3436
call_user_func($this->setterCallback, $keyValuePairs);
@@ -46,4 +48,18 @@ public function count():int {
4648
$keyValuePairs = call_user_func($this->getterCallback);
4749
return count($keyValuePairs);
4850
}
51+
52+
private function correctCamelCase(string $name):string {
53+
preg_match_all(
54+
'/((?:^|[A-Z])[a-z]+)/',
55+
$name,
56+
$matches
57+
);
58+
59+
$wordArray = [];
60+
foreach($matches[0] as $word) {
61+
array_push($wordArray, lcfirst($word));
62+
}
63+
return implode("-", $wordArray);
64+
}
4965
}

test/phpunit/DOMStringMapFactoryTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,19 @@ public function testCreateDatasetWithDataAttribute():void {
3838
self::assertEquals("php", $domStringMap->language);
3939
}
4040

41+
public function testSetCorrectsCamelCase():void {
42+
$document = new HTMLDocument();
43+
$element = $document->createElement("example-element");
44+
$domStringMap = DOMStringMapFactory::createDataset($element);
45+
self::assertCount(0, $element->attributes);
46+
$domStringMap->thisIsCamelCase = "test";
47+
self::assertCount(1, $element->attributes);
48+
$attribute = $element->attributes[0];
49+
self::assertSame("data-this-is-camel-case", $attribute->name);
50+
self::assertSame("test", $attribute->value);
51+
self::assertSame("test", $element->dataset->thisIsCamelCase);
52+
}
53+
4154
public function testCreateDatasetMutate():void {
4255
$attributeArray = [
4356
"id" => "example",

0 commit comments

Comments
 (0)