RuleFinder::findRule()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace SMW\ImageCaption;
4
5
use SMW\Schema\SchemaFilterFactory;
6
use SMW\Schema\SchemaFinder;
7
use SMW\Schema\SchemaFilter;
8
use SMW\Schema\Rule;
9
use SMW\Schema\CompartmentIterator;
10
11
/**
12
 * @license GNU GPL v2+
13
 * @since 1.0
14
 *
15
 * @author mwjames
16
 */
17
class RuleFinder {
18
19
	/**
20
	 * @var SchemaFinder
21
	 */
22
	private $schemaFinder;
23
24
	/**
25
	 * @var SchemaFilterFactory
26
	 */
27
	private $schemaFilterFactory;
28
29
	/**
30
	 * @since 1.0
31
	 *
32
	 * @param SchemaFinder $schemaFinder
33
	 * @param SchemaFilterFactory $schemaFilterFactory
34
	 */
35
	public function __construct( SchemaFinder $schemaFinder, SchemaFilterFactory $schemaFilterFactory ) {
36
		$this->schemaFinder = $schemaFinder;
37
		$this->schemaFilterFactory = $schemaFilterFactory;
38
	}
39
40
	/**
41
	 * @since 1.0
42
	 *
43
	 * @param array $categories
44
	 *
45
	 * @return Rule
46
	 */
47
	public function findRule( array $categories = [] ) : Rule {
48
49
		$schemaList = $this->schemaFinder->getSchemaListByType(
50
			ImageCaption::SCHEMA_TYPE
51
		);
52
53
		$rules = $schemaList->newCompartmentIteratorByKey(
54
			'caption_rules',
55
			CompartmentIterator::RULE_COMPARTMENT
56
		);
57
58
		$categoryFilter = $this->schemaFilterFactory->newCategoryFilter(
59
			$categories
60
		);
61
62
		$categoryFilter->filter( $rules );
63
64
		// Use the first "best" matched rule
65
		foreach ( $categoryFilter->getMatches() as $rule ) {
66
			return $rule;
67
		}
68
69
		return $rules->find( 'default_rule', CompartmentIterator::MATCH_KEY )->current();
70
	}
71
72
}
73