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     * @param FunctionScore $container
42     */
43    public function append( FunctionScore $container ) {
44        $mi = new \MultipleIterator( \MultipleIterator::MIT_NEED_ALL | \MultipleIterator::MIT_KEYS_NUMERIC );
45        $mi->attachIterator( new \ArrayIterator( $this->boostedQueries ) );
46        $mi->attachIterator( new \ArrayIterator( $this->weights ) );
47
48        foreach ( $mi as [ $query, $weight ] ) {
49            if ( $weight < 0 ) {
50                $mustNotQuery = new BoolQuery();
51                $mustNotQuery->addMustNot( $query );
52
53                $weight *= -1;
54                $query = $mustNotQuery;
55            }
56
57            $container->addWeightFunction( $weight, $query );
58        }
59    }
60}