protected function _resolveIterator(Traversable $iterator, $test = null, $limit = null)
    {
        $origIterator = $iterator;

        // Default test function
        if (!is_callable($test)) {
            $test = function (Traversable $subject) {
                return $subject instanceof Iterator;
            };
        }

        if (is_null($limit)) {
            $limit = 100;
        } else {
            $limit = $this->_normalizeInt($limit);
        }

        $i = 0;
        while (!$test($iterator) && $i < $limit) {
            if (!($iterator instanceof IteratorAggregate)) {
                break;
            }

            $_it = $iterator->getIterator();
            if ($iterator === $_it) {
                throw $this->_createOutOfRangeException(
                    $this->__('Infinite recursion: looks like the traversable wraps itself on level %1$d', [$i]),
                    null,
                    null,
                    $origIterator
                );
            }

            $iterator = $_it;
            ++$i;
        }

        if (!$test($iterator)) {
            throw $this->_createOutOfRangeException(
                $this->__('The deepest iterator is not a match (limit is %1$d)', [$limit]),
                null,
                null,
                $origIterator
            );
        }

        return $iterator;
    }