comparison vendor/sebastian/object-enumerator/src/Enumerator.php @ 14:1fec387a4317

Update Drupal core to 8.5.2 via Composer
author Chris Cannam
date Mon, 23 Apr 2018 09:46:53 +0100
parents
children
comparison
equal deleted inserted replaced
13:5fb285c0d0e3 14:1fec387a4317
1 <?php
2 /*
3 * This file is part of 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
11 namespace SebastianBergmann\ObjectEnumerator;
12
13 use SebastianBergmann\ObjectReflector\ObjectReflector;
14 use SebastianBergmann\RecursionContext\Context;
15
16 /**
17 * Traverses array structures and object graphs
18 * to enumerate all referenced objects.
19 */
20 class Enumerator
21 {
22 /**
23 * Returns an array of all objects referenced either
24 * directly or indirectly by a variable.
25 *
26 * @param array|object $variable
27 *
28 * @return object[]
29 */
30 public function enumerate($variable)
31 {
32 if (!is_array($variable) && !is_object($variable)) {
33 throw new InvalidArgumentException;
34 }
35
36 if (isset(func_get_args()[1])) {
37 if (!func_get_args()[1] instanceof Context) {
38 throw new InvalidArgumentException;
39 }
40
41 $processed = func_get_args()[1];
42 } else {
43 $processed = new Context;
44 }
45
46 $objects = [];
47
48 if ($processed->contains($variable)) {
49 return $objects;
50 }
51
52 $array = $variable;
53 $processed->add($variable);
54
55 if (is_array($variable)) {
56 foreach ($array as $element) {
57 if (!is_array($element) && !is_object($element)) {
58 continue;
59 }
60
61 $objects = array_merge(
62 $objects,
63 $this->enumerate($element, $processed)
64 );
65 }
66 } else {
67 $objects[] = $variable;
68
69 $reflector = new ObjectReflector;
70
71 foreach ($reflector->getAttributes($variable) as $value) {
72 if (!is_array($value) && !is_object($value)) {
73 continue;
74 }
75
76 $objects = array_merge(
77 $objects,
78 $this->enumerate($value, $processed)
79 );
80 }
81 }
82
83 return $objects;
84 }
85 }