@@ -37,15 +37,15 @@ public static function prepend(string $target, string $html): string
3737 */
3838 public static function replace (string $ target , string $ html , bool $ morph = false ): string
3939 {
40- return self ::custom ('replace ' , $ target , $ html , $ morph ? ['method=" morph" ' ] : []);
40+ return self ::custom ('replace ' , $ target , $ html , $ morph ? ['method ' => ' morph ' ] : []);
4141 }
4242
4343 /**
4444 * Updates the content of the element(s) designated by the target CSS selector.
4545 */
4646 public static function update (string $ target , string $ html , bool $ morph = false ): string
4747 {
48- return self ::custom ('update ' , $ target , $ html , $ morph ? ['method=" morph" ' ] : []);
48+ return self ::custom ('update ' , $ target , $ html , $ morph ? ['method ' => ' morph ' ] : []);
4949 }
5050
5151 /**
@@ -87,17 +87,33 @@ public static function refresh(?string $requestId = null): string
8787 }
8888
8989 /**
90- * @param array<string> $attr
90+ * Custom action and attributes.
91+ *
92+ * @param array<string, string|int|null> $attr
9193 */
9294 public static function custom (string $ action , string $ target , string $ html , array $ attr = []): string
9395 {
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+ }
96112
97113 return \sprintf (<<<EOHTML
98- <turbo-stream action="%s" targets="%s" %s>
114+ <turbo-stream%s>
99115 <template>%s</template>
100116 </turbo-stream>
101- EOHTML , $ action , htmlspecialchars ( $ target ), $ atrrString , $ html );
117+ EOHTML , $ attrString , $ html );
102118 }
103119}
0 commit comments