Test Failed
Pull Request — master (#2138)
by Nico
07:39
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 2
{
39
    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 2
        private readonly StuTime $stuTime,
52
        private readonly StuRandom $stuRandom
53 2
    ) {}
54
55 2
    public function registerGlobalVariables(): void
56 2
    {
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
            ]
64
        );
65
    }
66
67
    /**
68 2
     * Registers global available twig methods and filters
69
     */
70 2
    public function registerFiltersAndFunctions(): void
71 2
    {
72
        $this->registerFilters();
73
        $this->registerFunctions();
74 108
    }
75
76 95
    private function registerFilters(): void
77 2
    {
78
        $bbcode2txtFilter = new TwigFilter('bbcode2txt', fn($string): string => $this->parser->parse($string)->getAsText());
79 108
        $this->environment->addFilter($bbcode2txtFilter);
80 2
81
        $bbcodeFilter = new TwigFilter('bbcode', fn($string): string => $this->parser->parse($string)->getAsHTML(), ['is_safe' => ['html']]);
82 2
        $this->environment->addFilter($bbcodeFilter);
83 2
84
        $jsquoteFilter = new TwigFilter('jsquote', fn($string): string => $this->templateHelper->jsquote($string));
85 2
        $this->environment->addFilter($jsquoteFilter);
86 9
87 9
        $addPlusCharacterFilter = new TwigFilter('addPlusCharacter', function ($value): string {
88
            if (is_int($value)) {
89 1
                return $this->templateHelper->addPlusCharacter((string) $value);
90 2
            }
91 2
            return $this->templateHelper->addPlusCharacter($value);
92
        });
93 2
        $this->environment->addFilter($addPlusCharacterFilter);
94 9
95 9
        $formatSecondsFilter = new TwigFilter('formatSeconds', function ($value): string {
96
            if (is_int($value)) {
97
                return $this->templateHelper->formatSeconds((string) $value);
98 2
            }
99 2
            return $this->templateHelper->formatSeconds($value);
100
        });
101 8
        $this->environment->addFilter($formatSecondsFilter);
102 2
103
        $planetFieldTitleFilter = new TwigFilter('planetFieldTitle', fn($planetField): string => $this->templateHelper->getPlanetFieldTitle($planetField));
104 3
        $this->environment->addFilter($planetFieldTitleFilter);
105 2
106
        $planetFieldTypeDescriptionFilter = new TwigFilter('planetFieldTypeDescription', fn($id): string => $this->templateHelper->getPlanetFieldTypeDescription($id));
107 6
        $this->environment->addFilter($planetFieldTypeDescriptionFilter);
108 2
109
        $formatProductionValueFilter = new TwigFilter('formatProductionValue', fn($value): string => $this->templateHelper->formatProductionValue($value));
110 2
        $this->environment->addFilter($formatProductionValueFilter);
111 2
112
        $isPositiveFilter = new TwigFilter('isPositive', fn(int $value): bool => $value > 0);
113 12
        $this->environment->addFilter($isPositiveFilter);
114 2
115
        $stuDateTimeFilter = new TwigFilter('stuDateTime', fn($value): string => $this->stuTime->transformToStuDateTime($value));
116 8
        $this->environment->addFilter($stuDateTimeFilter);
117 2
118
        $stuDateFilter = new TwigFilter('stuDate', fn($value): string => $this->stuTime->transformToStuDate($value));
119 10
        $this->environment->addFilter($stuDateFilter);
120 2
121
        $nl2brFilter = new TwigFilter('nl2br', fn(string $value): string => nl2br($value));
122 20
        $this->environment->addFilter($nl2brFilter);
123 2
124
        $htmlSafeFilter = new TwigFilter('htmlSafe', fn(string $text): string => htmlspecialchars($text));
125 2
        $this->environment->addFilter($htmlSafeFilter);
126 2
127
        $adventDoorFilter = new TwigFilter('adventDoor', fn(AnomalyInterface $anomaly): int => (int)((120 - $anomaly->getRemainingTicks()) / 5) + 1);
128 3
        $this->environment->addFilter($adventDoorFilter);
129 3
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 2
            $name
134
        ));
