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