Skip to content

Commit 65095da

Browse files
Merge pull request #9 from utopia-php/add-json-encode-option
Add json encode option
2 parents 46e791f + d46047d commit 65095da

1 file changed

Lines changed: 36 additions & 1 deletion

File tree

src/Client.php

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class Client
3535

3636
/** @var array<int> $retryStatusCodes */
3737
private array $retryStatusCodes = [500, 503];
38+
private mixed $jsonEncodeFlags;
3839

3940
/**
4041
* @param string $key
@@ -121,7 +122,41 @@ public function setMaxRetries(int $maxRetries): self
121122
$this->maxRetries = $maxRetries;
122123
return $this;
123124
}
125+
/**
126+
* set json_encode flags.
127+
*
128+
* @param array<int> $flags
129+
* @return self
130+
*/
131+
public function setJsonEncodeFlags(array $flags): self
132+
{
133+
$this->jsonEncodeFlags = implode('|', $flags);
134+
return $this;
135+
}
136+
137+
/**
138+
* Encode to json.
139+
*
140+
* @param array<string, mixed> $data
141+
* @return string
142+
* @throws \Exception If JSON encoding fails
143+
*/
144+
private function jsonEncode(array $data): string
145+
{
146+
$result = null;
124147

148+
if (!empty($this->jsonEncodeFlags)) {
149+
$result = json_encode($data, $this->jsonEncodeFlags);
150+
} else {
151+
$result = json_encode($data);
152+
}
153+
154+
if ($result === false) {
155+
throw new Exception('Failed to encode data to JSON: ' . json_last_error_msg());
156+
}
157+
158+
return $result;
159+
}
125160
/**
126161
* Set the retry delay in milliseconds.
127162
*
@@ -215,7 +250,7 @@ public function fetch(
215250

216251
if (isset($this->headers['content-type']) && $body !== null) {
217252
$body = match ($this->headers['content-type']) {
218-
self::CONTENT_TYPE_APPLICATION_JSON => json_encode($body),
253+
self::CONTENT_TYPE_APPLICATION_JSON => $this->jsonEncode($body),
219254
self::CONTENT_TYPE_APPLICATION_FORM_URLENCODED, self::CONTENT_TYPE_MULTIPART_FORM_DATA => self::flatten($body),
220255
self::CONTENT_TYPE_GRAPHQL => $body[0],
221256
default => $body,

0 commit comments

Comments
 (0)