Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
12
use function array_merge;
13
use function func_get_args;
14
use function is_array;
15
use function is_object;
16
use SebastianBergmann\ObjectReflector\ObjectReflector;
17
use SebastianBergmann\RecursionContext\Context;
18
 
19
/**
20
 * Traverses array structures and object graphs
21
 * to enumerate all referenced objects.
22
 */
23
class Enumerator
24
{
25
    /**
26
     * Returns an array of all objects referenced either
27
     * directly or indirectly by a variable.
28
     *
29
     * @param array|object $variable
30
     *
31
     * @return object[]
32
     */
33
    public function enumerate($variable)
34
    {
35
        if (!is_array($variable) && !is_object($variable)) {
36
            throw new InvalidArgumentException;
37
        }
38
 
39
        if (isset(func_get_args()[1])) {
40
            if (!func_get_args()[1] instanceof Context) {
41
                throw new InvalidArgumentException;
42
            }
43
 
44
            $processed = func_get_args()[1];
45
        } else {
46
            $processed = new Context;
47
        }
48
 
49
        $objects = [];
50
 
51
        if ($processed->contains($variable)) {
52
            return $objects;
53
        }
54
 
55
        $array = $variable;
56
        $processed->add($variable);
57
 
58
        if (is_array($variable)) {
59
            foreach ($array as $element) {
60
                if (!is_array($element) && !is_object($element)) {
61
                    continue;
62
                }
63
 
64
                $objects = array_merge(
65
                    $objects,
66
                    $this->enumerate($element, $processed)
67
                );
68
            }
69
        } else {
70
            $objects[] = $variable;
71
 
72
            $reflector = new ObjectReflector;
73
 
74
            foreach ($reflector->getAttributes($variable) as $value) {
75
                if (!is_array($value) && !is_object($value)) {
76
                    continue;
77
                }
78
 
79
                $objects = array_merge(
80
                    $objects,
81
                    $this->enumerate($value, $processed)
82
                );
83
            }
84
        }
85
 
86
        return $objects;
87
    }
88
}