1<?php
2/*
3 * Copyright 2015-2017 MongoDB, Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *   http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18namespace MongoDB\Model;
19
20use IteratorIterator;
21use Traversable;
22use function array_key_exists;
23
24/**
25 * IndexInfoIterator for both listIndexes command and legacy query results.
26 *
27 * This common iterator may be used to wrap a Cursor returned by both the
28 * listIndexes command and, for legacy servers, queries on the "system.indexes"
29 * collection.
30 *
31 * @internal
32 * @see \MongoDB\Collection::listIndexes()
33 * @see https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst
34 * @see http://docs.mongodb.org/manual/reference/command/listIndexes/
35 * @see http://docs.mongodb.org/manual/reference/system-collections/
36 */
37class IndexInfoIteratorIterator extends IteratorIterator implements IndexInfoIterator
38{
39    /** @var string|null $ns */
40    private $ns;
41
42    /**
43     * @param string|null $ns
44     */
45    public function __construct(Traversable $iterator, $ns = null)
46    {
47        parent::__construct($iterator);
48
49        $this->ns = $ns;
50    }
51
52    /**
53     * Return the current element as an IndexInfo instance.
54     *
55     * @see IndexInfoIterator::current()
56     * @see http://php.net/iterator.current
57     * @return IndexInfo
58     */
59    public function current()
60    {
61        $info = parent::current();
62
63        if (! array_key_exists('ns', $info) && $this->ns !== null) {
64            $info['ns'] = $this->ns;
65        }
66
67        return new IndexInfo($info);
68    }
69}
70