From d7ff650e0afb345a4fb7e34b009cb2baa5b9d81c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Ols=CC=8Cavsky=CC=81?= Date: Fri, 6 May 2022 11:24:20 +0200 Subject: [PATCH] Add max nesting level configuration --- src/Exporter.php | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/Exporter.php b/src/Exporter.php index 7d9d8d4..708c274 100644 --- a/src/Exporter.php +++ b/src/Exporter.php @@ -9,6 +9,7 @@ */ namespace SebastianBergmann\Exporter; +use const PHP_INT_MAX; use const PHP_VERSION; use function bin2hex; use function count; @@ -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. * @@ -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'; @@ -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 = ''; @@ -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) ); } @@ -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); @@ -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) ); }