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

AnomalyHandling::processExistingAnomalies()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 3
rs 10
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