Skip to content

Commit

Permalink
bug #208 Fix incorrect classes assignation and controller rendering (…
Browse files Browse the repository at this point in the history
…ker0x)

This PR was merged into the main branch.

Discussion
----------

Fix incorrect classes assignation and controller rendering

Fix incorrect class assignation mentioned by `@pbories` in #206 (comment)

Commits
-------

e716638 Fix incorrect classes assignation and controller rendering
  • Loading branch information
weaverryan committed Sep 26, 2023
2 parents 7e3b6f6 + e716638 commit 471ebbc
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/Dto/StimulusControllersDto.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function addController(string $controllerName, array $controllerValues =
foreach ($controllerClasses as $key => $class) {
$key = $this->escapeAsHtmlAttr($this->normalizeKeyName($key));

$this->values['data-'.$controllerName.'-'.$key.'-class'] = $class;
$this->classes['data-'.$controllerName.'-'.$key.'-class'] = $class;
}
}

Expand All @@ -49,15 +49,11 @@ public function __toString(): string
return '';
}

return rtrim(
'data-controller="'.implode(' ', $this->controllers).'" '.
implode(' ', array_map(function (string $attribute, string $value): string {
return $attribute.'="'.$this->escapeAsHtmlAttr($value).'"';
}, array_keys($this->values), $this->values)).' '.
implode(' ', array_map(function (string $attribute, string $value): string {
return $attribute.'="'.$this->escapeAsHtmlAttr($value).'"';
}, array_keys($this->classes), $this->classes))
);
return rtrim(implode(' ', array_filter([
'data-controller="'.implode(' ', $this->controllers).'"',
$this->formatDataAttribute($this->values),
$this->formatDataAttribute($this->classes),
])));
}

public function toArray(): array
Expand Down Expand Up @@ -85,4 +81,11 @@ private function normalizeKeyName(string $str): string
// Adapted from ByteString::snake
return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1-\2', $str));
}

private function formatDataAttribute(array $data): string
{
return implode(' ', array_map(function (string $attribute, string $value): string {
return $attribute.'="'.$this->escapeAsHtmlAttr($value).'"';
}, array_keys($data), $data));
}
}

0 comments on commit 471ebbc

Please sign in to comment.