3 * This file is part of the Recursion Context package.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace SebastianBergmann\RecursionContext;
14 * A context containing previously processed arrays and objects
15 * when recursively processing a value.
25 * @var \SplObjectStorage
30 * Initialises the context
32 public function __construct()
34 $this->arrays = array();
35 $this->objects = new \SplObjectStorage;
39 * Adds a value to the context.
41 * @param array|object $value The value to add.
43 * @return int|string The ID of the stored value, either as a string or integer.
45 * @throws InvalidArgumentException Thrown if $value is not an array or object
47 public function add(&$value)
49 if (is_array($value)) {
50 return $this->addArray($value);
51 } elseif (is_object($value)) {
52 return $this->addObject($value);
55 throw new InvalidArgumentException(
56 'Only arrays and objects are supported'
61 * Checks if the given value exists within the context.
63 * @param array|object $value The value to check.
65 * @return int|string|false The string or integer ID of the stored value if it has already been seen, or false if the value is not stored.
67 * @throws InvalidArgumentException Thrown if $value is not an array or object
69 public function contains(&$value)
71 if (is_array($value)) {
72 return $this->containsArray($value);
73 } elseif (is_object($value)) {
74 return $this->containsObject($value);
77 throw new InvalidArgumentException(
78 'Only arrays and objects are supported'
87 private function addArray(array &$array)
89 $key = $this->containsArray($array);
95 $this->arrays[] = &$array;
97 return count($this->arrays) - 1;
101 * @param object $object
105 private function addObject($object)
107 if (!$this->objects->contains($object)) {
108 $this->objects->attach($object);
111 return spl_object_hash($object);
115 * @param array $array
119 private function containsArray(array &$array)
121 $keys = array_keys($this->arrays, $array, true);
122 $hash = '_Key_' . microtime(true);
124 foreach ($keys as $key) {
125 $this->arrays[$key][$hash] = $hash;
127 if (isset($array[$hash]) && $array[$hash] === $hash) {
128 unset($this->arrays[$key][$hash]);
133 unset($this->arrays[$key][$hash]);
140 * @param object $value
142 * @return string|false
144 private function containsObject($value)
146 if ($this->objects->contains($value)) {
147 return spl_object_hash($value);