Passed
Push — master ( fd4f11...882af9 )
by Nico
25:47
created

CommodityTransferStrategy   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 183
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 2 Features 0
Metric Value
eloc 102
c 3
b 2
f 0
dl 0
loc 183
ccs 0
cts 107
cp 0
rs 9.1199
wmc 41

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setTemplateVariables() 0 22 4
D transferPerShip() 0 77 20
A __construct() 0 6 1
A createStorageBar() 0 9 1
C transfer() 0 58 15

How to fix   Complexity   

Complex Class

Complex classes like CommodityTransferStrategy often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CommodityTransferStrategy, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Lib\Transfer\Strategy;
6
7
use Override;
0 ignored issues
show
Bug introduced by
The type Override was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use request;
9
use Stu\Lib\Information\InformationWrapper;
10
use Stu\Lib\Pirate\PirateReactionInterface;
11
use Stu\Lib\Pirate\PirateReactionTriggerEnum;
12
use Stu\Lib\Transfer\BeamUtilInterface;
13
use Stu\Module\Colony\Lib\ColonyLibFactoryInterface;
14
use Stu\Module\Control\GameControllerInterface;
15
use Stu\Module\Ship\Lib\ShipWrapperInterface;
16
use Stu\Module\Template\StatusBarColorEnum;
0 ignored issues
show
Bug introduced by
The type Stu\Module\Template\StatusBarColorEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Stu\Module\Template\StatusBarFactoryInterface;
18
use Stu\Orm\Entity\ColonyInterface;
19
use Stu\Orm\Entity\ShipInterface;
20
21
class CommodityTransferStrategy implements TransferStrategyInterface
22
{
23
    public function __construct(
24
        private ColonyLibFactoryInterface $colonyLibFactory,
25
        private BeamUtilInterface $beamUtil,
26
        private PirateReactionInterface $pirateReaction,
27
        private StatusBarFactoryInterface $statusBarFactory
28
    ) {}
29
30
    #[Override]
31
    public function setTemplateVariables(
32
        bool $isUnload,
33
        ShipInterface|ColonyInterface $source,
34
        ShipInterface|ColonyInterface $target,
35
        GameControllerInterface $game
36
    ): void {
37
38
        $game->setTemplateVar(
39
            'BEAMABLE_STORAGE',
40
            $isUnload ? $source->getBeamableStorage() : $target->getBeamableStorage()
41
        );
42
43
        if ($target instanceof ColonyInterface) {
44
            $game->setTemplateVar(
45
                'SHOW_SHIELD_FREQUENCY',
46
                $this->colonyLibFactory->createColonyShieldingManager($target)->isShieldingEnabled() && $target->getUser() !== $source->getUser()
47
            );
48
        }
49
50
        $game->setTemplateVar('SOURCE_STORAGE_BAR', $this->createStorageBar($source));
51
        $game->setTemplateVar('TARGET_STORAGE_BAR', $this->createStorageBar($target));
52
    }
53
54
    private function createStorageBar(ShipInterface|ColonyInterface $target): string
55
    {
56
        return $this->statusBarFactory
57
            ->createStatusBar()
58
            ->setColor(StatusBarColorEnum::STATUSBAR_GREEN)
59
            ->setLabel(_('Lager'))
60
            ->setMaxValue($target->getMaxStorage())
61
            ->setValue($target->getStorageSum())
62
            ->render();
63
    }
64
65
    #[Override]
66
    public function transfer(
67
        bool $isUnload,
68
        ShipWrapperInterface $wrapper,
69
        ShipInterface|ColonyInterface $target,
70
        InformationWrapper $informations
71
    ): void {
72
73
        $commodities = request::postArray('commodities');
74
        $gcount = request::postArray('count');
75
        if (count($commodities) == 0 || count($gcount) == 0) {
76
            $informations->addInformation(_("Es wurden keine Waren zum Beamen ausgewählt"));
77
            return;
78
        }
79
80
        $user = $wrapper->get()->getUser();
81
82
        if (
83
            $target instanceof ColonyInterface
84
            && $target->getUser() !== $user
85
            && $this->colonyLibFactory->createColonyShieldingManager($target)->isShieldingEnabled()
86
            && $target->getShieldFrequency() !== 0
87
        ) {
88
            $frequency = request::postInt('frequency');
89
            if ($frequency !== $target->getShieldFrequency()) {
90
                $informations->addInformation(_("Die Schildfrequenz ist nicht korrekt"));
91
                return;
92
            }
93
        }
94
95
        $hasTransfered = false;
96
97
        // check for fleet option
98
        $fleetWrapper = $wrapper->getFleetWrapper();
99
        if (request::postInt('isfleet') && $fleetWrapper !== null) {
100
            foreach ($fleetWrapper->getShipWrappers() as $wrapper) {
101
                if ($this->transferPerShip(
102
                    $isUnload,
103
                    $wrapper,
104
                    $target,
105
                    $informations
106
                )) {
107
                    $hasTransfered = true;
108
                }
109
            }
110
        } else {
111
            $hasTransfered =  $this->transferPerShip($isUnload, $wrapper, $target, $informations);
112
        }
113
114
        if (
115
            !$isUnload
116
            && $hasTransfered
117
            && $target instanceof ShipInterface
118
        ) {
119
            $this->pirateReaction->checkForPirateReaction(
120
                $target,
121
                PirateReactionTriggerEnum::ON_BEAM,
122
                $wrapper->get()
123
            );
124
        }
125
    }
126
127
    private function transferPerShip(
128
        bool $isUnload,
129
        ShipWrapperInterface $wrapper,
130
        ShipInterface|ColonyInterface $target,
131
        InformationWrapper $informations
132
    ): bool {
133
134
        $ship = $wrapper->get();
135
        $epsSystem = $wrapper->getEpsSystemData();
136
137
        //sanity checks
138
        $isDockTransfer = $this->beamUtil->isDockTransfer($ship, $target);
139
        if (!$isDockTransfer && ($epsSystem === null || $epsSystem->getEps() === 0)) {
140
            $informations->addInformation(_("Keine Energie vorhanden"));
141
            return false;
142
        }
143
        if ($ship->getCloakState()) {
144
            $informations->addInformation(_("Die Tarnung ist aktiviert"));
145
            return false;
146
        }
147
        if ($ship->isWarped()) {
148
            $informations->addInformation("Schiff befindet sich im Warp");
149
            return false;
150
        }
151
        if ($target instanceof ShipInterface && $target->isWarped()) {
152
            $informations->addInformation(sprintf(_('Die %s befindet sich im Warp'), $target->getName()));
153
            return false;
154
        }
155
156
        $transferTarget = $isUnload ? $target : $ship;
157
        if ($transferTarget->getMaxStorage() <= $transferTarget->getStorageSum()) {
158
            $informations->addInformation(sprintf(_('%s: Der Lagerraum ist voll'), $transferTarget->getName()));
159
            return false;
160
        }
161
162
        $commodities = request::postArray('commodities');
163
        $gcount = request::postArray('count');
164
165
        $storage = $isUnload ? $ship->getStorage() : $target->getStorage();
166
167
        if ($storage->isEmpty()) {
168
            $informations->addInformation(_("Keine Waren zum Beamen vorhanden"));
169
            return false;
170
        }
171
        if (count($commodities) == 0 || count($gcount) == 0) {
172
            $informations->addInformation(_("Es wurden keine Waren zum Beamen ausgewählt"));
173
            return false;
174
        }
175
        $informations->addInformation(sprintf(
176
            _('Die %s hat folgende Waren %s %s %s transferiert'),
177
            $ship->getName(),
178
            $isUnload ? 'zur' : 'von der',
179
            $target instanceof ColonyInterface ? 'Kolonie' : '',
180
            $target->getName()
181
        ));
182
183
        $hasTransfered = false;
184
        foreach ($commodities as $key => $value) {
185
            $commodityId = (int) $value;
186
187
            if (!array_key_exists($key, $gcount)) {
188
                continue;
189
            }
190
191
            if ($this->beamUtil->transferCommodity(
192
                $commodityId,
193
                $gcount[$key],
194
                $wrapper,
195
                $isUnload ? $ship : $target,
196
                $transferTarget,
197
                $informations
198
            )) {
199
                $hasTransfered = true;
200
            }
201
        }
202
203
        return $hasTransfered;
204
    }
205
}
206