Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.75% covered (success)
93.75%
15 / 16
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
LangWeightFunctionScoreBuilder
93.75% covered (success)
93.75%
15 / 16
66.67% covered (warning)
66.67%
2 / 3
7.01
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 append
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 getUserLang
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
1<?php
2
3namespace CirrusSearch\Search\Rescore;
4
5use CirrusSearch\CirrusConfigNames;
6use CirrusSearch\SearchConfig;
7use Elastica\Query\FunctionScore;
8use MediaWiki\Context\RequestContext;
9use MediaWiki\MainConfigNames;
10
11/**
12 * Boosts documents in user language and in wiki language if different
13 * Uses getUserLanguage in SearchConfig and LanguageCode for language values
14 * and CirrusSearchLanguageWeight['user'|'wiki'] for respective weights.
15 */
16class LangWeightFunctionScoreBuilder extends FunctionScoreBuilder {
17    /**
18     * @var string user language
19     */
20    private $userLang;
21
22    /**
23     * @var float user language weight
24     */
25    private $userWeight;
26
27    /**
28     * @var string wiki language
29     */
30    private $wikiLang;
31
32    /**
33     * @var float wiki language weight
34     */
35    private $wikiWeight;
36
37    /**
38     * @param SearchConfig $config
39     * @param float $weight
40     * @param string|null $userLang
41     */
42    public function __construct( SearchConfig $config, $weight, $userLang = null ) {
43        parent::__construct( $config, $weight );
44        $this->userLang = $userLang;
45        $this->userWeight =
46            $config->getElement( CirrusConfigNames::LanguageWeight, 'user' );
47        $this->wikiLang = $config->get( MainConfigNames::LanguageCode );
48        $this->wikiWeight =
49            $config->getElement( CirrusConfigNames::LanguageWeight, 'wiki' );
50    }
51
52    public function append( FunctionScore $functionScore ) {
53        // Boost pages in a user's language
54        if ( $this->userWeight ) {
55            $functionScore->addWeightFunction( $this->userWeight * $this->weight,
56                new \Elastica\Query\Term( [ 'language' => $this->getUserLang() ] ) );
57        }
58
59        // And a wiki's language, if it's different
60        if ( $this->wikiWeight && $this->getUserLang() != $this->wikiLang ) {
61            $functionScore->addWeightFunction( $this->wikiWeight * $this->weight,
62                new \Elastica\Query\Term( [ 'language' => $this->wikiLang ] ) );
63        }
64    }
65
66    private function getUserLang(): string {
67        if ( $this->userLang === null ) {
68            $this->userLang = RequestContext::getMain()->getLanguage()->getCode();
69        }
70        return $this->userLang;
71    }
72}