Test Failed
Push — develop ( 425fc0...4f2be8 )
by Paul
13:11
created

StarRatingDefaults   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 28
dl 0
loc 52
ccs 25
cts 25
cp 1
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 1
    protected function defaults(): array
27
    {
28 1
        return [
29 1
            'args' => [],
30 1
            'max_rating' => 0,
31 1
            'num_empty' => 0,
32 1
            'num_full' => 0,
33 1
            'num_half' => 0,
34 1
            'rating' => 0,
35 1
            'reviews' => 0,
36 1
        ];
37
    }
38
39
    /**
40
     * Finalize provided values, this always runs last.
41
     */
42 1
    protected function finalize(array $values = []): array
43
    {
44 1
        $max = Rating::max();
45 1
        $rating = $values['rating'] ?? 0;
46 1
        $reviews = $values['reviews'] ?? 0;
47 1
        $remainder = round($rating - floor($rating), 1); // round for reliable floating-point comparison
48 1
        $numFull = intval($remainder >= 0.9 ? ceil($rating) : floor($rating));
49 1
        $numHalf = intval(ceil($rating - $numFull));
50 1
        $numEmpty = max(0, $max - $numFull - $numHalf);
51 1
        $values['max_rating'] = $max;
52 1
        $values['num_empty'] = $numEmpty;
53 1
        $values['num_full'] = $numFull;
54 1
        $values['num_half'] = $numHalf;
55 1
        if (0 === $reviews && 0 === $numHalf) {
56 1
            $values['rating'] = $numFull; // integer
57
        }
58 1
        return $values;
59
    }
60
}
61