Completed
Push — master ( 92913a...680cd6 )
by Jeroen De
03:27 queued 01:46
created

functions.php ➔ iterable_merge()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 4
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
declare( strict_types = 1 );
4
5
/**
6
 * @license GNU GPL v2+
7
 * @author Jeroen De Dauw < [email protected] >
8
 */
9
10
function iterable_to_array( iterable $iterable ): array {
11 13
	if ( is_array( $iterable ) ) {
12 7
		return $iterable;
13
	}
14
15 6
	return iterator_to_array( $iterable );
16
}
17
18
function iterable_to_iterator( iterable $iterable ): Iterator {
19 16
	if ( $iterable instanceof Iterator ) {
20 5
		return $iterable;
21
	}
22
23 11
	if ( is_array( $iterable ) ) {
24 7
		return new ArrayIterator( $iterable );
25
	}
26
27 4
	return new \WMDE\TraversableIterator\TraversableIterator( $iterable );
28
}
29
30
/**
31
 * array_merge clone for iterables using lazy evaluation
32
 *
33
 * As with array_merge, numeric elements with keys are assigned a fresh key,
34
 * starting with key 0. Unlike array_merge, elements with duplicate non-numeric
35
 * keys are kept in the Generator. Beware that when converting the Generator
36
 * to an array with a function such as iterator_to_array, these duplicates will
37
 * be dropped, resulting in identical behaviour as array_merge.
38
 *
39
 *
40
 * @param iterable ...$iterables
41
 * @return Generator
42
 */
43
function iterable_merge( iterable ...$iterables ): Generator {
44 11
	$numericIndex = 0;
45
46 11
	foreach ( $iterables as $iterable ) {
47 10
		foreach ( $iterable as $key => $value ) {
48 10
			yield is_int( $key ) ? $numericIndex++ : $key => $value;
49
		}
50
	}
51
}