Passed
Push — master ( bf35ce...0cc399 )
by Paul
09:08 queued 05:03
created
plugin/Modules/Rating.php 1 patch
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -4,207 +4,207 @@
 block discarded – undo
4 4
 
5 5
 class Rating
6 6
 {
7
-    /**
8
-     * The more sure we are of the confidence interval (the higher the confidence level), the less
9
-     * precise the estimation will be as the margin for error will be higher.
10
-     * @see http://homepages.math.uic.edu/~bpower6/stat101/Confidence%20Intervals.pdf
11
-     * @see https://www.thecalculator.co/math/Confidence-Interval-Calculator-210.html
12
-     * @see https://www.youtube.com/watch?v=grodoLzThy4
13
-     * @see https://en.wikipedia.org/wiki/Standard_score
14
-     * @var array
15
-     */
16
-    const CONFIDENCE_LEVEL_Z_SCORES = [
17
-        50 => 0.67449,
18
-        70 => 1.04,
19
-        75 => 1.15035,
20
-        80 => 1.282,
21
-        85 => 1.44,
22
-        90 => 1.64485,
23
-        92 => 1.75,
24
-        95 => 1.95996,
25
-        96 => 2.05,
26
-        97 => 2.17009,
27
-        98 => 2.326,
28
-        99 => 2.57583,
29
-        '99.5' => 2.81,
30
-        '99.8' => 3.08,
31
-        '99.9' => 3.29053,
32
-    ];
7
+	/**
8
+	 * The more sure we are of the confidence interval (the higher the confidence level), the less
9
+	 * precise the estimation will be as the margin for error will be higher.
10
+	 * @see http://homepages.math.uic.edu/~bpower6/stat101/Confidence%20Intervals.pdf
11
+	 * @see https://www.thecalculator.co/math/Confidence-Interval-Calculator-210.html
12
+	 * @see https://www.youtube.com/watch?v=grodoLzThy4
13
+	 * @see https://en.wikipedia.org/wiki/Standard_score
14
+	 * @var array
15
+	 */
16
+	const CONFIDENCE_LEVEL_Z_SCORES = [
17
+		50 => 0.67449,
18
+		70 => 1.04,
19
+		75 => 1.15035,
20
+		80 => 1.282,
21
+		85 => 1.44,
22
+		90 => 1.64485,
23
+		92 => 1.75,
24
+		95 => 1.95996,
25
+		96 => 2.05,
26
+		97 => 2.17009,
27
+		98 => 2.326,
28
+		99 => 2.57583,
29
+		'99.5' => 2.81,
30
+		'99.8' => 3.08,
31
+		'99.9' => 3.29053,
32
+	];
33 33
 
34
-    /**
35
-     * @var int
36
-     */
37
-    const MAX_RATING = 5;
34
+	/**
35
+	 * @var int
36
+	 */
37
+	const MAX_RATING = 5;
38 38
 
39
-    /**
40
-     * @var int
41
-     */
42
-    const MIN_RATING = 1;
39
+	/**
40
+	 * @var int
41
+	 */
42
+	const MIN_RATING = 1;
43 43
 
44
-    /**
45
-     * @param int $roundBy
46
-     * @return float
47
-     */
48
-    public function getAverage(array $ratingCounts, $roundBy = 1)
49
-    {
50
-        $average = array_sum($ratingCounts);
51
-        if ($average > 0) {
52
-            $average = $this->getTotalSum($ratingCounts) / $average;
53
-        }
54
-        $roundedAverage = round($average, intval($roundBy));
55
-        return floatval(apply_filters('site-reviews/rating/average', $roundedAverage, $ratingCounts, $average));
56
-    }
44
+	/**
45
+	 * @param int $roundBy
46
+	 * @return float
47
+	 */
48
+	public function getAverage(array $ratingCounts, $roundBy = 1)
49
+	{
50
+		$average = array_sum($ratingCounts);
51
+		if ($average > 0) {
52
+			$average = $this->getTotalSum($ratingCounts) / $average;
53
+		}
54
+		$roundedAverage = round($average, intval($roundBy));
55
+		return floatval(apply_filters('site-reviews/rating/average', $roundedAverage, $ratingCounts, $average));
56
+	}
57 57
 
58
-    /**
59
-     * Get the lower bound for up/down ratings
60
-     * Method receives an up/down ratings array: [1, -1, -1, 1, 1, -1].
61
-     * @see http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
62
-     * @see https://news.ycombinator.com/item?id=10481507
63
-     * @see https://dataorigami.net/blogs/napkin-folding/79030467-an-algorithm-to-sort-top-comments
64
-     * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
65
-     * @param int $confidencePercentage
66
-     * @return int|float
67
-     */
68
-    public function getLowerBound(array $upDownCounts = [0, 0], $confidencePercentage = 95)
69
-    {
70
-        $numRatings = array_sum($upDownCounts);
71
-        if ($numRatings < 1) {
72
-            return 0;
73
-        }
74
-        $z = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
75
-        $phat = 1 * $upDownCounts[1] / $numRatings;
76
-        return ($phat + $z * $z / (2 * $numRatings) - $z * sqrt(($phat * (1 - $phat) + $z * $z / (4 * $numRatings)) / $numRatings)) / (1 + $z * $z / $numRatings);
77
-    }
58
+	/**
59
+	 * Get the lower bound for up/down ratings
60
+	 * Method receives an up/down ratings array: [1, -1, -1, 1, 1, -1].
61
+	 * @see http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
62
+	 * @see https://news.ycombinator.com/item?id=10481507
63
+	 * @see https://dataorigami.net/blogs/napkin-folding/79030467-an-algorithm-to-sort-top-comments
64
+	 * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
65
+	 * @param int $confidencePercentage
66
+	 * @return int|float
67
+	 */
68
+	public function getLowerBound(array $upDownCounts = [0, 0], $confidencePercentage = 95)
69
+	{
70
+		$numRatings = array_sum($upDownCounts);
71
+		if ($numRatings < 1) {
72
+			return 0;
73
+		}
74
+		$z = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
75
+		$phat = 1 * $upDownCounts[1] / $numRatings;
76
+		return ($phat + $z * $z / (2 * $numRatings) - $z * sqrt(($phat * (1 - $phat) + $z * $z / (4 * $numRatings)) / $numRatings)) / (1 + $z * $z / $numRatings);
77
+	}
78 78
 
79
-    /**
80
-     * @return int|float
81
-     */
82
-    public function getOverallPercentage(array $ratingCounts)
83
-    {
84
-        return round($this->getAverage($ratingCounts) * 100 / glsr()->constant('MAX_RATING', __CLASS__), 2);
85
-    }
79
+	/**
80
+	 * @return int|float
81
+	 */
82
+	public function getOverallPercentage(array $ratingCounts)
83
+	{
84
+		return round($this->getAverage($ratingCounts) * 100 / glsr()->constant('MAX_RATING', __CLASS__), 2);
85
+	}
86 86
 
87
-    /**
88
-     * @return array
89
-     */
90
-    public function getPercentages(array $ratingCounts)
91
-    {
92
-        $total = array_sum($ratingCounts);
93
-        foreach ($ratingCounts as $index => $count) {
94
-            if (empty($count)) {
95
-                continue;
96
-            }
97
-            $ratingCounts[$index] = $count / $total * 100;
98
-        }
99
-        return $this->getRoundedPercentages($ratingCounts);
100
-    }
87
+	/**
88
+	 * @return array
89
+	 */
90
+	public function getPercentages(array $ratingCounts)
91
+	{
92
+		$total = array_sum($ratingCounts);
93
+		foreach ($ratingCounts as $index => $count) {
94
+			if (empty($count)) {
95
+				continue;
96
+			}
97
+			$ratingCounts[$index] = $count / $total * 100;
98
+		}
99
+		return $this->getRoundedPercentages($ratingCounts);
100
+	}
101 101
 
102
-    /**
103
-     * @return float
104
-     */
105
-    public function getRanking(array $ratingCounts)
106
-    {
107
-        return floatval(apply_filters('site-reviews/rating/ranking',
108
-            $this->getRankingUsingImdb($ratingCounts),
109
-            $ratingCounts,
110
-            $this
111
-        ));
112
-    }
102
+	/**
103
+	 * @return float
104
+	 */
105
+	public function getRanking(array $ratingCounts)
106
+	{
107
+		return floatval(apply_filters('site-reviews/rating/ranking',
108
+			$this->getRankingUsingImdb($ratingCounts),
109
+			$ratingCounts,
110
+			$this
111
+		));
112
+	}
113 113
 
114
-    /**
115
-     * Get the bayesian ranking for an array of reviews
116
-     * This formula is the same one used by IMDB to rank their top 250 films.
117
-     * @see https://www.xkcd.com/937/
118
-     * @see https://districtdatalabs.silvrback.com/computing-a-bayesian-estimate-of-star-rating-means
119
-     * @see http://fulmicoton.com/posts/bayesian_rating/
120
-     * @see https://stats.stackexchange.com/questions/93974/is-there-an-equivalent-to-lower-bound-of-wilson-score-confidence-interval-for-va
121
-     * @param int $confidencePercentage
122
-     * @return int|float
123
-     */
124
-    public function getRankingUsingImdb(array $ratingCounts, $confidencePercentage = 70)
125
-    {
126
-        $avgRating = $this->getAverage($ratingCounts);
127
-        // Represents a prior (your prior opinion without data) for the average star rating. A higher prior also means a higher margin for error.
128
-        // This could also be the average score of all items instead of a fixed value.
129
-        $bayesMean = ($confidencePercentage / 100) * glsr()->constant('MAX_RATING', __CLASS__); // prior, 70% = 3.5
130
-        // Represents the number of ratings expected to begin observing a pattern that would put confidence in the prior.
131
-        $bayesMinimal = 10; // confidence
132
-        $numOfReviews = array_sum($ratingCounts);
133
-        return $avgRating > 0
134
-            ? (($bayesMinimal * $bayesMean) + ($avgRating * $numOfReviews)) / ($bayesMinimal + $numOfReviews)
135
-            : 0;
136
-    }
114
+	/**
115
+	 * Get the bayesian ranking for an array of reviews
116
+	 * This formula is the same one used by IMDB to rank their top 250 films.
117
+	 * @see https://www.xkcd.com/937/
118
+	 * @see https://districtdatalabs.silvrback.com/computing-a-bayesian-estimate-of-star-rating-means
119
+	 * @see http://fulmicoton.com/posts/bayesian_rating/
120
+	 * @see https://stats.stackexchange.com/questions/93974/is-there-an-equivalent-to-lower-bound-of-wilson-score-confidence-interval-for-va
121
+	 * @param int $confidencePercentage
122
+	 * @return int|float
123
+	 */
124
+	public function getRankingUsingImdb(array $ratingCounts, $confidencePercentage = 70)
125
+	{
126
+		$avgRating = $this->getAverage($ratingCounts);
127
+		// Represents a prior (your prior opinion without data) for the average star rating. A higher prior also means a higher margin for error.
128
+		// This could also be the average score of all items instead of a fixed value.
129
+		$bayesMean = ($confidencePercentage / 100) * glsr()->constant('MAX_RATING', __CLASS__); // prior, 70% = 3.5
130
+		// Represents the number of ratings expected to begin observing a pattern that would put confidence in the prior.
131
+		$bayesMinimal = 10; // confidence
132
+		$numOfReviews = array_sum($ratingCounts);
133
+		return $avgRating > 0
134
+			? (($bayesMinimal * $bayesMean) + ($avgRating * $numOfReviews)) / ($bayesMinimal + $numOfReviews)
135
+			: 0;
136
+	}
137 137
 
138
-    /**
139
-     * The quality of a 5 star rating depends not only on the average number of stars but also on
140
-     * the number of reviews. This method calculates the bayesian ranking of a page by its number
141
-     * of reviews and their rating.
142
-     * @see http://www.evanmiller.org/ranking-items-with-star-ratings.html
143
-     * @see https://stackoverflow.com/questions/1411199/what-is-a-better-way-to-sort-by-a-5-star-rating/1411268
144
-     * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
145
-     * @param int $confidencePercentage
146
-     * @return float
147
-     */
148
-    public function getRankingUsingZScores(array $ratingCounts, $confidencePercentage = 90)
149
-    {
150
-        $ratingCountsSum = array_sum($ratingCounts) + glsr()->constant('MAX_RATING', __CLASS__);
151
-        $weight = $this->getWeight($ratingCounts, $ratingCountsSum);
152
-        $weightPow2 = $this->getWeight($ratingCounts, $ratingCountsSum, true);
153
-        $zScore = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
154
-        return $weight - $zScore * sqrt(($weightPow2 - pow($weight, 2)) / ($ratingCountsSum + 1));
155
-    }
138
+	/**
139
+	 * The quality of a 5 star rating depends not only on the average number of stars but also on
140
+	 * the number of reviews. This method calculates the bayesian ranking of a page by its number
141
+	 * of reviews and their rating.
142
+	 * @see http://www.evanmiller.org/ranking-items-with-star-ratings.html
143
+	 * @see https://stackoverflow.com/questions/1411199/what-is-a-better-way-to-sort-by-a-5-star-rating/1411268
144
+	 * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
145
+	 * @param int $confidencePercentage
146
+	 * @return float
147
+	 */
148
+	public function getRankingUsingZScores(array $ratingCounts, $confidencePercentage = 90)
149
+	{
150
+		$ratingCountsSum = array_sum($ratingCounts) + glsr()->constant('MAX_RATING', __CLASS__);
151
+		$weight = $this->getWeight($ratingCounts, $ratingCountsSum);
152
+		$weightPow2 = $this->getWeight($ratingCounts, $ratingCountsSum, true);
153
+		$zScore = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
154
+		return $weight - $zScore * sqrt(($weightPow2 - pow($weight, 2)) / ($ratingCountsSum + 1));
155
+	}
156 156
 
157
-    /**
158
-     * @param int $target
159
-     * @return array
160
-     */
161
-    protected function getRoundedPercentages(array $percentages, $totalPercent = 100)
162
-    {
163
-        array_walk($percentages, function (&$percent, $index) {
164
-            $percent = [
165
-                'index' => $index,
166
-                'percent' => floor($percent),
167
-                'remainder' => fmod($percent, 1),
168
-            ];
169
-        });
170
-        $indexes = glsr_array_column($percentages, 'index');
171
-        $remainders = glsr_array_column($percentages, 'remainder');
172
-        array_multisort($remainders, SORT_DESC, SORT_STRING, $indexes, SORT_DESC, $percentages);
173
-        $i = 0;
174
-        if (array_sum(glsr_array_column($percentages, 'percent')) > 0) {
175
-            while (array_sum(glsr_array_column($percentages, 'percent')) < $totalPercent) {
176
-                ++$percentages[$i]['percent'];
177
-                ++$i;
178
-            }
179
-        }
180
-        array_multisort($indexes, SORT_DESC, $percentages);
181
-        return array_combine($indexes, glsr_array_column($percentages, 'percent'));
182
-    }
157
+	/**
158
+	 * @param int $target
159
+	 * @return array
160
+	 */
161
+	protected function getRoundedPercentages(array $percentages, $totalPercent = 100)
162
+	{
163
+		array_walk($percentages, function (&$percent, $index) {
164
+			$percent = [
165
+				'index' => $index,
166
+				'percent' => floor($percent),
167
+				'remainder' => fmod($percent, 1),
168
+			];
169
+		});
170
+		$indexes = glsr_array_column($percentages, 'index');
171
+		$remainders = glsr_array_column($percentages, 'remainder');
172
+		array_multisort($remainders, SORT_DESC, SORT_STRING, $indexes, SORT_DESC, $percentages);
173
+		$i = 0;
174
+		if (array_sum(glsr_array_column($percentages, 'percent')) > 0) {
175
+			while (array_sum(glsr_array_column($percentages, 'percent')) < $totalPercent) {
176
+				++$percentages[$i]['percent'];
177
+				++$i;
178
+			}
179
+		}
180
+		array_multisort($indexes, SORT_DESC, $percentages);
181
+		return array_combine($indexes, glsr_array_column($percentages, 'percent'));
182
+	}
183 183
 
184
-    /**
185
-     * @return int
186
-     */
187
-    protected function getTotalSum(array $ratingCounts)
188
-    {
189
-        return array_reduce(array_keys($ratingCounts), function ($carry, $index) use ($ratingCounts) {
190
-            return $carry + ($index * $ratingCounts[$index]);
191
-        });
192
-    }
184
+	/**
185
+	 * @return int
186
+	 */
187
+	protected function getTotalSum(array $ratingCounts)
188
+	{
189
+		return array_reduce(array_keys($ratingCounts), function ($carry, $index) use ($ratingCounts) {
190
+			return $carry + ($index * $ratingCounts[$index]);
191
+		});
192
+	}
193 193
 
194
-    /**
195
-     * @param int|float $ratingCountsSum
196
-     * @param bool $powerOf2
197
-     * @return float
198
-     */
199
-    protected function getWeight(array $ratingCounts, $ratingCountsSum, $powerOf2 = false)
200
-    {
201
-        return array_reduce(array_keys($ratingCounts),
202
-            function ($count, $rating) use ($ratingCounts, $ratingCountsSum, $powerOf2) {
203
-                $ratingLevel = $powerOf2
204
-                    ? pow($rating, 2)
205
-                    : $rating;
206
-                return $count + ($ratingLevel * ($ratingCounts[$rating] + 1)) / $ratingCountsSum;
207
-            }
208
-        );
209
-    }
194
+	/**
195
+	 * @param int|float $ratingCountsSum
196
+	 * @param bool $powerOf2
197
+	 * @return float
198
+	 */
199
+	protected function getWeight(array $ratingCounts, $ratingCountsSum, $powerOf2 = false)
200
+	{
201
+		return array_reduce(array_keys($ratingCounts),
202
+			function ($count, $rating) use ($ratingCounts, $ratingCountsSum, $powerOf2) {
203
+				$ratingLevel = $powerOf2
204
+					? pow($rating, 2)
205
+					: $rating;
206
+				return $count + ($ratingLevel * ($ratingCounts[$rating] + 1)) / $ratingCountsSum;
207
+			}
208
+		);
209
+	}
210 210
 }
Please login to merge, or discard this patch.