Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dataset camel case bugfix #434

Merged
merged 2 commits into from
Mar 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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