Passed
Push — dev ( fd7324...4b1ed0 )
by Nico
29:02
created

TwigHelper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

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