Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
BoostedQueriesFunction
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
2 / 2
4
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 append
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace CirrusSearch\Search\Rescore;
4
5use Elastica\Query\AbstractQuery;
6use Elastica\Query\BoolQuery;
7use Elastica\Query\FunctionScore;
8use Wikimedia\Assert\Assert;
9
10/**
11 * Simple list of weighted queries.
12 * @see FunctionScore::addWeightFunction()
13 */
14class BoostedQueriesFunction implements BoostFunctionBuilder {
15
16    /**
17     * @var AbstractQuery[]
18     */
19    private $boostedQueries;
20
21    /**
22     * @var float[]
23     */
24    private $weights;
25
26    /**
27     * Build a BoostedQueriesFunction using a list of queries and its associated weights.
28     * @param AbstractQuery[] $boostedQueries
29     * @param float[] $weights
30     */
31    public function __construct( array $boostedQueries, array $weights ) {
32        Assert::parameter( count( $boostedQueries ) === count( $weights ), '$weights',
33            '$weights must have the same number of elements as $boostedQueries' );
34        $this->boostedQueries = $boostedQueries;
35        $this->weights = $weights;
36    }
37
38    /**
39     * Append functions to the function score $container
40     */
41    public function append( FunctionScore $container ) {
42        $mi = new \MultipleIterator( \MultipleIterator::MIT_NEED_ALL | \MultipleIterator::MIT_KEYS_NUMERIC );
43        $mi->attachIterator( new \ArrayIterator( $this->boostedQueries ) );
44        $mi->attachIterator( new \ArrayIterator( $this->weights ) );
45
46        foreach ( $mi as [ $query, $weight ] ) {
47            if ( $weight < 0 ) {
48                $mustNotQuery = new BoolQuery();
49                $mustNotQuery->addMustNot( $query );
50
51                $weight *= -1;
52                $query = $mustNotQuery;
53            }
54
55            $container->addWeightFunction( $weight, $query );
56        }
57    }
58}