Skip to content

Commit

Permalink
Add max nesting level configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
olsavmic committed May 6, 2022
1 parent 57b1424 commit d7ff650
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/Exporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/
namespace SebastianBergmann\Exporter;

use const PHP_INT_MAX;
use const PHP_VERSION;
use function bin2hex;
use function count;
Expand Down Expand Up @@ -48,6 +49,14 @@
*/
final class Exporter
{

private int $maxNestingLevel;

public function __construct(int $maxNestingLevel = PHP_INT_MAX)
{
$this->maxNestingLevel = $maxNestingLevel;
}

/**
* Exports a value as a string.
*
Expand Down Expand Up @@ -208,7 +217,7 @@ public function toArray(mixed $value): array
/**
* Recursive implementation of export.
*/
private function recursiveExport(mixed &$value, int $indentation, ?Context $processed = null): string
private function recursiveExport(mixed &$value, int $indentation, ?Context $processed = null, int $nestingLevel = 0): string
{
if ($value === null) {
return 'null';
Expand Down Expand Up @@ -287,6 +296,10 @@ private function recursiveExport(mixed &$value, int $indentation, ?Context $proc
return 'Array &' . $key;
}

if ($nestingLevel > $this->maxNestingLevel) {
return sprintf('Array &%s (Max nesting level exceeded)', $key);
}

$array = $value;
$key = $processed->add($value);
$values = '';
Expand All @@ -296,8 +309,8 @@ private function recursiveExport(mixed &$value, int $indentation, ?Context $proc
$values .= sprintf(
'%s %s => %s' . "\n",
$whitespace,
$this->recursiveExport($k, $indentation),
$this->recursiveExport($value[$k], $indentation + 1, $processed)
$this->recursiveExport($k, $indentation, null, $nestingLevel + 1),
$this->recursiveExport($value[$k], $indentation + 1, $processed, $nestingLevel + 1)
);
}

Expand All @@ -314,6 +327,10 @@ private function recursiveExport(mixed &$value, int $indentation, ?Context $proc
return sprintf('%s Object #%d', $class, spl_object_id($value));
}

if ($nestingLevel > $this->maxNestingLevel) {
return sprintf('%s Object #%d (Max nesting level exceeded)', $class, spl_object_id($value));
}

$processed->add($value);
$values = '';
$array = $this->toArray($value);
Expand All @@ -323,8 +340,8 @@ private function recursiveExport(mixed &$value, int $indentation, ?Context $proc
$values .= sprintf(
'%s %s => %s' . "\n",
$whitespace,
$this->recursiveExport($k, $indentation),
$this->recursiveExport($v, $indentation + 1, $processed)
$this->recursiveExport($k, $indentation, null, $nestingLevel + 1),
$this->recursiveExport($v, $indentation + 1, $processed, $nestingLevel + 1)
);
}

Expand Down

0 comments on commit d7ff650

Please sign in to comment.