Skip to content

Commit

Permalink
dataset camel case bugfix (#434)
Browse files Browse the repository at this point in the history
* test: isolate bug #432

* fix: correct camel case for dataset attributes
closes #432
  • Loading branch information
g105b authored Mar 2, 2023
1 parent 1f3a429 commit 3e1afe7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/DOMStringMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
}
}
13 changes: 13 additions & 0 deletions test/phpunit/DOMStringMapFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 3e1afe7

Please sign in to comment.