summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Iterators/ResultIterator.php
blob: 31a6b9e500d930f8792ec83ac39f4b610d5f0b46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<?php

namespace SMW\Iterators;

use ArrayIterator;
use Countable;
use Iterator;
use ResultWrapper;
use RuntimeException;
use SeekableIterator;

/**
 * @license GNU GPL v2+
 * @since 2.5
 *
 * @author mwjames
 */
class ResultIterator implements Iterator, Countable, SeekableIterator {

	/**
	 * @var ResultWrapper
	 */
	public $res;

	/**
	 * @var integer
	 */
	public $position;

	/**
	 * @var mixed
	 */
	public $current;

	/**
	 * @var boolean
	 */
	public $numRows = false;

	/**
	 * @since 2.5
	 *
	 * @param Iterator|array $res
	 */
	public function __construct( $res ) {

		if ( !$res instanceof Iterator && !is_array( $res ) ) {
			throw new RuntimeException( "Expected an Iterator or array!" );
		}

		// @see MediaWiki's ResultWrapper
		if ( $res instanceof Iterator && method_exists( $res , 'numRows' ) ) {
			$this->numRows = true;
		}

		if ( is_array( $res ) ) {
			$res = new ArrayIterator( $res );
		}

		$this->res = $res;
		$this->position = 0;
		$this->setCurrent( $this->res->current() );
	}

	/**
	 * @see Countable::count
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function count() {
		return $this->numRows ? $this->res->numRows() : $this->res->count();
	}

	/**
	 * @see SeekableIterator::seek
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function seek( $position ) {
		$this->res->seek( $position );
		$this->setCurrent( $this->res->current() );
		$this->position = $position;
	}

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function current() {
		return $this->current;
	}

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function key() {
		return $this->position;
	}

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function next() {
		$row = $this->res->next();
		$this->setCurrent( $row );
		$this->position++;
	}

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function rewind() {
		$this->res->rewind();
		$this->position = 0;
		$this->setCurrent( $this->res->current() );
	}

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function valid() {
		return $this->current !== false;
	}

	protected function setCurrent( $row ) {
		if ( $row === false || $row === null ) {
			$this->current = false;
		} else {
			$this->current = $row;
		}
	}

}