Passed
Push — master ( d8de29...20c7ec )
by Jeroen De
36s
created

InMemoryTermIdsAcquirer   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 0
dl 0
loc 60
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A acquireTermIds() 0 19 5
B cleanTerms() 0 18 7
A hasTerms() 0 14 1
1
<?php
2
3
namespace Wikibase\TermStore\MediaWiki\PackagePrivate;
4
5
class InMemoryTermIdsAcquirer implements TermIdsAcquirer, TermCleaner {
6
7
	private $terms = [];
8
	private $lastId = 0;
9
10
	public function acquireTermIds( array $termsArray ): array {
11
		$ids = [];
12
13
		foreach ( $termsArray as $type => $termsOfType ) {
14
			foreach ( $termsOfType as $lang => $terms ) {
15
				$terms = (array)$terms;
16
17
				foreach ( $terms as $term ) {
18
					if ( !isset( $this->terms[$type][$lang][$term] ) ) {
19
						$this->terms[$type][$lang][$term] = ++$this->lastId;
20
					}
21
22
					$ids[] = $this->terms[$type][$lang][$term];
23
				}
24
			}
25
		}
26
27
		return $ids;
28
	}
29
30
	public function cleanTerms( array $termInLangIds ) {
31
		$termInLangIdsAsKeys = array_flip( $termInLangIds );
32
		foreach ( $this->terms as $type => &$termsOfType ) {
33
			foreach ( $termsOfType as $lang => &$termsOfLang ) {
34
				foreach ( $termsOfLang as $term => $id ) {
35
					if ( array_key_exists( $id, $termInLangIdsAsKeys ) ) {
36
						unset( $termsOfLang[$term] );
37
					}
38
				}
39
				if ( $termsOfLang === [] ) {
40
					unset( $termsOfType[$lang] );
41
				}
42
			}
43
			if ( $termsOfType === [] ) {
44
				unset( $this->terms[$type] );
45
			}
46
		}
47
	}
48
49
	public function hasTerms() {
50
		$empty = true;
51
		// if there's any leaf element in terms then it's not empty, otherwise we consider
52
		// the terms array empty even if it had some sub-arrays that are also empty by
53
		// this definition
54
		array_walk_recursive(
55
			$this->terms,
56
			function ( $element ) use ( &$empty ) {
0 ignored issues
show
Unused Code introduced by
The parameter $element is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
57
				$empty = false;
58
			}
59
		);
60
61
		return !$empty;
62
	}
63
64
}
65