@@ -33,6 +33,11 @@ class Response implements ArrayAccess, Stringable
3333 */
3434 protected array $ decoded = [];
3535
36+ /**
37+ * The custom decode callback.
38+ */
39+ protected ?Closure $ decodeUsing = null ;
40+
3641 /**
3742 * The request cookies.
3843 */
@@ -64,7 +69,7 @@ public function body(): string
6469 public function json (?string $ key = null , mixed $ default = null ): mixed
6570 {
6671 if (! $ this ->decoded ) {
67- $ this ->decoded = json_decode ($ this ->body (), true ) ?? [] ;
72+ $ this ->decoded = $ this -> decode ($ this ->body ()) ;
6873 }
6974
7075 if (is_null ($ key )) {
@@ -88,7 +93,34 @@ public function json(?string $key = null, mixed $default = null): mixed
8893 */
8994 public function object (): array |object |null
9095 {
91- return json_decode ($ this ->body (), false );
96+ return $ this ->decode ($ this ->body (), true );
97+ }
98+
99+ /**
100+ * Set a custom decode callback.
101+ *
102+ * The callback will be invoked with the following parameters:
103+ * - string $body: The raw response body.
104+ * - bool $asObject: When true, the decoder should return an array of objects.
105+ */
106+ public function decodeUsing (?Closure $ callback ): static
107+ {
108+ $ this ->decodeUsing = $ callback ;
109+ $ this ->decoded = [];
110+
111+ return $ this ;
112+ }
113+
114+ /**
115+ * Decode the given response body.
116+ */
117+ protected function decode (string $ body , bool $ asObject = false ): array |object |null
118+ {
119+ if ($ this ->decodeUsing instanceof Closure) {
120+ return ($ this ->decodeUsing )($ body , $ asObject );
121+ }
122+
123+ return json_decode ($ body , ! $ asObject );
92124 }
93125
94126 /**
0 commit comments