Skip to content

Commit 6c37aeb

Browse files
Custom array printing (#3)
1 parent d2bc617 commit 6c37aeb

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

app/Support/HttpCall.php

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ private static function generateOptions(Request $request): string
2323

2424
if ($request->headers()) {
2525
// TODO: what about headers that have Http helper methods, for example: `acceptJson`
26-
$options[] = 'withHeaders(' . var_export($request->headers(), true) . ')';
26+
$options[] = 'withHeaders(' . self::prettyPrintArray($request->headers()) . ')';
2727
}
2828

2929
if (empty($options)) {
@@ -39,6 +39,25 @@ private static function generateRequest(Request $request): string
3939
return "'" . $request->url() . "'";
4040
}
4141

42-
return sprintf('\'%s\', %s', $request->url(), var_export($request->data(), true));
42+
return sprintf('\'%s\', %s', $request->url(), self::prettyPrintArray($request->data()));
43+
}
44+
45+
private static function prettyPrintArray(array $data, $assoc = true)
46+
{
47+
$output = var_export($data, true);
48+
$patterns = [
49+
"/array \(/" => '[',
50+
"/^([ ]*)\)(,?)$/m" => '$1]$2',
51+
"/=>[ ]?\n[ ]+\[/" => '=> [',
52+
"/([ ]*)(\'[^\']+\') => ([\[\'])/" => '$1$2 => $3',
53+
];
54+
$output = preg_replace('/^\s+/m', ' ', $output);
55+
$output = preg_replace(['/^array \(/', '/\)$/'], ['[', ' ]'], $output);
56+
57+
if (!$assoc) {
58+
$output = preg_replace('/^(\s+)[^=]+=>\s+/m', '$1', $output);
59+
}
60+
61+
return trim(str_replace("\n", PHP_EOL, $output));
4362
}
4463
}

tests/fixtures/basic-post.out

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1-
Http::post('https://example.com', ['foo' => 'bar']);
1+
Http::post('https://example.com', [
2+
'foo' => 'bar',
3+
]);
Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1-
Http::post('https://example.com', ['foo' => 'bar', 'rho' => [1, 2], 'baz' => 'qui']);
1+
Http::post('https://example.com', [
2+
'foo' => 'bar',
3+
'rho' => [1, 2],
4+
'baz' => 'qui',
5+
]);

0 commit comments

Comments
 (0)