Skip to content

POC: Allow to limit the max-depth of Exporter->export() #55

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
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
20 changes: 15 additions & 5 deletions src/Exporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@

final class Exporter
{
private ?int $maxLevel;

/**
* Exports a value as a string.
*
Expand All @@ -49,9 +51,11 @@ final class Exporter
* - Carriage returns and newlines are normalized to \n
* - Recursion and repeated rendering is treated properly
*/
public function export(mixed $value, int $indentation = 0): string
public function export(mixed $value, int $indentation = 0, ?int $maxLevel = null): string
{
return $this->recursiveExport($value, $indentation);
$this->maxLevel = $maxLevel;

return $this->recursiveExport($value, $indentation, null, 0);
}

public function shortenedRecursiveExport(array &$data, ?Context $context = null): string
Expand Down Expand Up @@ -192,8 +196,14 @@ public function toArray(mixed $value): array
return $array;
}

private function recursiveExport(mixed &$value, int $indentation, ?Context $processed = null): string
private function recursiveExport(mixed &$value, int $indentation, ?Context $processed = null, $level = 0): string
{
if ($this->maxLevel !== null) {
if ($level > $this->maxLevel) {
return '** Max recursion level reached **';
}
}

if ($value === null) {
return 'null';
}
Expand Down Expand Up @@ -296,7 +306,7 @@ private function recursiveExport(mixed &$value, int $indentation, ?Context $proc
. ' ' .
$this->recursiveExport($k, $indentation)
. ' => ' .
$this->recursiveExport($value[$k], $indentation + 1, $processed)
$this->recursiveExport($value[$k], $indentation + 1, $processed, $level + 1)
. ",\n";
}

Expand Down Expand Up @@ -324,7 +334,7 @@ private function recursiveExport(mixed &$value, int $indentation, ?Context $proc
. ' ' .
$this->recursiveExport($k, $indentation)
. ' => ' .
$this->recursiveExport($v, $indentation + 1, $processed)
$this->recursiveExport($v, $indentation + 1, $processed, $level + 1)
. ",\n";
}

Expand Down