Skip to content
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

Avoiding overwriting of private members redeclared in derived classes #35

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
58 changes: 40 additions & 18 deletions src/Exporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,29 +143,15 @@ public function toArray($value)
return (array) $value;
}

$array = [];
$array = [];
$className = \get_class($value);

foreach ((array) $value as $key => $val) {
// Exception traces commonly reference hundreds to thousands of
// objects currently loaded in memory. Including them in the result
// has a severe negative performance impact.
if ("\0Error\0trace" === $key || "\0Exception\0trace" === $key) {
continue;
}

// properties are transformed to keys in the following way:
// private $property => "\0Classname\0property"
// protected $property => "\0*\0property"
// public $property => "property"
if (\preg_match('/^\0.+\0(.+)$/', (string) $key, $matches)) {
$key = $matches[1];
}

// See https://github.com/php/php-src/commit/5721132
if ($key === "\0gcdata") {
if ($this->ignoreKey($key)) {
continue;
}

$key = $this->getExportedKey($key, $className);
$array[$key] = $val;
}

Expand Down Expand Up @@ -300,4 +286,40 @@ protected function recursiveExport(&$value, $indentation, $processed = null)

return \var_export($value, true);
}

private function ignoreKey($key)
{
// Exception traces commonly reference hundreds to thousands of
// objects currently loaded in memory. Including them in the result
// has a severe negative performance impact.
if ("\0Error\0trace" === $key || "\0Exception\0trace" === $key) {
return true;
}

// See https://github.com/php/php-src/commit/5721132
if ($key === "\0gcdata") {
return true;
}

return false;
}

private function getExportedKey($key, $className)
{
// properties are transformed to keys in the following way:
// private $property => "\0Classname\0property"
// protected $property => "\0*\0property"
// public $property => "property"
$ignoredPrefixes = ['', '*', $className];

if (\preg_match('/^\0(.+)\0(.+)$/', (string) $key, $matches)) {
if (\in_array($matches[1], $ignoredPrefixes)) {
$key = $matches[2];
} else {
$key = "{$matches[1]}::{$matches[2]}";
}
}

return $key;
}
}