Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — dev-extbase-fluid (#714)
by Alexander
03:21
created

CalendarController::calendarAction()   F

Complexity

Conditions 16
Paths 541

Size

Total Lines 115
Code Lines 74

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 74
c 2
b 0
f 0
dl 0
loc 115
rs 2.0375
cc 16
nc 541
nop 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
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Controller;
14
15
use Kitodo\Dlf\Common\Helper;
16
use TYPO3\CMS\Core\Database\Connection;
17
use TYPO3\CMS\Core\Database\ConnectionPool;
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
20
class CalendarController extends AbstractController
21
{
22
    public $prefixId = 'tx_dlf';
23
24
    /**
25
     * The main method of the plugin
26
     *
27
     * @return void
28
     */
29
    public function mainAction()
30
    {
31
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
32
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
33
34
        // Set initial document (anchor or year file) if configured.
35
        if (empty($requestData['id']) && !empty($this->settings['initialDocument'])) {
36
            $requestData['id'] = $this->settings['initialDocument'];
37
        }
38
39
        // Load current document.
40
        $this->loadDocument($requestData);
41
        if ($this->doc === null) {
42
            // Quit without doing anything if required variables are not set.
43
            return;
44
        }
45
46
        $metadata = $this->doc->getTitledata();
47
        if (!empty($metadata['type'][0])) {
48
            $type = $metadata['type'][0];
49
        } else {
50
            return;
51
        }
52
53
        switch ($type) {
54
            case 'newspaper':
55
            case 'ephemera':
56
                $this->forward('years', NULL, NULL, $requestData);
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
57
            case 'year':
58
                $this->forward('calendar', NULL, NULL, $requestData);
59
            case 'issue':
60
            default:
61
                break;
62
        }
63
64
    }
65
66
    /**
67
     * The Calendar Method
68
     *
69
     * @access public
70
     *
71
     * @param string $content: The PlugIn content
72
     * @param array $conf: The PlugIn configuration
73
     *
74
     * @return void
75
     */
76
    public function calendarAction()
77
    {
78
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
79
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
80
81
        // access arguments passed by the mainAction()
82
        $mainrquestData = $this->request->getArguments();
83
84
        // merge both arguments together --> passing id by GET parameter tx_dlf[id] should win
85
        $requestData = array_merge($requestData, $mainrquestData);
86
87
        // Load current document.
88
        $this->loadDocument($requestData);
89
        if ($this->doc === null) {
90
            // Quit without doing anything if required variables are not set.
91
            return;
92
        }
93
94
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
95
            ->getQueryBuilderForTable('tx_dlf_documents');
96
97
        // Get all children of year anchor.
98
        $result = $queryBuilder
99
            ->select(
100
                'tx_dlf_documents.uid AS uid',
101
                'tx_dlf_documents.title AS title',
102
                'tx_dlf_documents.year AS year',
103
                'tx_dlf_documents.mets_label AS label',
104
                'tx_dlf_documents.mets_orderlabel AS orderlabel'
105
            )
106
            ->from('tx_dlf_documents')
107
            ->where(
108
                $queryBuilder->expr()->eq('tx_dlf_documents.structure', Helper::getUidFromIndexName('issue', 'tx_dlf_structures', $this->doc->cPid)),
109
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($this->doc->uid)),
110
                Helper::whereExpression('tx_dlf_documents')
111
            )
112
            ->orderBy('tx_dlf_documents.mets_orderlabel')
113
            ->execute();
114
115
        $issues = [];
116
117
        // Process results.
118
        while ($resArray = $result->fetch()) {
119
            // Set title for display in calendar view.
120
            if (!empty($resArray['title'])) {
121
                $title = $resArray['title'];
122
            } else {
123
                $title = !empty($resArray['label']) ? $resArray['label'] : $resArray['orderlabel'];
124
                if (strtotime($title) !== false) {
125
                    $title = strftime('%x', strtotime($title));
126
                }
127
            }
128
            $issues[] = [
129
                'uid' => $resArray['uid'],
130
                'title' => $title,
131
                'year' => $resArray['year']
132
            ];
133
        }
134
        //  We need an array of issues with year => month => day number as key.
135
        $calendarIssuesByYear = [];
136
        foreach ($issues as $issue) {
137
            $dateTimestamp = strtotime($issue['year']);
138
            if ($dateTimestamp !== false) {
139
                $_year = date('Y', $dateTimestamp);
140
                $_month = date('n', $dateTimestamp);
141
                $_day = date('j', $dateTimestamp);
142
                $calendarIssuesByYear[$_year][$_month][$_day][] = $issue;
143
            } else {
144
                $this->logger->warning('Document with UID ' . $issue['uid'] . 'has no valid date of publication');
1 ignored issue
show
Bug introduced by
The method warning() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

144
                $this->logger->/** @scrutinizer ignore-call */ 
145
                               warning('Document with UID ' . $issue['uid'] . 'has no valid date of publication');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
145
            }
146
        }
147
        // Sort by years.
148
        ksort($calendarIssuesByYear);
149
        // Build calendar for year (default) or season.
150
        $iteration = 1;
151
        foreach ($calendarIssuesByYear as $year => $calendarIssuesByMonth) {
152
            // Sort by months.
153
            ksort($calendarIssuesByMonth);
154
            // Default: First month is January, last month is December.
155
            $firstMonth = 1;
156
            $lastMonth = 12;
157
            // Show calendar from first issue up to end of season if applicable.
158
            if (
159
                empty($this->settings['showEmptyMonths'])
160
                && count($calendarIssuesByYear) > 1
161
            ) {
162
                if ($iteration == 1) {
163
                    $firstMonth = (int) key($calendarIssuesByMonth);
164
                } elseif ($iteration == count($calendarIssuesByYear)) {
165
                    end($calendarIssuesByMonth);
166
                    $lastMonth = (int) key($calendarIssuesByMonth);
167
                }
168
            }
169
            $this->getCalendarYear($calendarIssuesByMonth, $year, $firstMonth, $lastMonth);
170
            $iteration++;
171
        }
172
        // Prepare list as alternative view.
173
        $issueData = [];
174
        foreach ($this->allIssues as $dayTimestamp => $issues) {
175
            $issueData[$dayTimestamp]['dateString'] = strftime('%A, %x', $dayTimestamp);
176
            $issueData[$dayTimestamp]['items'] = [];
177
            foreach ($issues as $issue) {
178
                $issueData[$dayTimestamp]['items'][] = $issue;
179
            }
180
        }
181
        $this->view->assign('issueData', $issueData);
182
183
        // Link to current year.
184
        $linkTitleData = $this->doc->getTitledata();
185
        $yearLinkTitle = !empty($linkTitleData['mets_orderlabel'][0]) ? $linkTitleData['mets_orderlabel'][0] : $linkTitleData['mets_label'][0];
186
187
        $this->view->assign('documentId', $this->doc->uid);
188
        $this->view->assign('yearLinkTitle', $yearLinkTitle);
189
        $this->view->assign('parentDocumentId', $this->doc->parentId);
190
        $this->view->assign('allYearDocTitle', $this->doc->getTitle($this->doc->parentId));
191
    }
192
193
    /**
194
     * The Years Method
195
     *
196
     * @access public
197
     *
198
     * @return void
199
     */
200
    public function yearsAction()
201
    {
202
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
203
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
204
205
        // access arguments passed by the mainAction()
206
        $mainrquestData = $this->request->getArguments();
207
208
        // merge both arguments together --> passing id by GET parameter tx_dlf[id] should win
209
        $requestData = array_merge($requestData, $mainrquestData);
210
211
        // Load current document.
212
        $this->loadDocument($requestData);
213
        if ($this->doc === null) {
214
            // Quit without doing anything if required variables are not set.
215
            return;
216
        }
217
218
        // Get the title of the anchor file
219
        $titleAnchor = $this->doc->getTitle($this->doc->uid);
0 ignored issues
show
Unused Code introduced by
The assignment to $titleAnchor is dead and can be removed.
Loading history...
220
221
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
222
            ->getQueryBuilderForTable('tx_dlf_documents');
223
224
        // Get all children of anchor. This should be the year anchor documents
225
        $result = $queryBuilder
226
            ->select(
227
                'tx_dlf_documents.uid AS uid',
228
                'tx_dlf_documents.title AS title',
229
                'tx_dlf_documents.mets_label AS label',
230
                'tx_dlf_documents.mets_orderlabel AS orderlabel'
231
            )
232
            ->from('tx_dlf_documents')
233
            ->where(
234
                $queryBuilder->expr()->eq('tx_dlf_documents.structure', Helper::getUidFromIndexName('year', 'tx_dlf_structures', $this->doc->cPid)),
235
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($this->doc->uid)),
236
                Helper::whereExpression('tx_dlf_documents')
237
            )
238
            ->orderBy('tx_dlf_documents.mets_orderlabel')
239
            ->execute();
240
241
        $years = [];
242
        // Process results.
243
        while ($resArray = $result->fetch()) {
244
            $years[] = [
245
                'title' => !empty($resArray['label']) ? $resArray['label'] : (!empty($resArray['orderlabel']) ? $resArray['orderlabel'] : $resArray['title']),
246
                'uid' => $resArray['uid']
247
            ];
248
        }
249
        $yearArray = [];
250
        if (count($years) > 0) {
251
            foreach ($years as $year) {
252
                $yearArray[] = [
253
                    'documentId' => $year['uid'],
254
                    'title' => $year['title']
255
                ];
256
            }
257
            $this->view->assign('yearName', $yearArray);
258
        }
259
260
        $this->view->assign('documentId', $this->doc->uid);
261
        $this->view->assign('allYearDocTitle', $this->doc->getTitle($this->doc->uid));
262
    }
