Test Failed
Push — dev ( 2a033c...9ed769 )
by Nico
21:17 queued 07:42
created

TwigHelper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
c 0
b 0
f 0
nc 1
nop 13
dl 0
loc 15
ccs 2
cts 2
cp 1
crap 1
rs 10

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Module\Twig;
6
7
use JBBCode\Parser;
8
use Noodlehaus\ConfigInterface;
9
use Stu\Component\Building\NameAbbreviations;
0 ignored issues
show
Bug introduced by
The type Stu\Component\Building\NameAbbreviations 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...
10
use Stu\Component\Colony\ColonyMenuEnum;
11
use Stu\Component\Game\ModuleEnum;
12
use Stu\Component\Spacecraft\Crew\SpacecraftCrewCalculatorInterface;
13
use Stu\Component\Spacecraft\System\SpacecraftSystemTypeEnum;
14
use Stu\Component\Spacecraft\System\SpacecraftSystemWrapper;
15
use Stu\Component\Spacecraft\System\SpacecraftSystemWrapperFactoryInterface;
16
use Stu\Lib\Colony\PlanetFieldHostInterface;
17
use Stu\Lib\ModuleScreen\GradientColorInterface;
18
use Stu\Module\Colony\Lib\ColonyEpsProductionPreviewWrapper;
19
use Stu\Module\Colony\Lib\ColonyLibFactoryInterface;
20
use Stu\Module\Colony\Lib\ColonyProductionPreviewWrapper;
21
use Stu\Module\Control\AccessCheckInterface;
22
use Stu\Module\Control\AccessGrantedFeatureEnum;
23
use Stu\Module\Control\GameControllerInterface;
24
use Stu\Module\Control\StuRandom;
25
use Stu\Module\Control\StuTime;
26
use Stu\Module\Spacecraft\Lib\Battle\FightLibInterface;
27
use Stu\Module\Spacecraft\Lib\SpacecraftNfsItem;
28
use Stu\Module\Template\TemplateHelperInterface;
29
use Stu\Orm\Entity\AnomalyInterface;
30
use Stu\Orm\Entity\BuildingInterface;
31
use Stu\Orm\Entity\PlanetFieldInterface;
32
use Stu\Orm\Entity\SpacecraftInterface;
33
use Twig\Environment;
34
use Twig\TwigFilter;
35
use Twig\TwigFunction;
36
37
class TwigHelper
38
{
39 2
    public function __construct(
40
        private readonly GameControllerInterface $game,
41
        private readonly Environment $environment,
42
        private readonly Parser $parser,
43
        private readonly ConfigInterface $config,
44
        private readonly FightLibInterface $fightLib,
45
        private readonly ColonyLibFactoryInterface $colonyLibFactory,
46
        private readonly SpacecraftCrewCalculatorInterface $shipCrewCalculator,
47
        private readonly SpacecraftSystemWrapperFactoryInterface $spacecraftSystemWrapperFactory,
48
        private readonly GradientColorInterface $gradientColor,
49
        private readonly TemplateHelperInterface $templateHelper,
50
        private readonly AccessCheckInterface $accessCheck,
51
        private readonly StuTime $stuTime,
52
        private readonly StuRandom $stuRandom
53 2
    ) {}
54
55 2
    public function registerGlobalVariables(): void
56
    {
57 2
        $this->environment->addGlobal(
58 2
            'ASSET_PATHS',
59 2
            [
60 2
                'alliance' => $this->config->get('game.alliance_avatar_path'),
61 2
                'user' => $this->config->get('game.user_avatar_path'),
62 2
                'faction' => 'assets/rassen/',
63 2
            ]
64 2
        );
65
    }
66
67
    /**
68
     * Registers global available twig methods and filters
69
     */
70 2
    public function registerFiltersAndFunctions(): void
71
    {
72 2
        $this->registerFilters();
73 2
        $this->registerFunctions();
74
    }
75
76 108
    private function registerFilters(): void
77
    {
78 95
        $bbcode2txtFilter = new TwigFilter('bbcode2txt', fn($string): string => $this->parser->parse($string)->getAsText());
79 2
        $this->environment->addFilter($bbcode2txtFilter);
80
81 108
        $bbcodeFilter = new TwigFilter('bbcode', fn($string): string => $this->parser->parse($string)->getAsHTML(), ['is_safe' => ['html']]);
82 2
        $this->environment->addFilter($bbcodeFilter);
83
84 2
        $jsquoteFilter = new TwigFilter('jsquote', fn($string): string => $this->templateHelper->jsquote($string));
85 2
        $this->environment->addFilter($jsquoteFilter);
86
87 2
        $addPlusCharacterFilter = new TwigFilter('addPlusCharacter', function ($value): string {
88 9
            if (is_int($value)) {
89 9
                return $this->templateHelper->addPlusCharacter((string) $value);
90
            }
91 1
            return $this->templateHelper->addPlusCharacter($value);
92 2
        });
93 2
        $this->environment->addFilter($addPlusCharacterFilter);
94
95 2
        $formatSecondsFilter = new TwigFilter('formatSeconds', function ($value): string {
96 9
            if (is_int($value)) {
97 9
                return $this->templateHelper->formatSeconds((string) $value);
98
            }
99
            return $this->templateHelper->formatSeconds($value);
100 2
        });
101 2
        $this->environment->addFilter($formatSecondsFilter);
102
103 8
        $planetFieldTitleFilter = new TwigFilter('planetFieldTitle', fn($planetField): string => $this->templateHelper->getPlanetFieldTitle($planetField));
104 2
        $this->environment->addFilter($planetFieldTitleFilter);
105
106 3
        $planetFieldTypeDescriptionFilter = new TwigFilter('planetFieldTypeDescription', fn($id): string => $this->templateHelper->getPlanetFieldTypeDescription($id));
107 2
        $this->environment->addFilter($planetFieldTypeDescriptionFilter);
108
109 6
        $formatProductionValueFilter = new TwigFilter('formatProductionValue', fn($value): string => $this->templateHelper->formatProductionValue($value));
110 2
        $this->environment->addFilter($formatProductionValueFilter);
111
112 2
        $isPositiveFilter = new TwigFilter('isPositive', fn(int $value): bool => $value > 0);
113 2
        $this->environment->addFilter($isPositiveFilter);
114
115 12
        $stuDateTimeFilter = new TwigFilter('stuDateTime', fn($value): string => $this->stuTime->transformToStuDateTime($value));
116 2
        $this->environment->addFilter($stuDateTimeFilter);
117
118 8
        $stuDateFilter = new TwigFilter('stuDate', fn($value): string => $this->stuTime->transformToStuDate($value));
119 2
        $this->environment->addFilter($stuDateFilter);
120
121 10
        $nl2brFilter = new TwigFilter('nl2br', fn(string $value): string => nl2br($value));
122 2
        $this->environment->addFilter($nl2brFilter);
123
124 20
        $htmlSafeFilter = new TwigFilter('htmlSafe', fn(string $text): string => htmlspecialchars($text));
125 2
        $this->environment->addFilter($htmlSafeFilter);
126
127 2
        $adventDoorFilter = new TwigFilter('adventDoor', fn(AnomalyInterface $anomaly): int => (int)((120 - $anomaly->getRemainingTicks()) / 5) + 1);
128 2
        $this->environment->addFilter($adventDoorFilter);
129
130 3
        $shortNameFilter = new TwigFilter('shortName', fn(string $name): string => array_reduce(
131 3
            array_keys(NameAbbreviations::ABBREVIATIONS),
132 3
            fn(string $value, string $from): string => str_replace($from, NameAbbreviations::ABBREVIATIONS[$from], $value),
133 3
            $name
134 3
        ));
135 2
        $this->environment->addFilter($shortNameFilter);
136
137 3
        $getMaxCrewCountByShipFilter = new TwigFilter('getMaxCrewCountByShip', fn(SpacecraftInterface $spacecraft): int => $this->shipCrewCalculator->getMaxCrewCountByShip($spacecraft));
138 2
        $this->environment->addFilter($getMaxCrewCountByShipFilter);
139
140 4
        $numberWithThousandSeperatorFilter = new TwigFilter('numberWithThousandSeperator', fn($value): string => $this->templateHelper->getNumberWithThousandSeperator($value));
141 2
        $this->environment->addFilter($numberWithThousandSeperatorFilter);
142
    }
143
144 11
    private function registerFunctions(): void
145
    {
146 3
        $canAttackTargetFunction = new TwigFunction('canAttackTarget', fn(SpacecraftInterface $spacecraft, SpacecraftInterface|SpacecraftNfsItem $target): bool => $this->fightLib->canAttackTarget($spacecraft, $target));
147 2
        $this->environment->addFunction($canAttackTargetFunction);
148
149 3
        $getEpsProductionPreviewFunction = new TwigFunction('getEpsProductionPreview', fn(PlanetFieldHostInterface $host, BuildingInterface $building): ColonyEpsProductionPreviewWrapper => $this->colonyLibFactory->createEpsProductionPreviewWrapper($host, $building));
150 2
        $this->environment->addFunction($getEpsProductionPreviewFunction);
151
152 3
        $getCommodityProductionPreviewFunction = new TwigFunction('getCommodityProductionPreview', fn(PlanetFieldHostInterface $host, BuildingInterface $building): ColonyProductionPreviewWrapper => $this->colonyLibFactory->createColonyProductionPreviewWrapper($building, $host));
153 2
        $this->environment->addFunction($getCommodityProductionPreviewFunction);
154
155 7
        $getColonyMenuClassFunction = new TwigFunction('getColonyMenuClass', fn(ColonyMenuEnum $currentMenu, int $value): string => ColonyMenuEnum::getMenuClass($currentMenu, $value));
156 2
        $this->environment->addFunction($getColonyMenuClassFunction);
157
158 6
        $getViewFunction = new TwigFunction('getView', fn(string $value): ModuleEnum => ModuleEnum::from($value));
159 2
        $this->environment->addFunction($getViewFunction);
160
161 11
        $getUniqIdFunction = new TwigFunction('getUniqId', fn(): string => $this->stuRandom->uniqid());
162 2
        $this->environment->addFunction($getUniqIdFunction);
163
164 2
        $gradientColorFunction = new TwigFunction('gradientColor', fn(int $value, int $lowest, int $highest): string => $this->gradientColor->calculateGradientColor($value, $lowest, $highest));
165 2
        $this->environment->addFunction($gradientColorFunction);
166
167 2
        $gradientColorOverLimitFunction = new TwigFunction('gradientColorOverLimit', fn(int $value, int $lowest, int $highest): string => $this->gradientColor->calculateGradientColor(min($value, $highest), $lowest, $highest));
168 2
        $this->environment->addFunction($gradientColorOverLimitFunction);
169
170 6
        $stuDateFunction = new TwigFunction('stuDate', fn(string $format): string => $this->stuTime->date($format));
171 2
        $this->environment->addFunction($stuDateFunction);
172
173 8
        $dayNightPrefixFunction = new TwigFunction('getDayNightPrefix', fn(PlanetFieldInterface $field): string => $field->getDayNightPrefix($this->stuTime->time()));
174 2
        $this->environment->addFunction($dayNightPrefixFunction);
175
176 2
        $maskEmailFunction = new TwigFunction('maskEmail', fn(string $email): string => $this->maskEmail($email));
177 2
        $this->environment->addFunction($maskEmailFunction);
178
179 2
        $maskMobileFunction = new TwigFunction('maskMobile', fn(?string $mobile): string => $this->maskMobile($mobile));
180 2
        $this->environment->addFunction($maskMobileFunction);
181 2
182 2
        $hasSpacecraftSystemByNameFunction = new TwigFunction(
183 2
            'getSpacecraftSystemWrapper',
184 2
            fn(SpacecraftInterface $spacecraft, string $name): ?SpacecraftSystemWrapper
185
            => $this->spacecraftSystemWrapperFactory->create($spacecraft, SpacecraftSystemTypeEnum::getByName($name))
186 3
        );
187 2
        $this->environment->addFunction($hasSpacecraftSystemByNameFunction);
188
189
        $isFeatureGrantedFunction = new TwigFunction('isFeatureGranted', fn(int $userId, string $feature): bool => $this->accessCheck->isFeatureGranted($userId, AccessGrantedFeatureEnum::from($feature), $this->game));
190
        $this->environment->addFunction($isFeatureGrantedFunction);
191
    }
192
193
    private function maskEmail(string $email): string
194
    {
195
        if (!$email || strpos($email, '@') === false) {
196
            return '';
197
        }
198
199
        $parts = explode('@', $email);
200
        $localPart = $parts[0];
201
        $domain = $parts[1];
202
203
        if (strlen($localPart) <= 2) {
204
            return $localPart[0] . '*@' . $domain;
205
        }
206
207
        return $localPart[0] . str_repeat('*', strlen($localPart) - 2) . $localPart[strlen($localPart) - 1] . '@' . $domain;
208
    }
209
210
    private function maskMobile(?string $mobile): string
211
    {
212
        if ($mobile === null || strlen($mobile) < 8) {
213
            return '';
214
        }
215
216
        $displayMobile = $mobile;
217
        if (strpos($mobile, '0049') === 0) {
218
            $displayMobile = '+49' . substr($mobile, 4);
219
        } elseif (strpos($mobile, '0043') === 0) {
220
            $displayMobile = '+43' . substr($mobile, 4);
221
        } elseif (strpos($mobile, '0041') === 0) {
222
            $displayMobile = '+41' . substr($mobile, 4);
223
        }
224
225
        if (strlen($displayMobile) > 8) {
226
            $start = substr($displayMobile, 0, 6);
227
            $end = substr($displayMobile, -2);
228
            $middle = str_repeat('*', strlen($displayMobile) - 8);
229
            return $start . $middle . $end;
230
        }
231
232
        return $displayMobile;
233
    }
234
}
235