Completed
Push — master ( 0172d7...ac1295 )
by Seth
01:53
created

Relevance::add()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace smtech\StMarksSearch;
4
5
/**
6
 * Description of a search result's relevance, with rationales
7
 *
8
 * @author Seth Battis <[email protected]>
9
 */
10
class Relevance
11
{
12
    const EXACT_MATCH = 5;
13
14
    /**
15
     * Relevance score
16
     *
17
     * Ideally in a range from 0-10, with 5 indicating a fundamentally useful
18
     * result.
19
     *
20
     * @var float
21
     */
22
    private $score;
23
24
    /**
25
     * A list of rationales indicating how the relevance score was generated.
26
     *
27
     * @var string[]
28
     */
29
    private $rationales = [];
30
31
    /**
32
     * Construct a Relevance object
33
     *
34
     * @param float $score (Optional, defaults to 0.0)
35
     * @param string $rationale (Optional, defaults to `"Base value"` if
36
     *                          `$score` is non-zero`)
37
     */
38
    public function __construct($score = 0.0, $rationale = "Base value")
39
    {
40
        $this->score = $score;
41
        if ($score > 0) {
42
            $this->rationales[] = "$score: $rationale";
43
        }
44
    }
45
46
    /**
47
     * Add to the relevance of a score
48
     *
49
     * Or, one presumes, subtract, if `$scoreIncrement` is negative!
50
     *
51
     * @param float $scoreIncrement
52
     * @param string $rationale Rationale for this particular increment
53
     */
54
    public function add($scoreIncrement, $rationale)
55
    {
56
        $this->score += $scoreIncrement;
57
        $this->rationales[] = round($scoreIncrement, 2) . ": $rationale";
58
    }
59
60
    /**
61
     * Relevance score (ideally 0-10, with 5 indicating a fundamentally useful
62
     * result)
63
     *
64
     * @return float
65
     */
66
    public function getScore()
67
    {
68
        return $this->score;
69
    }
70
71
    /**
72
     * List of rationale's for how the relevance score was calculated
73
     *
74
     * @param  string $separator (Optional, defaults to `', '`)
75
     * @return string List of scoring rationales
76
     */
77
    public function getRationale($separator = ', ')
78
    {
79
        return implode($separator, $this->rationales);
80
    }
81
82
    public static function stringProportion($haystack, $needle)
83
    {
84
        if (preg_match("/$needle/i", $haystack, $matches) !== 1) {
85
            return 0.0;
86
        } else {
87
            return self::EXACT_MATCH * strlen($needle) * count($matches) / strlen($haystack);
88
        }
89
    }
90
}
91