summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Iterators/MappingIterator.php
blob: 0aa398885c7ca19eb8a7ac72fe46f1d1ad2762fb (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
<?php

namespace SMW\Iterators;

use ArrayIterator;
use Countable;
use Iterator;
use IteratorIterator;
use RuntimeException;

/**
 * This iterator is expected to be called in combination with another iterator
 * (or traversable/array) in order to apply a mapping on the returned current element
 * during an iterative (foreach etc.) process.
 *
 * @license GNU GPL v2+
 * @since 2.5
 *
 * @author mwjames
 */
class MappingIterator extends IteratorIterator implements Countable {

	/**
	 * @var callable
	 */
	private $callback;

	/**
	 * @var integer
	 */
	private $count = 1;

	/**
	 * @since 2.5
	 *
	 * @param Iterator|array $iterable
	 * @param callable  $callback
	 */
	public function __construct( $iterable, callable $callback ) {

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

		if ( !$iterable instanceof Iterator ) {
			throw new RuntimeException( "MappingIterator expected an Iterator" );
		}

		if ( $iterable instanceof Countable ) {
			$this->count = $iterable->count();
		}

		parent::__construct( $iterable );
		$this->callback = $callback;
	}

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

	/**
	 * @since 2.5
	 *
	 * {@inheritDoc}
	 */
	public function current() {
		return call_user_func( $this->callback, parent::current() );
	}

}