Enumerator.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of sebastian/object-enumerator.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\ObjectEnumerator;
  11. use function array_merge;
  12. use function is_array;
  13. use function is_object;
  14. use SebastianBergmann\ObjectReflector\ObjectReflector;
  15. use SebastianBergmann\RecursionContext\Context;
  16. final class Enumerator
  17. {
  18. /**
  19. * @psalm-return list<object>
  20. */
  21. public function enumerate(array|object $variable, Context $processed = new Context): array
  22. {
  23. $objects = [];
  24. if ($processed->contains($variable)) {
  25. return $objects;
  26. }
  27. $array = $variable;
  28. /* @noinspection UnusedFunctionResultInspection */
  29. $processed->add($variable);
  30. if (is_array($variable)) {
  31. foreach ($array as $element) {
  32. if (!is_array($element) && !is_object($element)) {
  33. continue;
  34. }
  35. /** @noinspection SlowArrayOperationsInLoopInspection */
  36. $objects = array_merge(
  37. $objects,
  38. $this->enumerate($element, $processed)
  39. );
  40. }
  41. return $objects;
  42. }
  43. $objects[] = $variable;
  44. foreach ((new ObjectReflector)->getProperties($variable) as $value) {
  45. if (!is_array($value) && !is_object($value)) {
  46. continue;
  47. }
  48. /** @noinspection SlowArrayOperationsInLoopInspection */
  49. $objects = array_merge(
  50. $objects,
  51. $this->enumerate($value, $processed)
  52. );
  53. }
  54. return $objects;
  55. }
  56. }