Passed
Push — master ( de3d61...be839c )
by Alec
13:42 queued 13s
created

WidgetIntervalContainer::add()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core\Widget;
6
7
use AlecRabbit\Spinner\Contract\IInterval;
8
use AlecRabbit\Spinner\Core\Widget\Contract\IWidgetIntervalContainer;
9
use WeakMap;
10
11
final class WidgetIntervalContainer implements IWidgetIntervalContainer
12
{
13
    protected ?IInterval $smallest = null;
14
15
    public function __construct(
16
        protected readonly WeakMap $map = new WeakMap(),
17
    ) {
18
    }
19
20
    public function getSmallest(): ?IInterval
21
    {
22
        return $this->smallest;
23
    }
24
25
    public function add(IInterval $interval): void
26
    {
27
        $this->map->offsetSet($interval, $interval);
28
        $this->updateSmallestOnAdd($interval);
29
    }
30
31
    private function updateSmallestOnAdd(IInterval $interval): void
32
    {
33
        if (null === $this->smallest) {
34
            $this->smallest = $interval;
35
            return;
36
        }
37
        $this->smallest = $this->smallest->smallest($interval);
38
    }
39
40
    public function remove(IInterval $interval): void
41
    {
42
        if ($this->map->offsetExists($interval)) {
43
            $this->map->offsetUnset($interval);
44
            $this->updateSmallestOnRemove($interval);
45
        }
46
    }
47
48
    private function updateSmallestOnRemove(IInterval $interval): void
49
    {
50
        if ($interval === $this->smallest) {
51
            $this->smallest = null;
52
            foreach ($this->map as $i) {
53
                $this->updateSmallestOnAdd($i);
54
            }
55
        }
56
    }
57
}
58