ProgressByRatio::shouldNotifyChange()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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