diff --git a/src/Dto/StimulusControllersDto.php b/src/Dto/StimulusControllersDto.php index 973aa19a..a842f44f 100644 --- a/src/Dto/StimulusControllersDto.php +++ b/src/Dto/StimulusControllersDto.php @@ -36,7 +36,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; } } @@ -46,15 +46,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 @@ -82,4 +78,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)); + } }