Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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