EntityIdListNormalizer::getRange()   B
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.0131

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 13
cts 14
cp 0.9286
rs 8.8817
c 0
b 0
f 0
cc 6
nc 5
nop 1
crap 6.0131
1
<?php
2
3
namespace Queryr\Replicator;
4
5
use InvalidArgumentException;
6
use Iterator;
7
use Wikibase\DataModel\Entity\EntityId;
8
use Wikibase\DataModel\Entity\EntityIdParser;
9
use Wikibase\DataModel\Entity\EntityIdParsingException;
10
use Wikibase\DataModel\Entity\ItemId;
11
use Wikibase\DataModel\Entity\PropertyId;
12
13
/**
14
 * @licence GNU GPL v2+
15
 * @author Jeroen De Dauw < [email protected] >
16
 */
17
class EntityIdListNormalizer {
18
19
	private $idParser;
20
21 10
	public function __construct( EntityIdParser $idParser ) {
22 10
		$this->idParser = $idParser;
23 10
	}
24
25
	/**
26
	 * @param string[] $ids
27
	 *
28
	 * @return Iterator
29
	 * @throws InvalidArgumentException
30
	 */
31 9
	public function getNormalized( array $ids ): Iterator {
32 9
		foreach ( $ids as $id ) {
33 8
			if ( strpos( $id, '-' ) !== false ) {
34 5
				foreach ( $this->getRange( $id ) as $resultId ) {
35 2
					yield $resultId;
36
				}
37
			}
38
			else {
39 5
				yield $this->getParsedId( $id );
40
			}
41
		}
42 5
	}
43
44 5
	private function getRange( string $id ): Iterator {
45 5
		$parts = explode( '-', $id, 2 );
46
47 5
		$startId = $this->getParsedId( $parts[0] );
48 5
		$endId = $this->getParsedId( $parts[1] );
49
50 4
		if ( $startId->getEntityType() !== $endId->getEntityType() ) {
51 1
			throw new InvalidArgumentException( 'Entity ids in the same range need to be of the same type' );
52
		}
53
54 3
		if ( !( $startId instanceof ItemId ) && !( $startId instanceof PropertyId ) ) {
55
			throw new InvalidArgumentException( 'ID type is not supported' );
56
		}
57
		/**
58
		 * @var ItemId|PropertyId $endId
59
		 */
60
61 3
		if ( $startId->getNumericId() > $endId->getNumericId()  ) {
62 1
			throw new InvalidArgumentException( 'The end of the range needs to be bigger than its start' );
63
		}
64
65 2
		$numericId = $endId->getNumericId();
66 2
		for ( $i = $startId->getNumericId(); $i <= $numericId; $i++ ) {
67 2
			yield $startId::newFromNumber( $i );
68
		}
69 2
	}
70
71 8
	private function getParsedId( string $id ): EntityId {
72
		try {
73 8
			return $this->idParser->parse( $id );
74
		}
75 2
		catch ( EntityIdParsingException $ex ) {
76 2
			throw new InvalidArgumentException( $ex->getMessage(), 0, $ex );
77
		}
78
	}
79
80
}
81