Passed
Push — develop ( c34e50...445d6d )
by Paul
06:42
created

StarRatingDefaults   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 28
dl 0
loc 52
ccs 0
cts 25
cp 0
rs 10
c 2
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A defaults() 0 10 1
A finalize() 0 17 4
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Defaults;
4
5
use GeminiLabs\SiteReviews\Modules\Rating;
6
7
class StarRatingDefaults extends DefaultsAbstract
8
{
9
    /**
10
     * The values that should be cast before sanitization is run.
11
     * This is done before $sanitize and $enums.
12
     */
13
    public array $casts = [
14
        'args' => 'array',
15
        'rating' => 'float',
16
    ];
17
18
    /**
19
     * The values that should be sanitized.
20
     * This is done after $casts and before $enums.
21
     */
22
    public array $sanitize = [
23
        'reviews' => 'min:0',
24
    ];
25
26
    protected function defaults(): array
27
    {
28
        return [
29
            'args' => [],
30
            'max_rating' => 0,
31
            'num_empty' => 0,
32
            'num_full' => 0,
33
            'num_half' => 0,
34
            'rating' => 0,
35
            'reviews' => 0,
36
        ];
37
    }
38
39
    /**
40
     * Finalize provided values, this always runs last.
41
     */
42
    protected function finalize(array $values = []): array
43
    {
44
        $max = Rating::max();
45
        $rating = $values['rating'] ?? 0;
46
        $reviews = $values['reviews'] ?? 0;
47
        $remainder = round($rating - floor($rating), 1); // round for reliable floating-point comparison
48
        $numFull = intval($remainder >= 0.9 ? ceil($rating) : floor($rating));
49
        $numHalf = intval(ceil($rating - $numFull));
50
        $numEmpty = max(0, $max - $numFull - $numHalf);
51
        $values['max_rating'] = $max;
52
        $values['num_empty'] = $numEmpty;
53
        $values['num_full'] = $numFull;
54
        $values['num_half'] = $numHalf;
55
        if (0 === $reviews && 0 === $numHalf) {
56
            $values['rating'] = $numFull; // integer
57
        }
58
        return $values;
59
    }
60
}
61