ProgressByRatio::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 4
dl 0
loc 12
ccs 5
cts 5
cp 1
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EngineWorks\ProgressStatus;
6
7
use InvalidArgumentException;
8
use SplObserver;
9
10
class ProgressByRatio extends Progress
11
{
12
    /** @var float */
13
    private $ratio;
14
15
    /** @var int */
16
    private $precision;
17
18
    /**
19
     * ProgressByRatio constructor.
20
     *
21
     * @param Status|null $status
22
     * @param iterable<SplObserver> $observers
23
     * @param float $ratio
24
     * @param int $precision
25
     */
26
    public function __construct(
27 9
        ?Status $status = null,
28
        iterable $observers = [],
29
        float $ratio = 0.01,
30
        int $precision = 2
31
    ) {
32
        parent::__construct($status, $observers);
33 9
        if ($precision < 0) {
34 9
            throw new InvalidArgumentException('Precision must be an positive integer');
35 1
        }
36
        $this->precision = $precision;
37 8
        $this->ratio = max(round($ratio, $this->precision), 10 ** (-$this->precision));
38 8
    }
39
40
    /** @noinspection PhpMissingParentCallCommonInspection */
41
    public function shouldNotifyChange(Status $current, Status $newStatus): bool
42 1
    {
43
        $current = (int) ceil(round($current->getRatio(), $this->precision) / $this->ratio);
44 1
        $new = (int) ceil(round($newStatus->getRatio(), $this->precision) / $this->ratio);
45 1
        return $current !== $new;
46 1
    }
47
48
    public function getRatio(): float
49 5
    {
50
        return $this->ratio;
51 5
    }
52
53
    public function getPrecision(): int
54 4
    {
55
        return $this->precision;
56 4
    }
57
}
58