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 RequestContext;
8
9/**
10 * Boosts documents in user language and in wiki language if different
11 * Uses getUserLanguage in SearchConfig and LanguageCode for language values
12 * and CirrusSearchLanguageWeight['user'|'wiki'] for respective weights.
13 */
14class LangWeightFunctionScoreBuilder extends FunctionScoreBuilder {
15    /**
16     * @var string user language
17     */
18    private $userLang;
19
20    /**
21     * @var float user language weight
22     */
23    private $userWeight;
24
25    /**
26     * @var string wiki language
27     */
28    private $wikiLang;
29
30    /**
31     * @var float wiki language weight
32     */
33    private $wikiWeight;
34
35    /**
36     * @param SearchConfig $config
37     * @param float $weight
38     * @param string|null $userLang
39     */
40    public function __construct( SearchConfig $config, $weight, $userLang = null ) {
41        parent::__construct( $config, $weight );
42        $this->userLang = $userLang;
43        $this->userWeight =
44            $config->getElement( 'CirrusSearchLanguageWeight', 'user' );
45        $this->wikiLang = $config->get( 'LanguageCode' );
46        $this->wikiWeight =
47            $config->getElement( 'CirrusSearchLanguageWeight', 'wiki' );
48    }
49
50    public function append( FunctionScore $functionScore ) {
51        // Boost pages in a user's language
52        $userLang = $this->getUserLang();
53        if ( $this->userWeight ) {
54            $functionScore->addWeightFunction( $this->userWeight * $this->weight,
55                new \Elastica\Query\Term( [ 'language' => $userLang ] ) );
56        }
57
58        // And a wiki's language, if it's different
59        if ( $this->wikiWeight && $this->userLang != $this->wikiLang ) {
60            $functionScore->addWeightFunction( $this->wikiWeight * $this->weight,
61                new \Elastica\Query\Term( [ 'language' => $this->wikiLang ] ) );
62        }
63    }
64
65    private function getUserLang() {
66        if ( $this->userLang === null ) {
67            $this->userLang = RequestContext::getMain()->getLanguage()->getCode();
68        }
69        return $this->userLang;
70    }
71}