aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-php-shim
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2026-06-24 22:05:15 +0900
committernsfisis <nsfisis@gmail.com>2026-06-24 22:11:34 +0900
commit555f5feb58fc89fd8a71c9a13a80ddf336e3afdc (patch)
treeb35360218e9dd70a28ed88b8a0694d0f09fb0609 /crates/shirabe-php-shim
parent7f810b1bb288445ee5376fada752e84ecb1ce211 (diff)
downloadphp-shirabe-555f5feb58fc89fd8a71c9a13a80ddf336e3afdc.tar.gz
php-shirabe-555f5feb58fc89fd8a71c9a13a80ddf336e3afdc.tar.zst
php-shirabe-555f5feb58fc89fd8a71c9a13a80ddf336e3afdc.zip
feat(php-shim): support JSON_PRETTY_PRINT in json_encode_ex
PHP's JSON_PRETTY_PRINT uses a 4-space indent, so use serde_json's PrettyFormatter with a 4-space indent when the flag is set.
Diffstat (limited to 'crates/shirabe-php-shim')
-rw-r--r--crates/shirabe-php-shim/src/json.rs16
1 files changed, 13 insertions, 3 deletions
diff --git a/crates/shirabe-php-shim/src/json.rs b/crates/shirabe-php-shim/src/json.rs
index 3d3ee5b..e2c48e4 100644
--- a/crates/shirabe-php-shim/src/json.rs
+++ b/crates/shirabe-php-shim/src/json.rs
@@ -29,9 +29,19 @@ pub fn json_encode_ex<T: serde::Serialize + ?Sized>(
// JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE set: forward slashes and non-ASCII
// characters are emitted verbatim. The two flags below re-apply PHP's default escaping when
// they are absent.
- // TODO(phase-c): other flags (e.g. JSON_PRETTY_PRINT, JSON_HEX_*, JSON_THROW_ON_ERROR) are not
- // handled yet; add them when a call site needs them.
- let mut s = serde_json::to_string(value)?;
+ // TODO(phase-c): other flags (e.g. JSON_HEX_*, JSON_THROW_ON_ERROR) are not handled yet; add
+ // them when a call site needs them.
+ let mut s = if flags & JSON_PRETTY_PRINT != 0 {
+ // PHP's JSON_PRETTY_PRINT uses a 4-space indent.
+ use serde::Serialize;
+ let mut buf = Vec::new();
+ let formatter = serde_json::ser::PrettyFormatter::with_indent(b" ");
+ let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
+ value.serialize(&mut ser)?;
+ String::from_utf8(buf)?
+ } else {
+ serde_json::to_string(value)?
+ };
if flags & JSON_UNESCAPED_SLASHES == 0 {
s = s.replace('/', "\\/");