Passed
Push — dev ( a37614...5d6f44 )
by Nico
05:36
created

TwigHelper::checkAlliancePermission()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6.1666

Importance

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