Last active
June 8, 2022 17:58
-
-
Save JonathanGawrych/3fb19a2d10b4df238ca7e58cf1df4803 to your computer and use it in GitHub Desktop.
A php function to scan an object to attempt to find a path to a value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function findPathToObj($from, $to, $maxLevel = 5): ?string | |
| { | |
| $queue = [[ | |
| 'var' => $from, | |
| 'path' => 'root', | |
| 'level' => 0 | |
| ]]; | |
| $seen = []; | |
| while (count($queue) > 0) { | |
| $objInfo = array_shift($queue); | |
| [ | |
| 'var' => $var, | |
| 'path' => $path, | |
| 'level' => $level | |
| ] = $objInfo; | |
| if ($var === $to) { | |
| return $path; | |
| } | |
| if ($maxLevel !== -1 && $level > $maxLevel) { | |
| continue; | |
| } | |
| if (gettype($var) !== 'array' && gettype($var) !== 'object') { | |
| continue; | |
| } | |
| if (in_array($var, $seen, strict: true)) { | |
| continue; | |
| } | |
| $seen[] = $var; | |
| if (gettype($var) === 'array') { | |
| foreach ($var as $key => $value) { | |
| if (is_string($key)) { | |
| $key = "'$key'"; | |
| } | |
| $queue[] = [ | |
| 'var' => $value, | |
| 'path' => "{$path}[{$key}]", | |
| 'level' => $level + 1 | |
| ]; | |
| } | |
| } else { | |
| $reflection = new \ReflectionObject($var); | |
| $properties = $reflection->getProperties(); | |
| foreach ($properties as $property) | |
| { | |
| $property->setAccessible(true); | |
| $value = $property->getValue($var); | |
| $key = $property->getName(); | |
| if ($property->isProtected() || $property->isPrivate()) { | |
| $key = "#$key"; | |
| } | |
| if ($property->isStatic()) { | |
| $key = "::$key"; | |
| } | |
| $queue[] = [ | |
| 'var' => $value, | |
| 'path' => "{$path}->{$key}", | |
| 'level' => $level + 1 | |
| ]; | |
| } | |
| } | |
| } | |
| return null; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment