Passed
Push — master ( f4068b...77f637 )
by Nico
40:27 queued 14:09
created

ColonyProductionPreviewWrapper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 8
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Module\Colony\Lib;
6
7
use Stu\Lib\ColonyProduction\ColonyProduction;
8
use Stu\Orm\Repository\BuildingCommodityRepositoryInterface;
9
10
class ColonyProductionPreviewWrapper
11
{
12
    private ColonyLibFactoryInterface $colonyLibFactory;
13
14
    private BuildingCommodityRepositoryInterface $buildingCommodityRepository;
15
16
17
    /** @var array<ColonyProduction> */
18
    private array $production = [];
19
20
    /** @var array<int, array<ColonyProduction>> */
21
    private array $preview = [];
22
23
    /**
24
     * @param array<ColonyProduction> $production
25
     */
26
    public function __construct(
27
        ColonyLibFactoryInterface $colonyLibFactory,
28
        BuildingCommodityRepositoryInterface $buildingCommodityRepository,
29
        array $production
30
    ) {
31
        $this->colonyLibFactory = $colonyLibFactory;
32
        $this->buildingCommodityRepository = $buildingCommodityRepository;
33
        $this->production = $production;
34
    }
35
36
    /**
37
     * @param int|string $buildingId
38
     *
39
     * @return array<ColonyProduction>
40
     */
41
    public function __get($buildingId): array
42
    {
43
        $bid = (int) $buildingId;
44
45
        if (!array_key_exists($bid, $this->preview)) {
46
            $this->preview[$bid] = $this->loadPreview($bid);
47
        }
48
49
        return $this->preview[$bid];
50
    }
51
52
    /** @return array<ColonyProduction> */
53
    private function loadPreview(int $buildingId): array
54
    {
55
        $bcommodities = $this->buildingCommodityRepository->getByBuilding($buildingId);
56
57
        /** @var array<ColonyProduction> */
58
        $ret = [];
59
        foreach ($bcommodities as $commodityId => $prod) {
60
            $commodityId = $prod->getCommodityId();
61
            if (array_key_exists($commodityId, $this->production)) {
62
63
                $ret[$commodityId] = clone $this->production[$commodityId];
64
                $ret[$commodityId]->upperProduction($prod->getAmount());
65
            } else {
66
67
                $obj = $this->colonyLibFactory->createColonyProduction(
68
                    $prod->getCommodity(),
69
                    $prod->getAmount()
70
                );
71
                $ret[$commodityId] = $obj;
72
            }
73
74
            $ret[$commodityId]->setPreviewProduction($prod->getAmount());
75
        }
76
77
        return $ret;
78
    }
79
}
80