-
Notifications
You must be signed in to change notification settings - Fork 188
feat: add object param examples handling #1186
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Warning Rate limit exceeded@ChiragAgg5k has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 3 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
WalkthroughRefactors getParamExample across many SDK language classes (Dart, Deno, GraphQL, Kotlin, Node, Python, REST, ReactNative, Web, Ruby, DotNet, Go, Swift, PHP, ReactNative) to use a $hasExample guard and PHP 8 match-based returns, return type-specific defaults when examples are absent, normalize booleans/strings, and pretty-print object examples via JSON decode/encode with fallbacks. Kotlin now builds mapOf(...) from JSON examples. PHP::jsonToAssoc and Ruby::jsonToHash gain an optional indent parameter. Swift adds jsonToSwiftDict helper. No public/exported signatures (besides added optional indent params) were otherwise changed. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
example.php (1)
29-36
: Re-enable TLS verification for curl; current settings permit MITM.
These settings disable peer and host verification. At minimum, default to secure and allow opt-out via env for local testing.Suggested implementation (outside the changed hunk):
function getSSLPage($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_URL, $url); $insecure = getenv('ALLOW_INSECURE_SSL') === '1'; curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, !$insecure); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $insecure ? 0 : 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); if ($result === false) { throw new Exception('cURL error: ' . curl_error($ch)); } curl_close($ch); return $result; }
🧹 Nitpick comments (8)
src/SDK/Language/Dart.php (1)
256-271
: DRY the pretty-print logic across languages.
This same block appears in Web, Node, Python, etc. Consider a shared helper in the base Language to format and indent JSON safely.I can draft a small helper like:
- formatJsonMultiline(string $json, int $indentSpaces = 4): ?string
- Optionally a Python-specific variant to convert booleans/null tokens.
src/SDK/Language/ReactNative.php (1)
222-238
: Harden JSON handling; prefer explicit decode check and readable flagsUse json_last_error() and add UNESCAPED flags. Keeps behavior stable and output cleaner. Also centralizing this logic across languages would reduce duplication.
- case self::TYPE_OBJECT: - $formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT); - if ($formatted) { - $lines = explode("\n", $formatted); - $indentedLines = []; - foreach ($lines as $i => $line) { - if ($i === 0) { - $indentedLines[] = $line; // First line doesn't need extra indent - } else { - $indentedLines[] = ' ' . $line; // Add 4 spaces for indentation - } - } - $output .= implode("\n", $indentedLines); - } else { - $output .= $example; - } + case self::TYPE_OBJECT: + $decoded = json_decode($example, true); + if (json_last_error() === JSON_ERROR_NONE) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $lines = explode("\n", $formatted); + $indentedLines = []; + foreach ($lines as $i => $line) { + $indentedLines[] = $i === 0 ? $line : ' ' . $line; + } + $output .= implode("\n", $indentedLines); + } else { + $output .= $example; + } break;src/SDK/Language/REST.php (1)
107-122
: Indentation looks off (only last line indented); indent all lines after first by two spacesCurrent logic indents only the final line, which is inconsistent with other languages and likely unintentional.
- $formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT); - if ($formatted) { - $lines = explode("\n", $formatted); - $indentedLines = []; - foreach ($lines as $i => $line) { - if ($i === count($lines) - 1) { // just add space in last line - $indentedLines[] = ' ' . $line; - } else { - $indentedLines[] = $line; - } - } - $output .= implode("\n", $indentedLines); - } else { - $output .= $example; - } + $decoded = json_decode($example, true); + if (json_last_error() === JSON_ERROR_NONE) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $lines = explode("\n", $formatted); + $indentedLines = []; + foreach ($lines as $i => $line) { + $indentedLines[] = $i === 0 ? $line : ' ' . $line; // indent after first line + } + $output .= implode("\n", $indentedLines); + } else { + $output .= $example; + }src/SDK/Language/Deno.php (1)
195-211
: Prefer explicit decode error check and readable flagsSame as other languages: guard on json_last_error() and add UNESCAPED flags for cleaner output.
- case self::TYPE_OBJECT: - $formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT); - if ($formatted) { - $lines = explode("\n", $formatted); - $indentedLines = []; - foreach ($lines as $i => $line) { - if ($i === 0) { - $indentedLines[] = $line; // First line doesn't need extra indent - } else { - $indentedLines[] = ' ' . $line; // Add 4 spaces for indentation - } - } - $output .= implode("\n", $indentedLines); - } else { - $output .= $example; - } + case self::TYPE_OBJECT: + $decoded = json_decode($example, true); + if (json_last_error() === JSON_ERROR_NONE) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $lines = explode("\n", $formatted); + $indentedLines = []; + foreach ($lines as $i => $line) { + $indentedLines[] = $i === 0 ? $line : ' ' . $line; + } + $output .= implode("\n", $indentedLines); + } else { + $output .= $example; + } break;src/SDK/Language/PHP.php (4)
393-393
: Indentation off-by-one; bracket alignment.Item lines are indented by 8 spaces at indent 0, and the closing bracket doesn’t align with the opener.
Apply this diff:
@@ - $output = "[\n"; + $output = $baseIndent . "[\n"; @@ - $output .= ' ' . $itemIndent . '\'' . $key . '\' => ' . $value . $comma . "\n"; + $output .= $itemIndent . '\'' . $key . '\' => ' . $value . $comma . "\n"; @@ - $output .= $baseIndent . ' ]'; + $output .= $baseIndent . ']';Also applies to: 412-412, 415-415
399-409
: Prefer list syntax for sequential arrays.JSON often contains lists. Rendering lists as keyed arrays ('0' => ...) is noisy. Detect lists and print short form [value1, value2].
Apply this diff:
- if (is_array($node)) { - $value = $this->jsonToAssoc($node, $indent + 1); + if (is_array($node)) { + if (function_exists('array_is_list') && array_is_list($node)) { + $value = $this->listToPhp($node, $indent + 1); + } else { + $value = $this->jsonToAssoc($node, $indent + 1); + }Add this helper (outside the shown range):
protected function listToPhp(array $list, int $indent = 0): string { if (empty($list)) { return '[]'; } $baseIndent = str_repeat(' ', $indent); $itemIndent = str_repeat(' ', $indent + 1); $output = $baseIndent . "[\n"; $last = count($list) - 1; foreach ($list as $i => $item) { if (is_array($item)) { $value = (function_exists('array_is_list') && array_is_list($item)) ? $this->listToPhp($item, $indent + 1) : $this->jsonToAssoc($item, $indent + 1); } elseif (is_string($item)) { $value = var_export($item, true); } elseif (is_bool($item)) { $value = $item ? 'true' : 'false'; } elseif (is_null($item)) { $value = 'null'; } else { $value = $item; } $comma = ($i < $last) ? ',' : ''; $output .= $itemIndent . $value . $comma . "\n"; } $output .= $baseIndent . ']'; return $output; }
395-412
: Micro: avoid recomputing count() inside the loop.Small readability/perf win.
Apply this diff:
- $keys = array_keys($data); - foreach ($keys as $index => $key) { + $keys = array_keys($data); + $lastIndex = count($keys) - 1; + foreach ($keys as $index => $key) { @@ - $comma = ($index < count($keys) - 1) ? ',' : ''; + $comma = ($index < $lastIndex) ? ',' : '';
312-314
: Guard call sites against invalid JSON for TYPE_OBJECT.If the example/default isn’t valid JSON, json_decode returns null and (before making $data nullable) crashes. Even with the nullable fix, you may prefer an explicit fallback.
Outside the shown range, consider:
- case self::TYPE_OBJECT: - $output .= $this->jsonToAssoc(json_decode($default, true)); + case self::TYPE_OBJECT: + $assoc = json_decode($default, true); + $output .= is_array($assoc) ? $this->jsonToAssoc($assoc) : '[]';Also applies to: 363-364
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (11)
example.php
(1 hunks)src/SDK/Language/Dart.php
(1 hunks)src/SDK/Language/Deno.php
(1 hunks)src/SDK/Language/GraphQL.php
(1 hunks)src/SDK/Language/Kotlin.php
(1 hunks)src/SDK/Language/Node.php
(1 hunks)src/SDK/Language/PHP.php
(1 hunks)src/SDK/Language/Python.php
(1 hunks)src/SDK/Language/REST.php
(1 hunks)src/SDK/Language/ReactNative.php
(1 hunks)src/SDK/Language/Web.php
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
- GitHub Check: build (8.3, Swift56)
- GitHub Check: build (8.3, Ruby30)
- GitHub Check: build (8.3, AppleSwift56)
- GitHub Check: build (8.3, WebNode)
- GitHub Check: build (8.3, WebChromium)
- GitHub Check: build (8.3, Ruby27)
- GitHub Check: build (8.3, Python313)
- GitHub Check: build (8.3, KotlinJava8)
- GitHub Check: build (8.3, Python312)
- GitHub Check: build (8.3, PHP80)
- GitHub Check: build (8.3, PHP83)
- GitHub Check: build (8.3, Python311)
- GitHub Check: build (8.3, Node20)
- GitHub Check: build (8.3, Go112)
- GitHub Check: build (8.3, KotlinJava17)
- GitHub Check: build (8.3, FlutterBeta)
- GitHub Check: build (8.3, FlutterStable)
- GitHub Check: build (8.3, Deno1193)
- GitHub Check: build (8.3, Android5Java17)
- GitHub Check: build (8.3, Android14Java17)
🔇 Additional comments (2)
src/SDK/Language/PHP.php (2)
385-416
: Readable object example formatting: good change.Adding indentation support in jsonToAssoc improves the generated examples’ clarity, and the default argument keeps BC for call sites.
385-416
: No subclass overrides of jsonToAssoc detected
The only definition of jsonToAssoc is in src/SDK/Language/PHP.php; no overrides found by ripgrep.
protected function jsonToAssoc(array $data, int $indent = 0): string | ||
{ | ||
$output = '['; | ||
if (empty($data)) { | ||
return '[]'; | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Allow null input to prevent TypeError when json_decode fails.
json_decode(..., true) can return null; with a strict array type-hint this will fatally error before your empty() guard. Make $data nullable.
Apply this diff:
- protected function jsonToAssoc(array $data, int $indent = 0): string
+ protected function jsonToAssoc(?array $data, int $indent = 0): string
No further changes needed since the existing empty() check already returns '[]'.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
protected function jsonToAssoc(array $data, int $indent = 0): string | |
{ | |
$output = '['; | |
if (empty($data)) { | |
return '[]'; | |
} | |
protected function jsonToAssoc(?array $data, int $indent = 0): string | |
{ | |
if (empty($data)) { | |
return '[]'; | |
} | |
// ...rest of implementation... | |
} |
🤖 Prompt for AI Agents
In src/SDK/Language/PHP.php around lines 385 to 390, the jsonToAssoc signature
currently type-hints array which causes a TypeError when json_decode returns
null; change the parameter to allow null (make it nullable, e.g. ?array $data)
so the empty() guard can handle null and continue returning '[]' as before; no
other logic changes required.
$node = $data[$key]; | ||
|
||
if (is_array($node)) { | ||
$value = $this->jsonToAssoc($node, $indent + 1); | ||
} elseif (is_string($node)) { | ||
$value = '\'' . $node . '\''; | ||
} elseif (is_bool($node)) { | ||
$value = $node ? 'true' : 'false'; | ||
} elseif (is_null($node)) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Escape keys and string values to avoid broken PHP output.
Keys/values containing quotes or backslashes will currently produce invalid PHP. Escape both the array key and string values.
Apply this diff:
@@
- foreach ($keys as $index => $key) {
+ foreach ($keys as $index => $key) {
+ $escapedKey = strtr((string) $key, ["\\" => "\\\\", "'" => "\\'"]);
$node = $data[$key];
@@
- } elseif (is_string($node)) {
- $value = '\'' . $node . '\'';
+ } elseif (is_string($node)) {
+ // Safe scalar quoting
+ $value = var_export($node, true);
@@
- $comma = ($index < count($keys) - 1) ? ',' : '';
- $output .= ' ' . $itemIndent . '\'' . $key . '\' => ' . $value . $comma . "\n";
+ $comma = ($index < count($keys) - 1) ? ',' : '';
+ $output .= ' ' . $itemIndent . '\'' . $escapedKey . '\' => ' . $value . $comma . "\n";
Also applies to: 412-412
🤖 Prompt for AI Agents
In src/SDK/Language/PHP.php around lines 397-405 (and also at line 412), the
generated PHP breaks when keys or string values contain quotes/backslashes;
escape both the array key and any string value before emitting them. Replace
literal '\'' . $key . '\'' and '\'' . $node . '\'' with properly escaped
versions (e.g. '\'' . addslashes($key) . '\'' and '\'' . addslashes($node) .
'\'') or use var_export($key, true)/var_export($node, true) to produce safe PHP
literals; apply the same change at line 412 where keys/strings are emitted.
Ensure boolean/null/array branches remain unchanged.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR adds object parameter example handling by implementing pretty-printing and indentation for object parameters across all SDK language implementations. The changes standardize how object examples are formatted to improve readability in generated code snippets.
- Refactored parameter example generation methods to use modern PHP match expressions
- Added pretty-printing support for JSON object examples with proper indentation
- Standardized default values and file input examples across different language SDKs
Reviewed Changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated 4 comments.
Show a summary per file
File | Description |
---|---|
src/SDK/Language/Web.php | Added JSON pretty-printing with 4-space indentation for object examples |
src/SDK/Language/ReactNative.php | Added JSON pretty-printing with 4-space indentation for object examples |
src/SDK/Language/REST.php | Added JSON pretty-printing with custom regex for 2-space indentation |
src/SDK/Language/Python.php | Added JSON pretty-printing with boolean conversion and 4-space indentation |
src/SDK/Language/PHP.php | Enhanced jsonToAssoc method with proper multi-line formatting and indentation |
src/SDK/Language/Node.php | Added JSON pretty-printing with 4-space indentation for object examples |
src/SDK/Language/Kotlin.php | Added custom map formatting for object examples with proper Kotlin syntax |
src/SDK/Language/GraphQL.php | Added JSON pretty-printing with 8-space indentation for object examples |
src/SDK/Language/Deno.php | Added JSON pretty-printing with 4-space indentation for object examples |
src/SDK/Language/Dart.php | Added JSON pretty-printing with 4-space indentation for object examples |
Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.
$value = (is_array($node)) ? $this->jsonToAssoc($node) : $node; | ||
$output .= '\'' . $key . '\' => ' . ((is_string($node)) ? '\'' . $value . '\'' : $value) . (($key !== \array_key_last($data)) ? ', ' : ''); | ||
$comma = ($index < count($keys) - 1) ? ',' : ''; | ||
$output .= ' ' . $itemIndent . '\'' . $key . '\' => ' . $value . $comma . "\n"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Double indentation being applied. The line already includes $itemIndent
which contains the proper indentation, but then adds an additional ' '
prefix, resulting in incorrect formatting.
$output .= ' ' . $itemIndent . '\'' . $key . '\' => ' . $value . $comma . "\n"; | |
$output .= $itemIndent . '\'' . $key . '\' => ' . $value . $comma . "\n"; |
Copilot uses AI. Check for mistakes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks accurate, seems like double indent
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 11
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/SDK/Language/GraphQL.php (1)
33-35
: GraphQL boolean scalar should be ‘Boolean’, not ‘Bool’Using
Bool
is invalid per GraphQL spec.Suggested update (outside changed hunk):
- return 'Boolean';
♻️ Duplicate comments (6)
src/SDK/Language/Deno.php (1)
168-176
: LGTM on file default; resolves prior remark.The FILE default now uses InputFile.fromPath(...), which addresses the earlier feedback.
src/SDK/Language/Web.php (1)
149-155
: Guard against "null" on invalid JSON; decode once and check errors.Same issue noted previously: pretty-print only if decode succeeds; keep 4-space indentation for subsequent lines.
- self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", $formatted) - : $example, + self::TYPE_OBJECT => (function () use ($example) { + $decoded = json_decode($example, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + return preg_replace('/\n/', "\n ", $formatted); + } + return $example; + })(),src/SDK/Language/REST.php (1)
83-89
: String default uses JSON double quotes — good.Matches prior suggestion to prefer JSON-style "" in REST examples.
src/SDK/Language/Python.php (1)
335-342
: Fix JSON ‘null’ edge-case, safe boolean conversion, and string escaping
- Avoid emitting "null" when JSON decode fails; pretty-print only when decode succeeds.
- Parse
'false'
/'true'
strings correctly.- Don’t flip booleans inside quoted strings in objects.
- Escape quotes/backslashes in string examples.
- return match ($type) { - self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, - self::TYPE_BOOLEAN => ($example) ? 'True' : 'False', - self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", str_replace(['true', 'false'], ['True', 'False'], $formatted)) - : $example, - self::TYPE_STRING => "'{$example}'", - }; + return match ($type) { + self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, + self::TYPE_BOOLEAN => (function ($v) { + $b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + return ($b ?? (bool) $v) ? 'True' : 'False'; + })($example), + self::TYPE_OBJECT => (function ($v) { + $decoded = json_decode($v, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $formatted = preg_replace('/(?<!")\btrue\b(?!")/', 'True', $formatted); + $formatted = preg_replace('/(?<!")\bfalse\b(?!")/', 'False', $formatted); + return preg_replace('/\n/', "\n ", $formatted); + } + return $v; + })($example), + self::TYPE_STRING => "'" . str_replace(["\\", "'"], ["\\\\", "\\'"], (string) $example) . "'", + };src/SDK/Language/GraphQL.php (1)
139-141
: Consider keeping object examples as strings via GraphQL block strings (optional)If consumers expect a string for JSON scalars, wrap pretty JSON in a triple-quoted block string. Previously discussed; add only if needed.
src/SDK/Language/Node.php (1)
130-150
: Fix boolean truthiness, prevent "null" pretty-print on invalid/array input, and escape strings.
- Strings like "false"/"0" currently evaluate truthy, yielding 'true'.
- Object examples can pretty-print to literal "null" due to double-decode and lack of error checks; arrays as examples also break.
- String examples aren’t escaped, risking broken snippets.
Apply this consolidated patch:
@@ - $hasExample = !empty($example) || $example === 0 || $example === false; + // Presence check (handle '0', 'false', empty string) but ignore null + $hasExample = array_key_exists('example', $param) && $param['example'] !== null; @@ - return match ($type) { - self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, - self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', - self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", $formatted) - : $example, - self::TYPE_STRING => "'{$example}'", - }; + // Pre-compute object JSON once; guard against invalid JSON and non-string inputs + $objectJson = null; + if ($hasExample) { + if (is_string($example)) { + $decoded = json_decode($example, true); + if (json_last_error() === JSON_ERROR_NONE) { + $objectJson = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + } + } elseif (is_array($example)) { + $objectJson = json_encode($example, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + } + } + + return match ($type) { + // Ensure arrays passed as PHP arrays serialize to JSON + self::TYPE_ARRAY => is_string($example) ? $example : json_encode($example, JSON_UNESCAPED_SLASHES), + self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => is_string($example) ? $example : (string)$example, + // Robust boolean parsing for strings like "false", "true", "0", "1" + self::TYPE_BOOLEAN => (filter_var($example, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false) ? 'true' : 'false', + // Pretty-print valid JSON or array; otherwise fall back to original string/example + self::TYPE_OBJECT => $objectJson !== null + ? preg_replace('/\n/', "\n ", $objectJson) + : (is_string($example) ? $example : '{}'), + // Escape quotes and backslashes to keep generated code valid + self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'", + };
🧹 Nitpick comments (3)
src/SDK/Language/Deno.php (1)
179-186
: Be tolerant of boolean strings.If specs provide "true"/"false" as strings, current truthiness misclassifies "false". Consider a stricter parse.
- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', + self::TYPE_BOOLEAN => (filter_var($example, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false) ? 'true' : 'false',src/SDK/Language/Web.php (1)
149-151
: Optionally support boolean strings.- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', + self::TYPE_BOOLEAN => (filter_var($example, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false) ? 'true' : 'false',src/SDK/Language/REST.php (1)
94-95
: Optional: accept boolean strings.- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', + self::TYPE_BOOLEAN => (filter_var($example, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false) ? 'true' : 'false',
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (8)
src/SDK/Language/Dart.php
(1 hunks)src/SDK/Language/Deno.php
(1 hunks)src/SDK/Language/GraphQL.php
(1 hunks)src/SDK/Language/Node.php
(1 hunks)src/SDK/Language/Python.php
(1 hunks)src/SDK/Language/REST.php
(1 hunks)src/SDK/Language/ReactNative.php
(1 hunks)src/SDK/Language/Web.php
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/SDK/Language/Dart.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (17)
- GitHub Check: build (8.3, Swift56)
- GitHub Check: build (8.3, Ruby31)
- GitHub Check: build (8.3, AppleSwift56)
- GitHub Check: build (8.3, Ruby30)
- GitHub Check: build (8.3, Python313)
- GitHub Check: build (8.3, PHP83)
- GitHub Check: build (8.3, Python311)
- GitHub Check: build (8.3, Python312)
- GitHub Check: build (8.3, PHP80)
- GitHub Check: build (8.3, FlutterBeta)
- GitHub Check: build (8.3, Node16)
- GitHub Check: build (8.3, Node20)
- GitHub Check: build (8.3, KotlinJava11)
- GitHub Check: build (8.3, DotNet80)
- GitHub Check: build (8.3, FlutterStable)
- GitHub Check: build (8.3, Android14Java17)
- GitHub Check: build (8.3, Android5Java17)
🔇 Additional comments (1)
src/SDK/Language/Node.php (1)
134-140
: Defaults/readability LGTM.Nice use of match with sensible defaults for absent examples; the file placeholder is appropriate for Node SDK snippets.
return match ($type) { | ||
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | ||
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | ||
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | ||
? preg_replace('/\n/', "\n ", $formatted) | ||
: $example, | ||
self::TYPE_STRING => "'{$example}'", | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Handle string examples safely.
Unescaped quotes/backslashes in $example can break TS snippets. Escape them before wrapping in quotes.
- self::TYPE_STRING => "'{$example}'",
+ self::TYPE_STRING => "'" . str_replace(['\\', \"'\"], ['\\\\', \"\\\\'\"], (string)$example) . "'",
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | |
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | |
? preg_replace('/\n/', "\n ", $formatted) | |
: $example, | |
self::TYPE_STRING => "'{$example}'", | |
}; | |
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | |
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | |
? preg_replace('/\n/', "\n ", $formatted) | |
: $example, | |
self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'", | |
}; |
🤖 Prompt for AI Agents
In src/SDK/Language/Deno.php around lines 179 to 186, the TYPE_STRING branch
wraps $example in single quotes but does not escape single quotes or
backslashes, which can break generated TS snippets; update that branch to first
escape backslashes and single quotes in $example (e.g., replace "\" with "\\\\"
then "'" with "\\'") and then wrap the escaped value in single quotes so the
output is safe for TypeScript.
🛠️ Refactor suggestion
Guard against "null" on invalid JSON; decode once and check errors.
json_encode(json_decode(...)) can yield the literal "null" when $example is invalid JSON. Decode once, verify, then pretty-print and indent.
- return match ($type) {
- self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false',
- self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT))
- ? preg_replace('/\n/', "\n ", $formatted)
- : $example,
- self::TYPE_STRING => "'{$example}'",
- };
+ return match ($type) {
+ self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
+ self::TYPE_BOOLEAN => ($example) ? 'true' : 'false',
+ self::TYPE_OBJECT => (function () use ($example) {
+ $decoded = json_decode($example, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+ return preg_replace('/\n/', "\n ", $formatted);
+ }
+ return $example;
+ })(),
+ self::TYPE_STRING => "'" . str_replace(['\\', \"'\"], ['\\\\', \"\\\\'\"], (string)$example) . "'",
+ };
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | |
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | |
? preg_replace('/\n/', "\n ", $formatted) | |
: $example, | |
self::TYPE_STRING => "'{$example}'", | |
}; | |
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | |
self::TYPE_OBJECT => (function () use ($example) { | |
$decoded = json_decode($example, true); | |
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { | |
$formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); | |
return preg_replace('/\n/', "\n ", $formatted); | |
} | |
return $example; | |
})(), | |
self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\\\'"], (string)$example) . "'", | |
}; |
🤖 Prompt for AI Agents
In src/SDK/Language/Deno.php around lines 179 to 186, the current code calls
json_encode(json_decode($example, true)) which can produce the literal "null"
when $example is invalid JSON; modify it to json_decode once into a variable,
check json_last_error() (and that the decoded value is not null when input isn't
the literal "null"), then only call json_encode($decoded, JSON_PRETTY_PRINT) and
indent the result via preg_replace if decoding succeeded; if decoding failed,
fall back to the original $example string.
return match ($type) { | ||
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | ||
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | ||
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | ||
? preg_replace('/\n/', "\n ", $formatted) | ||
: $example, | ||
self::TYPE_STRING => "'{$example}'", | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Guard JSON pretty-print, normalize boolean string inputs, and use double-quoted GraphQL strings
- Avoid "null" when decode fails; pretty-print only on valid JSON.
- Parse
'false'
/'true'
strings correctly. - Use double quotes for GraphQL strings.
- return match ($type) {
- self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false',
- self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT))
- ? preg_replace('/\n/', "\n ", $formatted)
- : $example,
- self::TYPE_STRING => "'{$example}'",
- };
+ return match ($type) {
+ self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
+ self::TYPE_BOOLEAN => (function ($v) {
+ $b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
+ return ($b ?? (bool) $v) ? 'true' : 'false';
+ })($example),
+ self::TYPE_OBJECT => (function ($v) {
+ $decoded = json_decode($v, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
+ return preg_replace('/\n/', "\n ", $formatted);
+ }
+ return $v;
+ })($example),
+ self::TYPE_STRING => '"' . addslashes((string) $example) . '"',
+ };
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | |
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | |
? preg_replace('/\n/', "\n ", $formatted) | |
: $example, | |
self::TYPE_STRING => "'{$example}'", | |
}; | |
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => (function ($v) { | |
$b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); | |
return ($b ?? (bool) $v) ? 'true' : 'false'; | |
})($example), | |
self::TYPE_OBJECT => (function ($v) { | |
$decoded = json_decode($v, true); | |
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { | |
$formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
return preg_replace('/\n/', "\n ", $formatted); | |
} | |
return $v; | |
})($example), | |
self::TYPE_STRING => '"' . addslashes((string) $example) . '"', | |
}; |
src/SDK/Language/Python.php
Outdated
self::TYPE_ARRAY => '[]', | ||
self::TYPE_BOOLEAN => 'False', | ||
self::TYPE_FILE => 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')', | ||
self::TYPE_INTEGER, self::TYPE_NUMBER => '0', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Invalid Python call syntax for InputFile example
Named args in Python use =
, not :
. Current example is a syntax error.
- self::TYPE_FILE => 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')',
+ self::TYPE_FILE => "InputFile(path='./path-to-files/image.jpg', filename='image.jpg')",
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
self::TYPE_INTEGER, self::TYPE_NUMBER => '0', | |
self::TYPE_INTEGER, self::TYPE_NUMBER => '0', | |
self::TYPE_FILE => "InputFile(path='./path-to-files/image.jpg', filename='image.jpg')", |
🤖 Prompt for AI Agents
In src/SDK/Language/Python.php around line 329, the generated Python example for
InputFile uses invalid named-argument syntax with ":"; change the example to use
"=" for named arguments (e.g., name=value) so the produced Python code is
syntactically correct; update the template or mapping that emits the example to
replace ":" with "=" for Python named args and add a quick unit/test to assert
the output is valid Python if applicable.
src/SDK/Language/ReactNative.php
Outdated
return match ($type) { | ||
self::TYPE_ARRAY => '[]', | ||
self::TYPE_BOOLEAN => 'false', | ||
self::TYPE_FILE => 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
React Native file example should match TS shape, not InputFile()
getTypeName()
returns {name: string, type: string, size: number, uri: string}
, but the default example uses InputFile(...)
which isn’t valid TS/JS. Use an object literal.
- self::TYPE_FILE => 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')',
+ self::TYPE_FILE => "{ uri: 'file://path-to-files/image.jpg', name: 'image.jpg', type: 'image/jpeg', size: 0 }",
🏁 Script executed:
#!/bin/bash
# Inspect TYPE_FILE mapping in ReactNative language generator
rg -nP --context 5 "self::TYPE_FILE" -n src/SDK/Language/ReactNative.php
# Inspect getTypeName method to verify returned shape
rg -nP --context 5 "function getTypeName" -n src/SDK/Language/ReactNative.php
Length of output: 2058
Use a TS-compatible object literal for file examples instead of InputFile()
The default example for TYPE_FILE
must match the TS shape returned by getTypeName()
({ name: string; type: string; size: number; uri: string }
), not the PHP-style InputFile()
call. Replace it with, for example:
- self::TYPE_FILE => 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')',
+ self::TYPE_FILE => "{ uri: 'file://path-to-files/image.jpg', name: 'image.jpg', type: 'image/jpeg', size: 0 }",
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
self::TYPE_FILE => 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')', | |
// … other types … | |
self::TYPE_FILE => "{ uri: 'file://path-to-files/image.jpg', name: 'image.jpg', type: 'image/jpeg', size: 0 }", | |
// … following types … |
🤖 Prompt for AI Agents
In src/SDK/Language/ReactNative.php around line 199, the default example for
self::TYPE_FILE uses a PHP-style InputFile(...) call; replace it with a
TypeScript-compatible object literal matching the shape returned by
getTypeName() — e.g. an object with keys name (string), type (string), size
(number), and uri (string) — so the example value becomes a plain JS/TS object
literal like { name: 'image.jpg', type: 'image/jpeg', size: 12345, uri:
'./path-to-files/image.jpg' }.
return match ($type) { | ||
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | ||
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | ||
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | ||
? preg_replace('/\n/', "\n ", $formatted) | ||
: $example, | ||
self::TYPE_STRING => "'{$example}'", | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Guard JSON pretty-printing, normalize boolean examples, and escape strings
- Prevent emitting "null" when
$example
isn’t valid JSON. - Treat
'false'
/'true'
strings correctly. - Escape single quotes/backslashes in string examples.
- return match ($type) {
- self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false',
- self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT))
- ? preg_replace('/\n/', "\n ", $formatted)
- : $example,
- self::TYPE_STRING => "'{$example}'",
- };
+ return match ($type) {
+ self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
+ self::TYPE_BOOLEAN => (function ($v) {
+ $b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
+ return ($b ?? (bool) $v) ? 'true' : 'false';
+ })($example),
+ self::TYPE_OBJECT => (function ($v) {
+ $decoded = json_decode($v, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
+ return preg_replace('/\n/', "\n ", $formatted);
+ }
+ return $v;
+ })($example),
+ self::TYPE_STRING => "'" . str_replace(["\\", "'"], ["\\\\", "\\'"], (string) $example) . "'",
+ };
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | |
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | |
? preg_replace('/\n/', "\n ", $formatted) | |
: $example, | |
self::TYPE_STRING => "'{$example}'", | |
}; | |
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => (function ($v) { | |
$b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); | |
return ($b ?? (bool) $v) ? 'true' : 'false'; | |
})($example), | |
self::TYPE_OBJECT => (function ($v) { | |
$decoded = json_decode($v, true); | |
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { | |
$formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
return preg_replace('/\n/', "\n ", $formatted); | |
} | |
return $v; | |
})($example), | |
self::TYPE_STRING => "'" . str_replace(["\\", "'"], ["\\\\", "\\'"], (string) $example) . "'", | |
}; |
src/SDK/Language/REST.php
Outdated
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | ||
? (function () use ($formatted) { | ||
// Replace leading four spaces with two spaces for indentation | ||
$formatted = preg_replace('/^ /m', ' ', $formatted); | ||
// Add two spaces before the closing brace if it's on a new line at the end | ||
$formatted = preg_replace('/\n(?=[^}]*}$)/', "\n ", $formatted); | ||
return $formatted; | ||
})() | ||
: $example, | ||
self::TYPE_STRING => "\"{$example}\"", | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Avoid emitting "null" for invalid JSON; decode once, verify, then pretty-print.
Also unescape slashes and keep the 2-space normalization.
- self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT))
- ? (function () use ($formatted) {
- // Replace leading four spaces with two spaces for indentation
- $formatted = preg_replace('/^ /m', ' ', $formatted);
- // Add two spaces before the closing brace if it's on a new line at the end
- $formatted = preg_replace('/\n(?=[^}]*}$)/', "\n ", $formatted);
- return $formatted;
- })()
- : $example,
+ self::TYPE_OBJECT => (function () use ($example) {
+ $decoded = json_decode($example, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+ // Replace leading four spaces with two spaces for indentation
+ $formatted = preg_replace('/^ {4}/m', ' ', $formatted);
+ // Add two spaces before the closing brace if it's on a new line at the end
+ $formatted = preg_replace('/\n(?=[^}]*}$)/', "\n ", $formatted);
+ return $formatted;
+ }
+ return $example;
+ })(),
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | |
? (function () use ($formatted) { | |
// Replace leading four spaces with two spaces for indentation | |
$formatted = preg_replace('/^ /m', ' ', $formatted); | |
// Add two spaces before the closing brace if it's on a new line at the end | |
$formatted = preg_replace('/\n(?=[^}]*}$)/', "\n ", $formatted); | |
return $formatted; | |
})() | |
: $example, | |
self::TYPE_STRING => "\"{$example}\"", | |
}; | |
self::TYPE_OBJECT => (function () use ($example) { | |
$decoded = json_decode($example, true); | |
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { | |
$formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); | |
// Replace leading four spaces with two spaces for indentation | |
$formatted = preg_replace('/^ {4}/m', ' ', $formatted); | |
// Add two spaces before the closing brace if it's on a new line at the end | |
$formatted = preg_replace('/\n(?=[^}]*}$)/', "\n ", $formatted); | |
return $formatted; | |
} | |
return $example; | |
})(), | |
self::TYPE_STRING => "\"{$example}\"", |
🤖 Prompt for AI Agents
In src/SDK/Language/REST.php around lines 95 to 105, the current logic decodes
and re-encodes inline which can emit the string "null" for invalid JSON; instead
decode once into a variable, check json_last_error() === JSON_ERROR_NONE, and
only then json_encode the decoded data with JSON_PRETTY_PRINT |
JSON_UNESCAPED_SLASHES; if decoding fails return the original $example
unchanged. After successful encoding apply the existing two-space normalization
(preg_replace to convert four-space indents to two and the closing-brace
spacing) before returning the formatted string.
return $formatted; | ||
})() | ||
: $example, | ||
self::TYPE_STRING => "\"{$example}\"", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Escape string examples using JSON encoding.
Prevents broken JSON when $example contains quotes or control chars.
- self::TYPE_STRING => "\"{$example}\"",
+ self::TYPE_STRING => json_encode((string)$example, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
self::TYPE_STRING => "\"{$example}\"", | |
self::TYPE_STRING => json_encode((string)$example, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), |
🤖 Prompt for AI Agents
In src/SDK/Language/REST.php around line 104, the string example is inserted
with manual quotes ("{$example}") which breaks JSON if $example contains quotes
or control characters; replace that with using json_encode($example) so the
example is properly escaped and valid JSON (e.g., set the array entry to
json_encode($example) instead of building quotes manually).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (4)
src/SDK/Language/ReactNative.php (2)
193-204
: Fix TYPE_FILE default for RN and make hasExample robust
- Default for files should be a TS-compatible object literal matching getTypeName(), not InputFile.fromPath(...).
- Current presence check treats string '0' as "no example". Use a key-existence check instead.
Apply:
- $hasExample = !empty($example) || $example === 0 || $example === false; + $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null; - return match ($type) { + return match ($type) { self::TYPE_ARRAY => '[]', self::TYPE_BOOLEAN => 'false', - self::TYPE_FILE => 'InputFile.fromPath(\'/path/to/file\', \'filename\')', + self::TYPE_FILE => "{ uri: 'file://path-to-files/image.jpg', name: 'image.jpg', type: 'image/jpeg', size: 0 }", self::TYPE_INTEGER, self::TYPE_NUMBER => '0', self::TYPE_OBJECT => '{}', self::TYPE_STRING => "''", };
206-213
: Guard JSON pretty-print, escape strings, and parse booleans reliably across all SDK generators--- a/src/SDK/Language/ReactNative.php +++ b/src/SDK/Language/ReactNative.php @@ Lines 206-213 - return match ($type) { - self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, - self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', - self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", $formatted) - : $example, - self::TYPE_STRING => "'{$example}'", - }; + return match ($type) { + self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, + self::TYPE_BOOLEAN => (function ($v) { + $b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + return ($b ?? (bool) $v) ? 'true' : 'false'; + })($example), + self::TYPE_OBJECT => (function ($v) { + $decoded = json_decode($v, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + return preg_replace('/\n/', "\n ", $formatted); + } + return $v; + })($example), + self::TYPE_STRING => "'" . str_replace(["\\", "'"], ["\\\\", "\\'"], (string) $example) . "'", + };
- Mirror this refactor in Web.php (line 141), Node.php (136), Deno.php (172), Kotlin.php (205), and Swift.php (404) to ensure consistent boolean parsing, JSON handling, and string escaping in all language templates.
src/SDK/Language/Web.php (2)
135-146
: Use Web-native File default and fix hasExample semantics
- Browser SDK should default to a File instance, not InputFile.fromPath(...).
- Treat '0' string as a valid example by checking key existence.
- $hasExample = !empty($example) || $example === 0 || $example === false; + $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null; - return match ($type) { + return match ($type) { self::TYPE_ARRAY => '[]', self::TYPE_BOOLEAN => 'false', - self::TYPE_FILE => 'InputFile.fromPath(\'/path/to/file\', \'filename\')', + self::TYPE_FILE => "new File([], 'image.jpg')", self::TYPE_INTEGER, self::TYPE_NUMBER => '0', self::TYPE_OBJECT => '{}', self::TYPE_STRING => "''", };
148-155
: Harden object formatting and string/boolean handling
- Guard JSON decode to avoid emitting "null".
- Escape string examples.
- Parse boolean-like strings safely.
- return match ($type) { - self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, - self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', - self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", $formatted) - : $example, - self::TYPE_STRING => "'{$example}'", - }; + return match ($type) { + self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, + self::TYPE_BOOLEAN => (function ($v) { + $b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + return ($b ?? (bool) $v) ? 'true' : 'false'; + })($example), + self::TYPE_OBJECT => (function ($v) { + $decoded = json_decode($v, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + return preg_replace('/\n/', "\n ", $formatted); + } + return $v; + })($example), + self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string) $example) . "'", + };
🧹 Nitpick comments (1)
src/SDK/Language/Python.php (1)
322-333
: Presence check should not treat '0' as emptyUse key-existence + non-empty string/null check to keep '0' as a valid example.
- $hasExample = !empty($example) || $example === 0 || $example === false; + $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
src/SDK/Language/Python.php
(1 hunks)src/SDK/Language/ReactNative.php
(1 hunks)src/SDK/Language/Web.php
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
- GitHub Check: build (8.3, DartStable)
- GitHub Check: build (8.3, WebChromium)
- GitHub Check: build (8.3, Go112)
- GitHub Check: build (8.3, Python313)
return match ($type) { | ||
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | ||
self::TYPE_BOOLEAN => ($example) ? 'True' : 'False', | ||
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | ||
? preg_replace('/\n/', "\n ", str_replace(['true', 'false'], ['True', 'False'], $formatted)) | ||
: $example, | ||
self::TYPE_STRING => "'{$example}'", | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Guard JSON formatting, avoid flipping booleans inside strings, and escape
- Decode once; only pretty-print when decode succeeds.
- Replace true/false tokens with Python’s True/False using a regex that skips quoted strings.
- Escape quotes/backslashes in string examples.
- Parse boolean-like strings robustly.
- return match ($type) {
- self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
- self::TYPE_BOOLEAN => ($example) ? 'True' : 'False',
- self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT))
- ? preg_replace('/\n/', "\n ", str_replace(['true', 'false'], ['True', 'False'], $formatted))
- : $example,
- self::TYPE_STRING => "'{$example}'",
- };
+ return match ($type) {
+ self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
+ self::TYPE_BOOLEAN => (function ($v) {
+ $b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
+ return ($b ?? (bool) $v) ? 'True' : 'False';
+ })($example),
+ self::TYPE_OBJECT => (function ($v) {
+ $decoded = json_decode($v, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
+ // Convert JSON boolean tokens to Python while skipping quoted strings
+ $formatted = preg_replace('/(?<!\")\\btrue\\b(?!\")/', 'True', $formatted);
+ $formatted = preg_replace('/(?<!\")\\bfalse\\b(?!\")/', 'False', $formatted);
+ return preg_replace('/\n/', "\n ", $formatted);
+ }
+ return $v;
+ })($example),
+ self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string) $example) . "'",
+ };
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'True' : 'False', | |
self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | |
? preg_replace('/\n/', "\n ", str_replace(['true', 'false'], ['True', 'False'], $formatted)) | |
: $example, | |
self::TYPE_STRING => "'{$example}'", | |
}; | |
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => (function ($v) { | |
$b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); | |
return ($b ?? (bool) $v) ? 'True' : 'False'; | |
})($example), | |
self::TYPE_OBJECT => (function ($v) { | |
$decoded = json_decode($v, true); | |
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { | |
$formatted = json_encode( | |
$decoded, | |
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | |
); | |
// Convert JSON boolean tokens to Python while skipping quoted strings | |
$formatted = preg_replace('/(?<!")\\btrue\\b(?!")/', 'True', $formatted); | |
$formatted = preg_replace('/(?<!")\\bfalse\\b(?!")/', 'False', $formatted); | |
return preg_replace('/\n/', "\n ", $formatted); | |
} | |
return $v; | |
})($example), | |
self::TYPE_STRING => "'" . str_replace( | |
['\\', "'"], | |
['\\\\', "\\'"], | |
(string) $example | |
) . "'", | |
}; |
🤖 Prompt for AI Agents
In src/SDK/Language/Python.php around lines 335 to 342, the JSON/object/string
example handling needs hardening: decode the example once and only pretty-print
when json_decode succeeds (fall back to original example otherwise); when
converting JSON booleans to Python booleans, perform a regex replacement that
skips matches inside quotes (so you don't flip tokens inside string values); for
string examples escape backslashes and single quotes before wrapping in single
quotes; and treat boolean-like string examples ('true'/'false' case-insensitive)
by mapping them to Python True/False rather than using PHP truthiness. Ensure
the code branches cover array/file/integer/number/boolean/object/string per type
and return the properly escaped/converted example.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
♻️ Duplicate comments (2)
src/SDK/Language/Web.php (1)
148-156
: Guard JSON decode, preserve '{}' vs '[]', unescape slashes, and escape strings.Invalid JSON currently yields "null", and '{}' turns into '[]'. Also string examples aren’t escaped.
- self::TYPE_ARRAY, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, - self::TYPE_FILE => 'document.getElementById(\'uploader/\').files[0]', - self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', - self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", $formatted) - : $example, - self::TYPE_STRING => "'{$example}'", + self::TYPE_ARRAY, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, + self::TYPE_FILE => 'new File([], \'image.jpg\')', + self::TYPE_BOOLEAN => (is_string($example) + ? (in_array(strtolower(trim((string)$example)), ['true','1','yes','on'], true) ? 'true' : 'false') + : ($example ? 'true' : 'false')), + self::TYPE_OBJECT => (function ($v) { + $decoded = json_decode($v, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + if ($v === '{}') { return '{}'; } + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + return preg_replace('/\n/', "\n ", $formatted); + } + return $v; + })($example), + self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'",src/SDK/Language/Python.php (1)
334-341
: Harden object pretty-printing, robust boolean parsing, and escape strings.Avoid emitting "null" on decode failure, keep '{}' as '{}', don’t flip booleans inside strings, and escape quotes/backslashes.
- return match ($type) { - self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, - self::TYPE_BOOLEAN => ($example) ? 'True' : 'False', - self::TYPE_OBJECT => ($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", str_replace(['true', 'false'], ['True', 'False'], $formatted)) - : $example, - self::TYPE_STRING => "'{$example}'", - }; + return match ($type) { + self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, + self::TYPE_BOOLEAN => (function ($v) { + if (is_string($v)) { + $lv = strtolower(trim($v)); + if (in_array($lv, ['true','1','yes','on'], true)) return 'True'; + if (in_array($lv, ['false','0','no','off'], true)) return 'False'; + } + return $v ? 'True' : 'False'; + })($example), + self::TYPE_OBJECT => (function ($v) { + $decoded = json_decode($v, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + if ($v === '{}') { return '{}'; } + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + // Replace JSON boolean tokens to Python booleans, skipping inside quotes + $formatted = preg_replace('/(?<!")\btrue\b(?!")/i', 'True', $formatted); + $formatted = preg_replace('/(?<!")\bfalse\b(?!")/i', 'False', $formatted); + return preg_replace('/\n/', "\n ", $formatted); + } + return $v; + })($example), + self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'", + };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (8)
src/SDK/Language/Dart.php
(1 hunks)src/SDK/Language/Deno.php
(1 hunks)src/SDK/Language/GraphQL.php
(1 hunks)src/SDK/Language/Kotlin.php
(1 hunks)src/SDK/Language/Node.php
(1 hunks)src/SDK/Language/Python.php
(1 hunks)src/SDK/Language/REST.php
(1 hunks)src/SDK/Language/Web.php
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- src/SDK/Language/Deno.php
- src/SDK/Language/Kotlin.php
- src/SDK/Language/REST.php
- src/SDK/Language/GraphQL.php
- src/SDK/Language/Node.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (17)
- GitHub Check: build (8.3, AppleSwift56)
- GitHub Check: build (8.3, WebNode)
- GitHub Check: build (8.3, Ruby30)
- GitHub Check: build (8.3, Swift56)
- GitHub Check: build (8.3, WebChromium)
- GitHub Check: build (8.3, Python311)
- GitHub Check: build (8.3, Python310)
- GitHub Check: build (8.3, PHP83)
- GitHub Check: build (8.3, DotNet80)
- GitHub Check: build (8.3, Node20)
- GitHub Check: build (8.3, PHP80)
- GitHub Check: build (8.3, FlutterBeta)
- GitHub Check: build (8.3, DartStable)
- GitHub Check: build (8.3, KotlinJava17)
- GitHub Check: build (8.3, Android5Java17)
- GitHub Check: build (8.3, FlutterStable)
- GitHub Check: build (8.3, Android14Java17)
$hasExample = !empty($example) || $example === 0 || $example === false; | ||
|
||
if (empty($example) && $example !== 0 && $example !== false) { | ||
switch ($type) { | ||
case self::TYPE_FILE: | ||
$output .= 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')'; | ||
break; | ||
case self::TYPE_NUMBER: | ||
case self::TYPE_INTEGER: | ||
$output .= '0'; | ||
break; | ||
case self::TYPE_BOOLEAN: | ||
$output .= 'false'; | ||
break; | ||
case self::TYPE_STRING: | ||
$output .= "''"; | ||
break; | ||
case self::TYPE_OBJECT: | ||
$output .= '{}'; | ||
break; | ||
case self::TYPE_ARRAY: | ||
$output .= '[]'; | ||
break; | ||
} | ||
} else { | ||
switch ($type) { | ||
case self::TYPE_OBJECT: | ||
case self::TYPE_FILE: | ||
case self::TYPE_NUMBER: | ||
case self::TYPE_INTEGER: | ||
case self::TYPE_ARRAY: | ||
$output .= $example; | ||
break; | ||
case self::TYPE_BOOLEAN: | ||
$output .= ($example) ? 'true' : 'false'; | ||
break; | ||
case self::TYPE_STRING: | ||
$output .= "'{$example}'"; | ||
break; | ||
} | ||
if (!$hasExample) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Fix $hasExample to not drop "0" (string).
empty('0') is true in PHP; this loses valid examples.
- $hasExample = !empty($example) || $example === 0 || $example === false;
+ $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null;
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
$hasExample = !empty($example) || $example === 0 || $example === false; | |
if (empty($example) && $example !== 0 && $example !== false) { | |
switch ($type) { | |
case self::TYPE_FILE: | |
$output .= 'InputFile(path: \'./path-to-files/image.jpg\', filename: \'image.jpg\')'; | |
break; | |
case self::TYPE_NUMBER: | |
case self::TYPE_INTEGER: | |
$output .= '0'; | |
break; | |
case self::TYPE_BOOLEAN: | |
$output .= 'false'; | |
break; | |
case self::TYPE_STRING: | |
$output .= "''"; | |
break; | |
case self::TYPE_OBJECT: | |
$output .= '{}'; | |
break; | |
case self::TYPE_ARRAY: | |
$output .= '[]'; | |
break; | |
} | |
} else { | |
switch ($type) { | |
case self::TYPE_OBJECT: | |
case self::TYPE_FILE: | |
case self::TYPE_NUMBER: | |
case self::TYPE_INTEGER: | |
case self::TYPE_ARRAY: | |
$output .= $example; | |
break; | |
case self::TYPE_BOOLEAN: | |
$output .= ($example) ? 'true' : 'false'; | |
break; | |
case self::TYPE_STRING: | |
$output .= "'{$example}'"; | |
break; | |
} | |
if (!$hasExample) { | |
$hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null; | |
if (!$hasExample) { |
🤖 Prompt for AI Agents
In src/SDK/Language/Dart.php around lines 229 to 231, the current $hasExample
check uses empty() which treats the string "0" as empty and drops valid
examples; replace the empty-based logic with a strict check that treats non-null
and non-empty-string values as present (so "0", 0, and false are considered
valid examples) by updating the condition accordingly.
return match ($type) { | ||
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | ||
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | ||
self::TYPE_OBJECT => ($decoded = json_decode($example, true)) !== null | ||
? (empty($decoded) && $example === '{}' | ||
? '{}' | ||
: preg_replace('/\n/', "\n ", json_encode($decoded, JSON_PRETTY_PRINT))) | ||
: $example, | ||
self::TYPE_STRING => "'{$example}'", | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Guard JSON decode, keep '{}' literal, add UNESCAPED_SLASHES, robust bools, and escape strings.
Prevents "null" output and misformatting; also ensures safe string literals.
- return match ($type) {
- self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false',
- self::TYPE_OBJECT => ($decoded = json_decode($example, true)) !== null
- ? (empty($decoded) && $example === '{}'
- ? '{}'
- : preg_replace('/\n/', "\n ", json_encode($decoded, JSON_PRETTY_PRINT)))
- : $example,
- self::TYPE_STRING => "'{$example}'",
- };
+ return match ($type) {
+ self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example,
+ self::TYPE_BOOLEAN => (is_string($example)
+ ? (in_array(strtolower(trim((string)$example)), ['true','1','yes','on'], true) ? 'true' : 'false')
+ : ($example ? 'true' : 'false')),
+ self::TYPE_OBJECT => (function ($v) {
+ $decoded = json_decode($v, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ if ($v === '{}') { return '{}'; }
+ $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+ return preg_replace('/\n/', "\n ", $formatted);
+ }
+ return $v;
+ })($example),
+ self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'",
+ };
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', | |
self::TYPE_OBJECT => ($decoded = json_decode($example, true)) !== null | |
? (empty($decoded) && $example === '{}' | |
? '{}' | |
: preg_replace('/\n/', "\n ", json_encode($decoded, JSON_PRETTY_PRINT))) | |
: $example, | |
self::TYPE_STRING => "'{$example}'", | |
}; | |
return match ($type) { | |
self::TYPE_ARRAY, self::TYPE_FILE, self::TYPE_INTEGER, self::TYPE_NUMBER => $example, | |
self::TYPE_BOOLEAN => (is_string($example) | |
? (in_array(strtolower(trim((string)$example)), ['true','1','yes','on'], true) ? 'true' : 'false') | |
: ($example ? 'true' : 'false')), | |
self::TYPE_OBJECT => (function ($v) { | |
$decoded = json_decode($v, true); | |
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { | |
if ($v === '{}') { return '{}'; } | |
$formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); | |
return preg_replace('/\n/', "\n ", $formatted); | |
} | |
return $v; | |
})($example), | |
self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'", | |
}; |
🤖 Prompt for AI Agents
In src/SDK/Language/Dart.php around lines 242 to 251, the current match arm can
output null or misformatted JSON and unsafe string/boolean literals; update the
logic to: for TYPE_OBJECT, attempt json_decode($example, true) and check
json_last_error() (treat '{}' explicitly as the empty-object literal), when
successful re-encode with json_encode($decoded,
JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) and indent newlines, otherwise return
the original $example; for TYPE_BOOLEAN, consider string values like 'false'/'0'
as false and 'true'/'1' as true and return the literal 'true' or 'false'
accordingly; for TYPE_STRING, escape single quotes and backslashes in $example
before wrapping with single quotes to produce a safe Dart string literal.
$hasExample = !empty($example) || $example === 0 || $example === false; | ||
|
||
if (empty($example) && $example !== 0 && $example !== false) { | ||
switch ($type) { | ||
case self::TYPE_NUMBER: | ||
case self::TYPE_INTEGER: | ||
case self::TYPE_BOOLEAN: | ||
$output .= 'None'; | ||
break; | ||
case self::TYPE_STRING: | ||
$output .= "''"; | ||
break; | ||
case self::TYPE_ARRAY: | ||
$output .= '[]'; | ||
break; | ||
case self::TYPE_OBJECT: | ||
$output .= '{}'; | ||
break; | ||
case self::TYPE_FILE: | ||
$output .= "InputFile.from_path('file.png')"; | ||
break; | ||
} | ||
} else { | ||
switch ($type) { | ||
case self::TYPE_NUMBER: | ||
case self::TYPE_INTEGER: | ||
case self::TYPE_ARRAY: | ||
case self::TYPE_OBJECT: | ||
$output .= $example; | ||
break; | ||
case self::TYPE_BOOLEAN: | ||
$output .= ($example) ? 'True' : 'False'; | ||
break; | ||
case self::TYPE_STRING: | ||
$output .= "'{$example}'"; | ||
break; | ||
case self::TYPE_FILE: | ||
$output .= "InputFile.from_path('file.png')"; | ||
break; | ||
} | ||
if (!$hasExample) { | ||
return match ($type) { | ||
self::TYPE_ARRAY => '[]', | ||
self::TYPE_FILE => 'InputFile.from_path(\'file.png\')', | ||
self::TYPE_INTEGER, self::TYPE_NUMBER , self::TYPE_BOOLEAN => 'None', | ||
self::TYPE_OBJECT => '{}', | ||
self::TYPE_STRING => "''", | ||
}; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Correct example presence detection; honor "0" (string) and False.
empty()-style logic misclassifies "0". Use explicit checks.
- $hasExample = !empty($example) || $example === 0 || $example === false;
+ $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null;
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
$hasExample = !empty($example) || $example === 0 || $example === false; | |
if (empty($example) && $example !== 0 && $example !== false) { | |
switch ($type) { | |
case self::TYPE_NUMBER: | |
case self::TYPE_INTEGER: | |
case self::TYPE_BOOLEAN: | |
$output .= 'None'; | |
break; | |
case self::TYPE_STRING: | |
$output .= "''"; | |
break; | |
case self::TYPE_ARRAY: | |
$output .= '[]'; | |
break; | |
case self::TYPE_OBJECT: | |
$output .= '{}'; | |
break; | |
case self::TYPE_FILE: | |
$output .= "InputFile.from_path('file.png')"; | |
break; | |
} | |
} else { | |
switch ($type) { | |
case self::TYPE_NUMBER: | |
case self::TYPE_INTEGER: | |
case self::TYPE_ARRAY: | |
case self::TYPE_OBJECT: | |
$output .= $example; | |
break; | |
case self::TYPE_BOOLEAN: | |
$output .= ($example) ? 'True' : 'False'; | |
break; | |
case self::TYPE_STRING: | |
$output .= "'{$example}'"; | |
break; | |
case self::TYPE_FILE: | |
$output .= "InputFile.from_path('file.png')"; | |
break; | |
} | |
if (!$hasExample) { | |
return match ($type) { | |
self::TYPE_ARRAY => '[]', | |
self::TYPE_FILE => 'InputFile.from_path(\'file.png\')', | |
self::TYPE_INTEGER, self::TYPE_NUMBER , self::TYPE_BOOLEAN => 'None', | |
self::TYPE_OBJECT => '{}', | |
self::TYPE_STRING => "''", | |
}; | |
} | |
$hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null; | |
if (!$hasExample) { | |
return match ($type) { | |
self::TYPE_ARRAY => '[]', | |
self::TYPE_FILE => 'InputFile.from_path(\'file.png\')', | |
self::TYPE_INTEGER, | |
self::TYPE_NUMBER, | |
self::TYPE_BOOLEAN => 'None', | |
self::TYPE_OBJECT => '{}', | |
self::TYPE_STRING => "''", | |
}; | |
} |
🤖 Prompt for AI Agents
In src/SDK/Language/Python.php around lines 322 to 332, the example presence
check misclassifies the string "0" as empty; update the $hasExample condition to
explicitly treat the string "0" as a valid example (in addition to the existing
integer 0 and boolean false) so the branch correctly detects examples like "0".
$hasExample = !empty($example) || $example === 0 || $example === false; | ||
|
||
if (!$hasExample) { | ||
return match ($type) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Fix $hasExample: '0' (string) is treated as empty by empty().
The current guard drops legitimate "0" examples.
- $hasExample = !empty($example) || $example === 0 || $example === false;
+ $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null;
🤖 Prompt for AI Agents
In src/SDK/Language/Web.php around lines 135 to 138, the current $hasExample
uses empty() which treats the string "0" as empty and thus drops valid "0"
examples; change the condition to treat "0" as a valid example (e.g. replace the
empty() check with an explicit check that $example is not null and not an empty
string, while still allowing numeric 0, string "0", and boolean false as valid
examples).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/SDK/Language/Ruby.php (1)
309-311
: Guard json_decode() before calling jsonToHash to avoid TypeError on invalid JSON.json_decode may return null; the typed parameter array $data will fatal.
- $output .= $this->jsonToHash(json_decode($example, true)); + $decoded = json_decode($example, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $output .= $this->jsonToHash($decoded); + } else { + $output .= $example; + }
♻️ Duplicate comments (7)
src/SDK/Language/Web.php (4)
140-141
: Use a browser-native File placeholder; remove brittle DOM access.document.getElementById('uploader/') is invalid/brittle. Prefer a self-contained File instance.
- self::TYPE_FILE => 'document.getElementById(\'uploader/\').files[0]', + self::TYPE_FILE => 'new File([], \'image.jpg\')',- self::TYPE_FILE => 'document.getElementById(\'uploader/\').files[0]', + self::TYPE_FILE => 'new File([], \'image.jpg\')',Also applies to: 147-150
151-156
: Guard JSON decode to avoid emitting literal "null"; pretty-print only on success.Decode once, check json_last_error, and add UNESCAPED_SLASHES for readability.
- self::TYPE_OBJECT => ($example === '{}') - ? '{}' - : (($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) - ? preg_replace('/\n/', "\n ", $formatted) - : $example), + self::TYPE_OBJECT => (function ($v) { + if ($v === '{}') { return '{}'; } + $decoded = json_decode($v, true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $formatted = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + return preg_replace('/\n/', "\n ", $formatted); + } + return $v; + })((string)$example),
157-157
: Escape string examples to prevent broken snippets.Wrap with escaped content instead of raw interpolation.
- self::TYPE_STRING => "'{$example}'", + self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'",
135-138
: Treat "0" (string) as a valid example; replace empty() guard.empty('0') is true and drops legitimate examples.
- $hasExample = !empty($example) || $example === 0 || $example === false; + $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null;src/SDK/Language/Dart.php (3)
245-249
: Prefer UNESCAPED_SLASHES and decode-error check for object pretty-print.Avoids needless escaping and accidental "null".
- ? (empty($decoded) && $example === '{}' - ? '{}' - : preg_replace('/\n/', "\n ", json_encode($decoded, JSON_PRETTY_PRINT))) + ? (empty($decoded) && $example === '{}' + ? '{}' + : preg_replace('/\n/', "\n ", json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)))
244-251
: Harden boolean and string example handling; avoid broken literals.'false' (string) yields 'true', and unescaped quotes break snippets.
- self::TYPE_BOOLEAN => ($example) ? 'true' : 'false', + self::TYPE_BOOLEAN => (is_string($example) + ? (in_array(strtolower(trim((string)$example)), ['true','1','yes','on'], true) ? 'true' : 'false') + : ($example ? 'true' : 'false')), - self::TYPE_STRING => "'{$example}'", + self::TYPE_STRING => "'" . str_replace(['\\', "'"], ['\\\\', "\\'"], (string)$example) . "'",
229-233
: Treat "0" (string) as a valid example; replace empty() guard.empty('0') is true and drops legitimate examples.
- $hasExample = !empty($example) || $example === 0 || $example === false; + $hasExample = array_key_exists('example', $param) && $example !== '' && $example !== null;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (8)
src/SDK/Language/Dart.php
(1 hunks)src/SDK/Language/Deno.php
(1 hunks)src/SDK/Language/GraphQL.php
(1 hunks)src/SDK/Language/Node.php
(1 hunks)src/SDK/Language/REST.php
(1 hunks)src/SDK/Language/ReactNative.php
(1 hunks)src/SDK/Language/Ruby.php
(1 hunks)src/SDK/Language/Web.php
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- src/SDK/Language/ReactNative.php
- src/SDK/Language/GraphQL.php
- src/SDK/Language/Deno.php
- src/SDK/Language/REST.php
- src/SDK/Language/Node.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
- GitHub Check: build (8.3, Python313)
- GitHub Check: build (8.3, Ruby27)
- GitHub Check: build (8.3, WebNode)
- GitHub Check: build (8.3, Python311)
- GitHub Check: build (8.3, Python312)
- GitHub Check: build (8.3, Node20)
- GitHub Check: build (8.3, Node18)
- GitHub Check: build (8.3, KotlinJava11)
- GitHub Check: build (8.3, DotNet80)
- GitHub Check: build (8.3, DartBeta)
- GitHub Check: build (8.3, FlutterStable)
- GitHub Check: build (8.3, CLINode16)
- GitHub Check: build (8.3, Android14Java17)
- GitHub Check: build (8.3, Android5Java17)
protected function jsonToHash(array $data, int $indent = 0): string | ||
{ | ||
$output = '{'; | ||
if (empty($data)) { | ||
return '{}'; | ||
} | ||
|
||
$output = "{\n"; | ||
$indentStr = str_repeat(' ', $indent + 4); | ||
$keys = array_keys($data); | ||
|
||
foreach ($data as $key => $node) { | ||
$value = (is_array($node)) ? $this->jsonToHash($node) : $node; | ||
$output .= '"' . $key . '" => ' . ((is_string($node)) ? '"' . $value . '"' : $value) . (($key !== array_key_last($data)) ? ', ' : ''); | ||
if (is_array($node)) { | ||
$value = $this->jsonToHash($node, $indent + 1); | ||
} elseif (is_bool($node)) { | ||
$value = $node ? 'true' : 'false'; | ||
} elseif (is_string($node)) { | ||
$value = '"' . $node . '"'; | ||
} else { | ||
$value = $node; | ||
} | ||
|
||
$output .= $indentStr . '"' . $key . '" => ' . $value; | ||
|
||
// Add comma if not the last item | ||
if ($key !== end($keys)) { | ||
$output .= ','; | ||
} | ||
|
||
$output .= "\n"; | ||
} | ||
|
||
$output .= '}'; | ||
$output .= str_repeat(' ', $indent + 2) . '}'; | ||
|
||
return $output; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix Ruby hash serialization: escape strings/keys, handle nulls, and emit arrays as Ruby arrays.
Current code: treats JSON arrays as Hashes, doesn't escape quotes, and renders null as empty string. Indentation also looks asymmetric (+4 for items, +2 for close).
- protected function jsonToHash(array $data, int $indent = 0): string
+ protected function jsonToHash(array $data, int $indent = 0): string
{
- if (empty($data)) {
- return '{}';
- }
-
- $output = "{\n";
- $indentStr = str_repeat(' ', $indent + 4);
- $keys = array_keys($data);
-
- foreach ($data as $key => $node) {
- if (is_array($node)) {
- $value = $this->jsonToHash($node, $indent + 1);
- } elseif (is_bool($node)) {
- $value = $node ? 'true' : 'false';
- } elseif (is_string($node)) {
- $value = '"' . $node . '"';
- } else {
- $value = $node;
- }
-
- $output .= $indentStr . '"' . $key . '" => ' . $value;
-
- // Add comma if not the last item
- if ($key !== end($keys)) {
- $output .= ',';
- }
-
- $output .= "\n";
- }
-
- $output .= str_repeat(' ', $indent + 2) . '}';
+ if (empty($data)) {
+ return '{}';
+ }
+
+ $output = "{\n";
+ $itemIndent = str_repeat(' ', $indent + 1);
+ $closeIndent = str_repeat(' ', $indent);
+ $lastKey = array_key_last($data);
+
+ foreach ($data as $key => $node) {
+ // Key as a safe Ruby string
+ $keyStr = json_encode((string)$key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
+
+ // Value serialization
+ if (is_array($node)) {
+ // Distinguish JSON arrays vs objects
+ $isList = array_keys($node) === range(0, count($node) - 1);
+ if ($isList) {
+ $items = [];
+ foreach ($node as $v) {
+ if (is_array($v)) {
+ $items[] = $this->jsonToHash($v, $indent + 1);
+ } elseif (is_bool($v)) {
+ $items[] = $v ? 'true' : 'false';
+ } elseif ($v === null) {
+ $items[] = 'nil';
+ } elseif (is_string($v)) {
+ $items[] = json_encode($v, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
+ } else {
+ $items[] = (string)$v;
+ }
+ }
+ $value = '[' . implode(', ', $items) . ']';
+ } else {
+ $value = $this->jsonToHash($node, $indent + 1);
+ }
+ } elseif (is_bool($node)) {
+ $value = $node ? 'true' : 'false';
+ } elseif ($node === null) {
+ $value = 'nil';
+ } elseif (is_string($node)) {
+ $value = json_encode($node, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
+ } else {
+ $value = (string)$node;
+ }
+
+ $output .= $itemIndent . $keyStr . ' => ' . $value;
+ if ($key !== $lastKey) {
+ $output .= ',';
+ }
+ $output .= "\n";
+ }
+
+ $output .= $closeIndent . '}';
return $output;
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
protected function jsonToHash(array $data, int $indent = 0): string | |
{ | |
$output = '{'; | |
if (empty($data)) { | |
return '{}'; | |
} | |
$output = "{\n"; | |
$indentStr = str_repeat(' ', $indent + 4); | |
$keys = array_keys($data); | |
foreach ($data as $key => $node) { | |
$value = (is_array($node)) ? $this->jsonToHash($node) : $node; | |
$output .= '"' . $key . '" => ' . ((is_string($node)) ? '"' . $value . '"' : $value) . (($key !== array_key_last($data)) ? ', ' : ''); | |
if (is_array($node)) { | |
$value = $this->jsonToHash($node, $indent + 1); | |
} elseif (is_bool($node)) { | |
$value = $node ? 'true' : 'false'; | |
} elseif (is_string($node)) { | |
$value = '"' . $node . '"'; | |
} else { | |
$value = $node; | |
} | |
$output .= $indentStr . '"' . $key . '" => ' . $value; | |
// Add comma if not the last item | |
if ($key !== end($keys)) { | |
$output .= ','; | |
} | |
$output .= "\n"; | |
} | |
$output .= '}'; | |
$output .= str_repeat(' ', $indent + 2) . '}'; | |
return $output; | |
} | |
protected function jsonToHash(array $data, int $indent = 0): string | |
{ | |
if (empty($data)) { | |
return '{}'; | |
} | |
$output = "{\n"; | |
$itemIndent = str_repeat(' ', $indent + 1); | |
$closeIndent = str_repeat(' ', $indent); | |
$lastKey = array_key_last($data); | |
foreach ($data as $key => $node) { | |
// Key as a safe Ruby string | |
$keyStr = json_encode((string)$key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
// Value serialization | |
if (is_array($node)) { | |
// Distinguish JSON arrays vs objects | |
$isList = array_keys($node) === range(0, count($node) - 1); | |
if ($isList) { | |
$items = []; | |
foreach ($node as $v) { | |
if (is_array($v)) { | |
$items[] = $this->jsonToHash($v, $indent + 1); | |
} elseif (is_bool($v)) { | |
$items[] = $v ? 'true' : 'false'; | |
} elseif ($v === null) { | |
$items[] = 'nil'; | |
} elseif (is_string($v)) { | |
$items[] = json_encode($v, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
} else { | |
$items[] = (string)$v; | |
} | |
} | |
$value = '[' . implode(', ', $items) . ']'; | |
} else { | |
$value = $this->jsonToHash($node, $indent + 1); | |
} | |
} elseif (is_bool($node)) { | |
$value = $node ? 'true' : 'false'; | |
} elseif ($node === null) { | |
$value = 'nil'; | |
} elseif (is_string($node)) { | |
$value = json_encode($node, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
} else { | |
$value = (string)$node; | |
} | |
$output .= $itemIndent . $keyStr . ' => ' . $value; | |
if ($key !== $lastKey) { | |
$output .= ','; | |
} | |
$output .= "\n"; | |
} | |
$output .= $closeIndent . '}'; | |
return $output; | |
} |
🤖 Prompt for AI Agents
In src/SDK/Language/Ruby.php around lines 332-366, the jsonToHash function
currently misserializes JSON: it treats arrays as hashes, doesn't escape string
contents or keys, renders nulls as empty strings, and uses inconsistent
indentation. Fix by: detect numeric-sequential arrays (array_keys are 0..n-1)
and render them as Ruby arrays "[...]" by recursively serializing items; escape
string values and keys (escape backslashes and double quotes) before wrapping in
double quotes; render null as Ruby nil; keep booleans as true/false and numbers
as-is; compute indentation consistently (use $indent to build base indent, e.g.
$indentStr = str_repeat(' ', $indent + 1) for items and close with str_repeat('
', $indent) . '}'); ensure comma placement by comparing current index to last
index using the keys array index (e.g. track $i and $last = count($keys)-1) when
appending commas; update recursive calls to pass $indent + 1 for nested
structures.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/SDK/Language/Go.php (1)
258-266
: Bug: Array example emitsinterface{}{...}
which is not a valid Go composite literal.Slice literals must be
[]interface{}{...}
at minimum; nested values also need typing.Minimal fix:
- $output .= 'interface{}{' . $example . '}'; + $output .= '[]interface{}{' . $example . '}';Better (consistent with object handling): parse JSON and reuse
toGoCompositeLiteral($decoded)
so nested items get proper types.
🧹 Nitpick comments (1)
src/SDK/Language/Go.php (1)
141-143
: Consistency: unifyany
vsinterface{}
usage.This file mixes
any
(Line 142) andinterface{}
(Lines 154-155). Prefer one for consistency; given the rest of the file usesinterface{}
, align the special case accordingly.Apply:
- return '[]map[string]any'; + return '[]map[string]interface{}';Alternatively, migrate all
interface{}
toany
if Go 1.18+ is guaranteed.Also applies to: 154-155
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
src/SDK/Language/DotNet.php
(1 hunks)src/SDK/Language/Go.php
(1 hunks)src/SDK/Language/Swift.php
(1 hunks)
src/SDK/Language/DotNet.php
Outdated
$output .= ($example === '{}') | ||
? '[object]' | ||
: (($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | ||
? 'new ' . preg_replace('/\n/', "\n ", $formatted) | ||
: 'new ' . $example); | ||
break; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
DotNet: Emitting invalid C# for object examples; also risks outputting new null
.
new
+ JSON is not valid C# syntax. Snippets likenew {"a":1}
won’t compile.- If
json_decode
fails,json_encode(null)
returns"null"
and you emitnew null
. - Make JSON handling robust and render proper C# initializers (Dictionary/List) instead.
Apply this diff to replace the current branch:
- case self::TYPE_OBJECT:
- $output .= ($example === '{}')
- ? '[object]'
- : (($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT))
- ? 'new ' . preg_replace('/\n/', "\n ", $formatted)
- : 'new ' . $example);
+ case self::TYPE_OBJECT:
+ $trimmed = trim((string)$example);
+ if ($trimmed === '{}') {
+ $output .= '[object]';
+ } else {
+ $decoded = json_decode($example, true);
+ if (json_last_error() === JSON_ERROR_NONE) {
+ $output .= $this->jsonToCSharpObject($decoded);
+ } else {
+ // Fallback to a safe placeholder rather than emitting invalid C#
+ $output .= '[object]';
+ }
+ }
Add these helpers inside the DotNet class (outside the changed hunk):
private function jsonToCSharpObject($value, int $level = 0): string
{
$indent = str_repeat(' ', $level);
$next = str_repeat(' ', $level + 1);
if (is_array($value)) {
if ($this->isAssoc($value)) {
if ($value === []) {
return 'new Dictionary<string, object>()';
}
$lines = [];
foreach ($value as $k => $v) {
$lines[] = $next . '["' . addslashes((string)$k) . '"] = ' . $this->jsonToCSharpObject($v, $level + 1);
}
return "new Dictionary<string, object>\n{$indent}{\n" . implode(",\n", $lines) . "\n{$indent}}";
} else {
if ($value === []) {
return 'new List<object>()';
}
$items = array_map(fn($v) => $this->jsonToCSharpObject($v, $level + 1), $value);
return "new List<object>\n{$indent}{\n{$next}" . implode(",\n{$next}", $items) . "\n{$indent}}";
}
}
if (is_string($value)) return '"' . addslashes($value) . '"';
if (is_bool($value)) return $value ? 'true' : 'false';
if (is_int($value) || is_float($value)) return (string)$value;
if ($value === null) return 'null';
return 'null';
}
private function isAssoc(array $arr): bool
{
// Treat empty as assoc only when you intend a Dictionary (TYPE_OBJECT branch)
return $arr === [] || array_keys($arr) !== range(0, count($arr) - 1);
}
Note: Ensure the generated C# files include using System.Collections.Generic;
.
🤖 Prompt for AI Agents
In src/SDK/Language/DotNet.php around lines 288–293, the current code emits
invalid C# by prefixing raw JSON with "new " (producing things like `new
{"a":1}` or `new null`); replace that branch to parse JSON safely and render
proper C# initializers using helpers: add the provided jsonToCSharpObject and
isAssoc private methods to the DotNet class and call json_decode on the example,
check for json_decode success, then use jsonToCSharpObject to produce
Dictionary/List/string/bool/number/null C# literals instead of naïvely
concatenating "new ". Also ensure generated files include `using
System.Collections.Generic;` when object initializers are emitted.
$output .= ($example === '{}') | ||
? 'map[string]interface{}{}' | ||
: (($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT)) | ||
? 'map[string]interface{}' . preg_replace('/\n/', "\n ", $formatted) | ||
: 'map[string]interface{}' . $example); | ||
break; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix: JSON pretty-printing yields invalid Go for nested values and can output map[string]interface{}null
.
- Using raw JSON inside a Go composite literal fails for nested objects/arrays (need typed
map[string]interface{}
/[]interface{}
recursively). json_encode(json_decode(...))
returns the string"null"
on decode failure, which is truthy and producesmap[string]interface{}null
.
Refactor to build a proper Go composite literal from decoded JSON and guard on json_last_error()
.
Apply this diff within the case:
- case self::TYPE_OBJECT:
- $output .= ($example === '{}')
- ? 'map[string]interface{}{}'
- : (($formatted = json_encode(json_decode($example, true), JSON_PRETTY_PRINT))
- ? 'map[string interface{}' . preg_replace('/\n/', "\n ", $formatted)
- : 'map[string interface{}' . $example);
+ case self::TYPE_OBJECT:
+ if ($example === '{}') {
+ $output .= 'map[string interface{}{}';
+ } else {
+ $decoded = \json_decode($example, true);
+ if (\json_last_error() === JSON_ERROR_NONE) {
+ $output .= $this->toGoCompositeLiteral($decoded);
+ } else {
+ // Safe fallback when example isn't valid JSON
+ $output .= 'map[string interface{}{}';
+ }
+ }
Add this helper method to the class (placement outside the selected lines):
protected function toGoCompositeLiteral($value, int $indent = 0): string
{
$sp = \str_repeat(' ', $indent);
if (\is_array($value)) {
$isAssoc = \array_keys($value) !== \range(0, \count($value) - 1);
if ($isAssoc) {
$lines = [];
foreach ($value as $k => $v) {
$key = \json_encode((string)$k, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$lines[] = $sp . ' ' . $key . ': ' . $this->toGoCompositeLiteral($v, $indent + 1);
}
return "map[string]interface{}{\n" . \implode(",\n", $lines) . "\n" . $sp . "}";
}
$items = [];
foreach ($value as $v) {
$items[] = $sp . ' ' . $this->toGoCompositeLiteral($v, $indent + 1);
}
return "[]interface{}{\n" . \implode(",\n", $items) . "\n" . $sp . "}";
}
if ($value === null) {
return 'nil';
}
if (\is_bool($value)) {
return $value ? 'true' : 'false';
}
if (\is_numeric($value)) {
return (string)$value;
}
// Strings
return \json_encode((string)$value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
🤖 Prompt for AI Agents
In src/SDK/Language/Go.php around lines 268-273, the current branch that
pretty-prints JSON injects raw JSON into a Go literal and can produce invalid
output like `map[string]interface{}null`; instead decode the JSON, check
json_last_error() to bail on decode failure, and convert the decoded PHP value
into a proper Go composite literal recursively (maps =>
map[string]interface{}{...}, lists => []interface{}{...}, null => nil,
booleans/numbers as Go literals, strings JSON-encoded) using a helper like
toGoCompositeLiteral($value, $indent) and use its output in place of the current
json_encode-based string. Ensure you add the helper method to the class (outside
the shown lines) and guard the decode path so on decode error you fall back to
the safe original behavior or an empty map.
$decoded = json_decode($example, true); | ||
if ($decoded && is_array($decoded)) { | ||
$output .= $this->jsonToSwiftDict($decoded); | ||
} else { | ||
$output .= '[:]'; | ||
} | ||
break; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Harden JSON parsing and accept empty objects; avoid silently treating JSON arrays as objects.
Current truthy check rejects {}
and doesn't distinguish []
(array) from {}
(object). Also, prefer checking json_last_error()
for safety.
Apply this diff:
- $decoded = json_decode($example, true);
- if ($decoded && is_array($decoded)) {
- $output .= $this->jsonToSwiftDict($decoded);
- } else {
- $output .= '[:]';
- }
+ $decoded = json_decode($example, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $isAssoc = array_keys($decoded) !== range(0, count($decoded) - 1);
+ if ($isAssoc || empty($decoded)) {
+ $output .= $this->jsonToSwiftDict($decoded, 0);
+ } else {
+ // Non-object JSON (e.g., list) — fall back for object-typed param
+ $output .= '[:]';
+ }
+ } else {
+ $output .= '[:]';
+ }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
$decoded = json_decode($example, true); | |
if ($decoded && is_array($decoded)) { | |
$output .= $this->jsonToSwiftDict($decoded); | |
} else { | |
$output .= '[:]'; | |
} | |
break; | |
$decoded = json_decode($example, true); | |
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { | |
$isAssoc = array_keys($decoded) !== range(0, count($decoded) - 1); | |
if ($isAssoc || empty($decoded)) { | |
$output .= $this->jsonToSwiftDict($decoded, 0); | |
} else { | |
// Non-object JSON (e.g., list) — fall back for object-typed param | |
$output .= '[:]'; | |
} | |
} else { | |
$output .= '[:]'; | |
} | |
break; |
/** | ||
* Converts JSON Object To Swift Native Dictionary | ||
* | ||
* @param array $data | ||
* @param int $indent | ||
* @return string | ||
*/ | ||
protected function jsonToSwiftDict(array $data, int $indent = 0): string | ||
{ | ||
if (empty($data)) { | ||
return '[:]'; | ||
} | ||
|
||
$baseIndent = str_repeat(' ', $indent); | ||
$itemIndent = str_repeat(' ', $indent + 1); | ||
$output = "[\n"; | ||
|
||
$keys = array_keys($data); | ||
foreach ($keys as $index => $key) { | ||
$node = $data[$key]; | ||
|
||
if (is_array($node)) { | ||
$value = $this->jsonToSwiftDict($node, $indent + 1); | ||
} elseif (is_string($node)) { | ||
$value = '"' . $node . '"'; | ||
} elseif (is_bool($node)) { | ||
$value = $node ? 'true' : 'false'; | ||
} elseif (is_null($node)) { | ||
$value = 'nil'; | ||
} else { | ||
$value = $node; | ||
} | ||
|
||
$comma = ($index < count($keys) - 1) ? ',' : ''; | ||
$output .= ' ' . $itemIndent . '"' . $key . '": ' . $value . $comma . "\n"; | ||
} | ||
|
||
$output .= ' ' . $baseIndent . ']'; | ||
|
||
return $output; | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Arrays inside object examples render as dictionaries; string escaping and indentation are off; nil
values in dictionaries may not compile.
- Lists (JSON arrays) become Swift dictionaries with numeric keys – incorrect.
- Strings/keys are not escaped, risking invalid Swift.
- Indentation adds extra 4 spaces; closing bracket misaligned.
- Using
nil
as a dictionary value often fails without explicit optional typing; useNSNull()
to stay unambiguous.
Replace the method body with array/list handling, escaping, and fixed indentation:
- protected function jsonToSwiftDict(array $data, int $indent = 0): string
- {
- if (empty($data)) {
- return '[:]';
- }
-
- $baseIndent = str_repeat(' ', $indent);
- $itemIndent = str_repeat(' ', $indent + 1);
- $output = "[\n";
-
- $keys = array_keys($data);
- foreach ($keys as $index => $key) {
- $node = $data[$key];
-
- if (is_array($node)) {
- $value = $this->jsonToSwiftDict($node, $indent + 1);
- } elseif (is_string($node)) {
- $value = '"' . $node . '"';
- } elseif (is_bool($node)) {
- $value = $node ? 'true' : 'false';
- } elseif (is_null($node)) {
- $value = 'nil';
- } else {
- $value = $node;
- }
-
- $comma = ($index < count($keys) - 1) ? ',' : '';
- $output .= ' ' . $itemIndent . '"' . $key . '": ' . $value . $comma . "\n";
- }
-
- $output .= ' ' . $baseIndent . ']';
-
- return $output;
- }
+ protected function jsonToSwiftDict(array $data, int $indent = 0): string
+ {
+ if (empty($data)) {
+ return '[:]';
+ }
+
+ $baseIndent = str_repeat(' ', $indent);
+ $itemIndent = str_repeat(' ', $indent + 1);
+ $output = $baseIndent . "[\n";
+
+ $keys = array_keys($data);
+ $lastIndex = count($keys) - 1;
+ foreach ($keys as $index => $key) {
+ $value = $this->jsonToSwiftValue($data[$key], $indent + 1);
+ $comma = ($index < $lastIndex) ? ',' : '';
+ $output .= $itemIndent . '"' . $this->swiftEscape($key) . '": ' . $value . $comma . "\n";
+ }
+
+ $output .= $baseIndent . ']';
+
+ return $output;
+ }
Add these helpers below the method (outside the changed range) to fully support arrays, values, and escaping:
// Place below jsonToSwiftDict(...)
protected function jsonToSwiftArray(array $list, int $indent = 0): string
{
if (empty($list)) {
return '[]';
}
$baseIndent = str_repeat(' ', $indent);
$itemIndent = str_repeat(' ', $indent + 1);
$output = $baseIndent . "[\n";
$lastIndex = count($list) - 1;
foreach ($list as $i => $item) {
$value = $this->jsonToSwiftValue($item, $indent + 1);
$comma = ($i < $lastIndex) ? ',' : '';
$output .= $itemIndent . $value . $comma . "\n";
}
$output .= $baseIndent . ']';
return $output;
}
protected function jsonToSwiftValue($node, int $indent = 0): string
{
if (is_array($node)) {
$isAssoc = array_keys($node) !== range(0, count($node) - 1);
return $isAssoc
? $this->jsonToSwiftDict($node, $indent)
: $this->jsonToSwiftArray($node, $indent);
}
if (is_string($node)) {
return '"' . $this->swiftEscape($node) . '"';
}
if (is_bool($node)) {
return $node ? 'true' : 'false';
}
if ($node === null) {
return 'NSNull()';
}
return (string)$node;
}
protected function swiftEscape(string $s): string
{
return str_replace(
["\\", "\"", "\r", "\n", "\t"],
["\\\\", "\\\"", "\\r", "\\n", "\\t"],
$s
);
}
This yields valid Swift for nested objects/lists, escapes safely, and avoids invalid ["key": nil]
literals.
🤖 Prompt for AI Agents
In src/SDK/Language/Swift.php around lines 451 to 492, the jsonToSwiftDict
implementation treats JSON arrays as numeric-key dictionaries, fails to escape
strings/keys, mis-indents the closing bracket, and emits nil values that can
break Swift; replace the method body to detect associative vs sequential arrays
and delegate to a jsonToSwiftArray for lists, use a jsonToSwiftValue helper to
serialize nodes (strings escaped via a swiftEscape helper, booleans as
true/false, null as NSNull()), fix indentation so baseIndent and itemIndent are
applied correctly and commas are only added between items, and add the three
helpers (jsonToSwiftArray, jsonToSwiftValue, swiftEscape) immediately below this
method to produce valid, properly escaped and indented Swift literals.
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Refactor