Passed
Push — dev ( 840a26...5b15b7 )
by Janko
18:04
created

AnomalyHandling   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 85%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 49
ccs 17
cts 20
cp 0.85
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A processExistingAnomalies() 0 11 3
A __construct() 0 6 1
A createNewAnomalies() 0 4 2
A decreaseLifespan() 0 10 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
    private AnomalyRepositoryInterface $anomalyRepository;
15
16
    /** @var array<AnomalyHandlerInterface> */
17
    private array $handlerList;
18
19
    /**
20
     * @param array<AnomalyHandlerInterface> $handlerList
21
     */
22 3
    public function __construct(
23
        AnomalyRepositoryInterface $anomalyRepository,
24
        array $handlerList
25
    ) {
26 3
        $this->anomalyRepository = $anomalyRepository;
27 3
        $this->handlerList = $handlerList;
28
    }
29
30 3
    public function processExistingAnomalies(): void
31
    {
32 3
        foreach ($this->anomalyRepository->findAll() as $anomaly) {
33 3
            if (!array_key_exists($anomaly->getAnomalyType()->getId(), $this->handlerList)) {
34 1
                throw new RuntimeException(sprintf('no handler defined for type: %d', $anomaly->getAnomalyType()->getId()));
35
            }
36
37 2
            $handler = $this->handlerList[$anomaly->getAnomalyType()->getId()];
38
39 2
            $handler->handleShipTick($anomaly);
40 2
            $this->decreaseLifespan($anomaly, $handler);
41
        }
42
    }
43
44
    public function createNewAnomalies(): void
45
    {
46
        foreach ($this->handlerList as $handler) {
47
            $handler->checkForCreation();
48
        }
49
    }
50
51 2
    private function decreaseLifespan(AnomalyInterface $anomaly, AnomalyHandlerInterface $handler): void
52
    {
53 2
        $remainingTicks = $anomaly->getRemainingTicks();
54
55 2
        if ($remainingTicks === 1) {
56 1
            $handler->letAnomalyDisappear($anomaly);
57 1
            $this->anomalyRepository->delete($anomaly);
58
        } else {
59 1
            $anomaly->setRemainingTicks($remainingTicks - 1);
60 1
            $this->anomalyRepository->save($anomaly);
61
        }
62
    }
63
}
64