263
264
    /**
265
     * Build calendar for a certain year
266
     *
267
     * @access protected
268
     *
269
     * @param array $calendarIssuesByMonth All issues sorted by month => day
270
     * @param int $year Gregorian year
271
     * @param int $firstMonth 1 for January, 2 for February, ... 12 for December
272
     * @param int $lastMonth 1 for January, 2 for February, ... 12 for December
273
     *
274
     * @return string Content for template subpart
275
     */
276
    protected function getCalendarYear($calendarIssuesByMonth, $year, $firstMonth = 1, $lastMonth = 12)
277
    {
278
        $calendarData = [];
279
        for ($i = $firstMonth; $i <= $lastMonth; $i++) {
280
            $calendarData[$i] = [
281
                'DAYMON_NAME' => strftime('%a', strtotime('last Monday')),
282
                'DAYTUE_NAME' => strftime('%a', strtotime('last Tuesday')),
283
                'DAYWED_NAME' => strftime('%a', strtotime('last Wednesday')),
284
                'DAYTHU_NAME' => strftime('%a', strtotime('last Thursday')),
285
                'DAYFRI_NAME' => strftime('%a', strtotime('last Friday')),
286
                'DAYSAT_NAME' => strftime('%a', strtotime('last Saturday')),
287
                'DAYSUN_NAME' => strftime('%a', strtotime('last Sunday')),
288
                'MONTHNAME'  => strftime('%B', strtotime($year . '-' . $i . '-1')) . ' ' . $year,
289
                'CALYEAR' => ($i == $firstMonth) ? $year : ''
290
            ];
291
292
            $firstOfMonth = strtotime($year . '-' . $i . '-1');
293
            $lastOfMonth = strtotime('last day of', ($firstOfMonth));
294
            $firstOfMonthStart = strtotime('last Monday', $firstOfMonth);
295
            // There are never more than 6 weeks in a month.
296
            for ($j = 0; $j <= 5; $j++) {
297
                $firstDayOfWeek = strtotime('+ ' . $j . ' Week', $firstOfMonthStart);
298
299
                $calendarData[$i]['week'][$j] = [
300
                    'DAYMON' => ['dayValue' => '&nbsp;'],
301
                    'DAYTUE' => ['dayValue' => '&nbsp;'],
302
                    'DAYWED' => ['dayValue' => '&nbsp;'],
303
                    'DAYTHU' => ['dayValue' => '&nbsp;'],
304
                    'DAYFRI' => ['dayValue' => '&nbsp;'],
305
                    'DAYSAT' => ['dayValue' => '&nbsp;'],
306
                    'DAYSUN' => ['dayValue' => '&nbsp;'],
307
                ];
308
                // Every week has seven days. ;-)
309
                for ($k = 0; $k <= 6; $k++) {
310
                    $currentDayTime = strtotime('+ ' . $k . ' Day', $firstDayOfWeek);
311
                    if (
312
                        $currentDayTime >= $firstOfMonth
313
                        && $currentDayTime <= $lastOfMonth
314
                    ) {
315
                        $dayLinks = '';
316
                        $dayLinksText = [];
317
                        $currentMonth = date('n', $currentDayTime);
318
                        if (is_array($calendarIssuesByMonth[$currentMonth])) {
319
                            foreach ($calendarIssuesByMonth[$currentMonth] as $id => $day) {
320
                                if ($id == date('j', $currentDayTime)) {
321
                                    $dayLinks = $id;
322
                                    foreach ($day as $issue) {
323
                                        $dayLinkLabel = empty($issue['title']) ? strftime('%x', $currentDayTime) : $issue['title'];
324
325
                                        $dayLinksText[] = [
326
                                            'documentId' => $issue['uid'],
327
                                            'text' => $dayLinkLabel
328
                                        ];
329
330
                                        // Save issue for list view.
331
                                        $this->allIssues[$currentDayTime][] = [
0 ignored issues
show
Bug Best Practice introduced by
The property allIssues does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
332
                                            'documentId' => $issue['uid'],
333
                                            'text' => $dayLinkLabel
334
                                        ];
335
                                    }
336
                                }
337
                            }
338
                            $dayLinkDiv = $dayLinksText;
339
                        }
340
                        switch (strftime('%w', strtotime('+ ' . $k . ' Day', $firstDayOfWeek))) {
341
                            case '0':
342
                                $calendarData[$i]['week'][$j]['DAYSUN']['dayValue'] = strftime('%d', $currentDayTime);
343
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
344
                                    $calendarData[$i]['week'][$j]['DAYSUN']['issues'] = $dayLinkDiv;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dayLinkDiv does not seem to be defined for all execution paths leading up to this point.
Loading history...
345
                                }
346
                                break;
347
                            case '1':
348
                                $calendarData[$i]['week'][$j]['DAYMON']['dayValue'] = strftime('%d', $currentDayTime);
349
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
350
                                    $calendarData[$i]['week'][$j]['DAYMON']['issues'] = $dayLinkDiv;
351
                                }
352
                                break;
353
                            case '2':
354
                                $calendarData[$i]['week'][$j]['DAYTUE']['dayValue'] = strftime('%d', $currentDayTime);
355
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
356
                                    $calendarData[$i]['week'][$j]['DAYTUE']['issues'] = $dayLinkDiv;
357
                                }
358
                                break;
359
                            case '3':
360
                                $calendarData[$i]['week'][$j]['DAYWED']['dayValue'] = strftime('%d', $currentDayTime);
361
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
362
                                    $calendarData[$i]['week'][$j]['DAYWED']['issues'] = $dayLinkDiv;
363
                                }
364
                                break;
365
                            case '4':
366
                                $calendarData[$i]['week'][$j]['DAYTHU']['dayValue'] = strftime('%d', $currentDayTime);
367
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
368
                                    $calendarData[$i]['week'][$j]['DAYTHU']['issues'] = $dayLinkDiv;
369
                                }
370
                                break;
371
                            case '5':
372
                                $calendarData[$i]['week'][$j]['DAYFRI']['dayValue'] = strftime('%d', $currentDayTime);
373
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
374
                                    $calendarData[$i]['week'][$j]['DAYFRI']['issues'] = $dayLinkDiv;
375
                                }
376
                                break;
377
                            case '6':
378
                                $calendarData[$i]['week'][$j]['DAYSAT']['dayValue'] = strftime('%d', $currentDayTime);
379
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
380
                                    $calendarData[$i]['week'][$j]['DAYSAT']['issues'] = $dayLinkDiv;
381
                                }
382
                                break;
383
                        }
384
                    }
385
                }
386
            }
387
        }
388
        $this->view->assign('calendarData', $calendarData);
389
    }
390
}
391