Passed
Push — dev ( 216c8f...156d5c )
by Janko
15:03
created

TwigHelper::registerFunctions()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 58
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 39
nc 1
nop 0
dl 0
loc 58
ccs 41
cts 41
cp 1
crap 2
rs 9.296
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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