Skip to content

Commit

Permalink
Merge pull request #14 from localheinz/fix/collapse
Browse files Browse the repository at this point in the history
Fix: Collapse empty arrays and objects
  • Loading branch information
localheinz authored Jan 5, 2018
2 parents c1a4ba8 + a1b697c commit 4a7e168
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Printer.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,11 @@ public function print(string $original, bool $unEscapeUnicode, bool $unEscapeSla
*/
if ('}' === $character || ']' === $character) {
--$indentLevel;
$previousCharacter = \substr($original, $i - 1, 1);

if ('{' !== $previousCharacter && '[' !== $previousCharacter) {
$trimmed = \rtrim($printed);
$previousNonWhitespaceCharacter = \substr($trimmed, -1);

if ('{' !== $previousNonWhitespaceCharacter && '[' !== $previousNonWhitespaceCharacter) {
$printed .= PHP_EOL;

for ($j = 0; $j < $indentLevel; ++$j) {
Expand All @@ -143,7 +145,7 @@ public function print(string $original, bool $unEscapeUnicode, bool $unEscapeSla
/**
* Collapse empty {} and [].
*/
$printed = \rtrim($printed);
$printed = $trimmed;
}
}

Expand Down
80 changes: 80 additions & 0 deletions test/Unit/PrinterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,86 @@ public function testPrintPrintsObjectPrettyWithUnEscapeUnicodeAndUnEscapeSlashes
$this->assertSame($original, $printed);
}

public function testPrintCollapsesEmptyArray()
{
$original = <<<'JSON'
[
]
JSON;

$expected = <<<'JSON'
[]
JSON;

$printer = new Printer();

$printed = $printer->print(
$original,
true,
true
);

$this->assertSame($expected, $printed);
}

public function testPrintCollapsesEmptyObject()
{
$original = <<<'JSON'
{
}
JSON;

$expected = <<<'JSON'
{}
JSON;

$printer = new Printer();

$printed = $printer->print(
$original,
true,
true
);

$this->assertSame($expected, $printed);
}

public function testPrintCollapsesEmptyComplex()
{
$original = <<<'JSON'
{
"foo": {
} ,
"bar": [ ]
}
JSON;

$expected = <<<'JSON'
{
"foo": {},
"bar": []
}
JSON;

$printer = new Printer();

$printed = $printer->print(
$original,
true,
true
);

$this->assertSame($expected, $printed);
}

/**
* @see https://github.com/zendframework/zend-json/pull/37
*/
Expand Down

0 comments on commit 4a7e168

Please sign in to comment.