135 3
        $this->environment->addFilter($shortNameFilter);
136 2
137
        $getMaxCrewCountByShipFilter = new TwigFilter('getMaxCrewCountByShip', fn(SpacecraftInterface $spacecraft): int => $this->shipCrewCalculator->getMaxCrewCountByShip($spacecraft));
138 4
        $this->environment->addFilter($getMaxCrewCountByShipFilter);
139 2
140
        $numberWithThousandSeperatorFilter = new TwigFilter('numberWithThousandSeperator', fn($value): string => $this->templateHelper->getNumberWithThousandSeperator($value));
141
        $this->environment->addFilter($numberWithThousandSeperatorFilter);
142 11
    }
143
144 3
    private function registerFunctions(): void
145 2
    {
146
        $canAttackTargetFunction = new TwigFunction('canAttackTarget', fn(SpacecraftInterface $spacecraft, SpacecraftInterface|SpacecraftNfsItem $target): bool => $this->fightLib->canAttackTarget($spacecraft, $target));
147 3
        $this->environment->addFunction($canAttackTargetFunction);
148 2
149
        $getEpsProductionPreviewFunction = new TwigFunction('getEpsProductionPreview', fn(PlanetFieldHostInterface $host, BuildingInterface $building): ColonyEpsProductionPreviewWrapper => $this->colonyLibFactory->createEpsProductionPreviewWrapper($host, $building));
150 3
        $this->environment->addFunction($getEpsProductionPreviewFunction);
151 2
152
        $getCommodityProductionPreviewFunction = new TwigFunction('getCommodityProductionPreview', fn(PlanetFieldHostInterface $host, BuildingInterface $building): ColonyProductionPreviewWrapper => $this->colonyLibFactory->createColonyProductionPreviewWrapper($building, $host));
153 7
        $this->environment->addFunction($getCommodityProductionPreviewFunction);
154 2
155
        $getColonyMenuClassFunction = new TwigFunction('getColonyMenuClass', fn(ColonyMenuEnum $currentMenu, int $value): string => ColonyMenuEnum::getMenuClass($currentMenu, $value));
156 6
        $this->environment->addFunction($getColonyMenuClassFunction);
157 2
158
        $getViewFunction = new TwigFunction('getView', fn(string $value): ModuleEnum => ModuleEnum::from($value));
159 11
        $this->environment->addFunction($getViewFunction);
160 2
161
        $getUniqIdFunction = new TwigFunction('getUniqId', fn(): string => $this->stuRandom->uniqid());
162 2
        $this->environment->addFunction($getUniqIdFunction);
163 2
164
        $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 2
167
        $gradientColorOverLimitFunction = new TwigFunction('gradientColorOverLimit', fn(int $value, int $lowest, int $highest): string => $this->gradientColor->calculateGradientColor(min($value, $highest), $lowest, $highest));
168 6
        $this->environment->addFunction($gradientColorOverLimitFunction);
169 2
170
        $stuDateFunction = new TwigFunction('stuDate', fn(string $format): string => $this->stuTime->date($format));
171 8
        $this->environment->addFunction($stuDateFunction);
172 2
173
        $dayNightPrefixFunction = new TwigFunction('getDayNightPrefix', fn(PlanetFieldInterface $field): string => $field->getDayNightPrefix($this->stuTime->time()));
174 2
        $this->environment->addFunction($dayNightPrefixFunction);
175 2
176 2
        $maskEmailFunction = new TwigFunction('maskEmail', fn(string $email): string => $this->maskEmail($email));
177 2
        $this->environment->addFunction($maskEmailFunction);
178 2
179 2
        $maskMobileFunction = new TwigFunction('maskMobile', fn(?string $mobile): string => $this->maskMobile($mobile));
180
        $this->environment->addFunction($maskMobileFunction);
181 3
182 2
        $hasSpacecraftSystemByNameFunction = new TwigFunction(
183
            'getSpacecraftSystemWrapper',
184
            fn(SpacecraftInterface $spacecraft, string $name): ?SpacecraftSystemWrapper
185
            => $this->spacecraftSystemWrapperFactory->create($spacecraft, SpacecraftSystemTypeEnum::getByName($name))
186
        );
187
        $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