Passed
Pull Request — master (#1825)
by Nico
59:43 queued 25:38
created

AnomalyHandling   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 84.21%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 43
ccs 16
cts 19
cp 0.8421
rs 10
c 0
b 0
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A processExistingAnomalies() 0 13 3
A __construct() 0 4 1
A createNewAnomalies() 0 4 2
A decreaseLifespan() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Component\Anomaly;
6
7
use RuntimeException;
8
use Stu\Component\Anomaly\Type\AnomalyHandlerInterface;
9
use Stu\Orm\Entity\AnomalyInterface;
10
use Stu\Orm\Repository\AnomalyRepositoryInterface;
11
12
final class AnomalyHandling implements AnomalyHandlingInterface
13
{
14
    /**
15
     * @param array<int, AnomalyHandlerInterface> $handlerList
16
     */
17 3
    public function __construct(
18
        private AnomalyRepositoryInterface $anomalyRepository,
19
        private array $handlerList
20
    ) {
21 3
    }
22
23 3
    public function processExistingAnomalies(): void
24
    {
25 3
        foreach ($this->anomalyRepository->findAllActive() as $anomaly) {
26 3
            $type = $anomaly->getAnomalyType()->getId();
27
28 3
            if (!array_key_exists($type, $this->handlerList)) {
29 1
                throw new RuntimeException(sprintf('no handler defined for type: %d', $type));
30
            }
31
32 2
            $handler = $this->handlerList[$type];
33
34 2
            $handler->handleShipTick($anomaly);
35 2
            $this->decreaseLifespan($anomaly, $handler);
36
        }
37
    }
38
39
    public function createNewAnomalies(): void
40
    {
41
        foreach ($this->handlerList as $handler) {
42
            $handler->checkForCreation();
43
        }
44
    }
45
46 2
    private function decreaseLifespan(AnomalyInterface $anomaly, AnomalyHandlerInterface $handler): void
47
    {
48 2
        $remainingTicks = $anomaly->getRemainingTicks();
49
50 2
        if ($remainingTicks === 1) {
51 1
            $handler->letAnomalyDisappear($anomaly);
52
        }
53 2
        $anomaly->setRemainingTicks($remainingTicks - 1);
54 2
        $this->anomalyRepository->save($anomaly);
55
    }
56
}
57