CommunicationProvider::setTemplateVariables()   C
last analyzed

Complexity

Conditions 13
Paths 128

Size

Total Lines 79
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 0
Metric Value
cc 13
eloc 55
nc 128
nop 1
dl 0
loc 79
ccs 0
cts 61
cp 0
crap 182
rs 6.3833
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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\Game\Lib\View\Provider;
6
7
use request;
8
use Stu\Component\Communication\Kn\KnFactoryInterface;
9
use Stu\Component\Communication\Kn\KnItemInterface;
10
use Stu\Component\Game\GameEnum;
0 ignored issues
show
Bug introduced by
The type Stu\Component\Game\GameEnum 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\Game\JavascriptExecutionTypeEnum;
12
use Stu\Module\Communication\View\ShowKnArchive\ShowKnArchive;
13
use Stu\Module\Control\GameControllerInterface;
14
use Stu\Orm\Entity\KnPost;
15
use Stu\Orm\Entity\User;
16
use Stu\Orm\Repository\KnPostArchivRepositoryInterface;
17
use Stu\Orm\Repository\KnPostRepositoryInterface;
18
19
final class CommunicationProvider implements ViewComponentProviderInterface
20
{
21 1
    public function __construct(
22
        private KnPostRepositoryInterface $knPostRepository,
23
        private KnFactoryInterface $knFactory,
24
        private KnPostArchivRepositoryInterface $knPostArchivRepository
25 1
    ) {}
26
27
    #[\Override]
28
    public function setTemplateVariables(GameControllerInterface $game): void
29
    {
30
        $user = $game->getUser();
31
        $userKnMark = $user->getKnMark();
32
33
        $newKnPostCount = $this->knPostRepository->getAmountSince($userKnMark);
34
        $knPostCount = $this->knPostRepository->getAmount();
35
36
        $mark = $knPostCount;
37
        $lim = floor($mark / GameEnum::KN_PER_SITE) * GameEnum::KN_PER_SITE;
38
        $knStart = $mark % GameEnum::KN_PER_SITE == 0 ? $lim - GameEnum::KN_PER_SITE : $lim;
39
40
        $mark = request::getInt('mark');
41
        if ($mark % GameEnum::KN_PER_SITE != 0 || $mark < 0) {
42
            $mark = 0;
43
        }
44
        if (request::getInt('user_mark') !== 0) {
45
            $mark = max(0, (int) floor(($newKnPostCount - 1) / GameEnum::KN_PER_SITE) * GameEnum::KN_PER_SITE);
46
        }
47
48
        $maxpage = ceil($knPostCount / GameEnum::KN_PER_SITE);
49
        $curpage = floor($mark / GameEnum::KN_PER_SITE);
50
        $knNavigation = [];
51
        if ($curpage != 0) {
52
            $knNavigation[] = ["page" => "<<", "mark" => 0, "cssclass" => "pages"];
53
            $knNavigation[] = ["page" => "<", "mark" => ($mark - GameEnum::KN_PER_SITE), "cssclass" => "pages"];
54
        }
55
        for ($i = $curpage - 1; $i <= $curpage + 3; $i++) {
56
            if ($i > $maxpage || $i < 1) {
57
                continue;
58
            }
59
            $knNavigation[] = [
60
                "page" => $i,
61
                "mark" => ($i * GameEnum::KN_PER_SITE - GameEnum::KN_PER_SITE),
62
                "cssclass" => ($curpage + 1 === $i ? "pages selected" : "pages")
63
            ];
64
        }
65
        if ($curpage + 1 !== $maxpage) {
66
            $knNavigation[] = ["page" => ">", "mark" => ($mark + GameEnum::KN_PER_SITE), "cssclass" => "pages"];
67
            $knNavigation[] = ["page" => ">>", "mark" => $maxpage * GameEnum::KN_PER_SITE - GameEnum::KN_PER_SITE, "cssclass" => "pages"];
68
        }
69
70
        $markedPostId = $this->getMarkedKnId($user);
71
72
        $game->setTemplateVar(
73
            'KN_POSTINGS',
74
            array_map(
75
                function (KnPost $knPost) use ($user, $markedPostId): KnItemInterface {
76
                    $knItem = $this->knFactory->createKnItem(
77
                        $knPost,
78
                        $user
79
                    );
80
                    if ($markedPostId && $knItem->getId() == $markedPostId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $markedPostId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
81
                        $knItem->setIsHighlighted(true);
82
                    }
83
                    return $knItem;
84
                },
85
                $this->knPostRepository->getBy($mark, GameEnum::KN_PER_SITE)
86
            )
87
        );
88
        $game->setTemplateVar('HAS_NEW_KN_POSTINGS', $this->knPostRepository->getAmountSince($userKnMark));
89
        $game->setTemplateVar('KN_START', $knStart);
90
        $game->setTemplateVar('KN_OFFSET', $mark);
91
        $game->setTemplateVar('NEW_KN_POSTING_COUNT', $newKnPostCount);
92
        $game->setTemplateVar('KN_NAVIGATION', $knNavigation);
93
94
        $availableVersions = $this->knPostArchivRepository->getAvailableVersions();
95
        $formattedVersions = array_map(function ($version) {
96
            return [
97
                'version' => $version,
98
                'display' => $this->formatVersion($version)
99
            ];
100
        }, $availableVersions);
101
102
        $game->setTemplateVar('AVAILABLE_ARCHIVE_VERSIONS', $formattedVersions);
103
        $game->setTemplateVar('SHOW_ARCHIVE_VIEW', ShowKnArchive::VIEW_IDENTIFIER);
104
105
        $game->addExecuteJS("initTranslations();", JavascriptExecutionTypeEnum::AFTER_RENDER);
106
    }
107
108
    private function getMarkedKnId(User $user): ?int
109
    {
110
        $markedPostId = request::getInt('markedPost');
111
        if ($markedPostId !== 0) {
112
            return $markedPostId;
113
        }
114
115
        $newerKnPosts = $this->knPostRepository->getNewerThenMark($user->getKnMark());
116
        if ($newerKnPosts !== []) {
117
            return $newerKnPosts[0]->getId();
118
        }
119
120
        return null;
121
    }
122
123
    private function formatVersion(string $version): string
124
    {
125
        $cleanVersion = ltrim($version, 'v');
126
127
        if (str_contains($cleanVersion, 'alpha')) {
128
            return 'v' . str_replace('alpha', 'α', $cleanVersion);
129
        }
130
131
        if (preg_match('/^(\d)(\d)$/', $cleanVersion, $matches)) {
132
            return 'v' . $matches[1] . '.' . $matches[2];
133
        }
134
135
        return $version;
136
    }
137
}
138