@@ -37,15 +37,15 @@ public static function prepend(string $target, string $html): string
37
37
*/
38
38
public static function replace (string $ target , string $ html , bool $ morph = false ): string
39
39
{
40
- return self ::custom ('replace ' , $ target , $ html , $ morph ? ['method=" morph" ' ] : []);
40
+ return self ::custom ('replace ' , $ target , $ html , $ morph ? ['method ' => ' morph ' ] : []);
41
41
}
42
42
43
43
/**
44
44
* Updates the content of the element(s) designated by the target CSS selector.
45
45
*/
46
46
public static function update (string $ target , string $ html , bool $ morph = false ): string
47
47
{
48
- return self ::custom ('update ' , $ target , $ html , $ morph ? ['method=" morph" ' ] : []);
48
+ return self ::custom ('update ' , $ target , $ html , $ morph ? ['method ' => ' morph ' ] : []);
49
49
}
50
50
51
51
/**
@@ -87,17 +87,33 @@ public static function refresh(?string $requestId = null): string
87
87
}
88
88
89
89
/**
90
- * @param array<string> $attr
90
+ * Custom action and attributes.
91
+ *
92
+ * @param array<string, string|int|null> $attr
91
93
*/
92
94
public static function custom (string $ action , string $ target , string $ html , array $ attr = []): string
93
95
{
94
- // Join array elements with a space and prepend a leading space
95
- $ atrrString = empty ($ attr ) ? '' : ' ' .implode (' ' , $ attr );
96
+ if (\array_key_exists ('action ' , $ attr ) || \array_key_exists ('targets ' , $ attr )) {
97
+ throw new \InvalidArgumentException ('The "action" and "targets" attributes are reserved and cannot be used. ' );
98
+ }
99
+
100
+ $ attr ['action ' ] = $ action ;
101
+ $ attr ['targets ' ] = $ target ;
102
+ $ attr = array_merge (['action ' => $ action , 'targets ' => $ target ], $ attr );
103
+
104
+ $ attrString = '' ;
105
+ foreach ($ attr as $ key => $ value ) {
106
+ if ($ value === null ) {
107
+ $ attrString .= sprintf (' %s ' , $ key );
108
+ }else {
109
+ $ attrString .= sprintf (' %s="%s" ' , $ key , is_string ($ value ) ? htmlspecialchars ($ value ) : $ value );
110
+ }
111
+ }
96
112
97
113
return \sprintf (<<<EOHTML
98
- <turbo-stream action="%s" targets="%s" %s>
114
+ <turbo-stream%s>
99
115
<template>%s</template>
100
116
</turbo-stream>
101
- EOHTML , $ action , htmlspecialchars ( $ target ), $ atrrString , $ html );
117
+ EOHTML , $ attrString , $ html );
102
118
}
103
119
}
0 commit comments