Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
94.12% |
16 / 17 |
|
75.00% |
3 / 4 |
CRAP | |
0.00% |
0 / 1 |
ContextualProfileOverride | |
94.12% |
16 / 17 |
|
75.00% |
3 / 4 |
7.01 | |
0.00% |
0 / 1 |
__construct | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
2.03 | |||
priority | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getOverriddenName | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
explain | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | namespace CirrusSearch\Profile; |
4 | |
5 | /** |
6 | * Overrider that generates a name from a template and |
7 | * contextual information from the profile request. |
8 | * Known "context values" are: |
9 | * - "language": defaults to language code from \IContextSource::getLanguage() |
10 | * @see \IContextSource::getLanguage() |
11 | */ |
12 | class ContextualProfileOverride implements SearchProfileOverride { |
13 | /** |
14 | * Language code context, defaults to current context language |
15 | * @see \IContextSource::getLanguage() |
16 | */ |
17 | public const LANGUAGE = 'language'; |
18 | |
19 | /** @var string */ |
20 | private $template; |
21 | |
22 | /** @var array */ |
23 | private $params; |
24 | |
25 | /** @var int */ |
26 | private $priority; |
27 | |
28 | /** |
29 | * @param string $template A templated profile name |
30 | * @param string[] $params Map from string in $template to context parameter |
31 | * to replace with. All parameters must be available in the context |
32 | * parameters or no override will be applied. |
33 | * @param int $priority |
34 | */ |
35 | public function __construct( $template, array $params, $priority = SearchProfileOverride::CONTEXTUAL_PRIO ) { |
36 | if ( !$params ) { |
37 | throw new \InvalidArgumentException( 'Must provide at least 1 parameter' ); |
38 | } |
39 | $this->template = $template; |
40 | $this->params = $params; |
41 | $this->priority = $priority; |
42 | } |
43 | |
44 | /** |
45 | * The priority of this override, lower wins. |
46 | * @return int |
47 | */ |
48 | public function priority() { |
49 | return $this->priority; |
50 | } |
51 | |
52 | /** |
53 | * Get the overridden name or null if it cannot be overridden. |
54 | * @param string[] $contextParams |
55 | * @return string|null |
56 | */ |
57 | public function getOverriddenName( array $contextParams ) { |
58 | $replacePairs = []; |
59 | foreach ( $this->params as $pattern => $param ) { |
60 | if ( !isset( $contextParams[$param] ) ) { |
61 | return null; |
62 | } |
63 | $replacePairs[$pattern] = $contextParams[$param]; |
64 | } |
65 | return strtr( $this->template, $replacePairs ); |
66 | } |
67 | |
68 | /** |
69 | * @return array |
70 | */ |
71 | public function explain(): array { |
72 | return [ |
73 | 'type' => 'contextual', |
74 | 'priority' => $this->priority(), |
75 | 'template' => $this->template |
76 | ]; |
77 | } |
78 | } |