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 — master (#715)
by Alexander
06:09 queued 03:33
created

CalendarController::getCalendarYear()   D

Complexity

Conditions 26
Paths 67

Size

Total Lines 114
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 26
eloc 84
c 2
b 0
f 0
nc 67
nop 4
dl 0
loc 114
rs 4.1666

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\Domain\Model\Document;
16
use TYPO3\CMS\Core\Database\ConnectionPool;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
19
class CalendarController extends AbstractController
20
{
21
    /**
22
     * This holds all issues for the list view.
23
     *
24
     * @var array
25
     * @access protected
26
     */
27
    protected $allIssues = [];
28
29
    /**
30
     * The main method of the plugin
31
     *
32
     * @return void
33
     */
34
    public function mainAction()
35
    {
36
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
37
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
38
39
        // Set initial document (anchor or year file) if configured.
40
        if (empty($requestData['id']) && !empty($this->settings['initialDocument'])) {
41
            $requestData['id'] = $this->settings['initialDocument'];
42
        }
43
44
        // Load current document.
45
        $this->loadDocument($requestData);
46
        if ($this->doc === null) {
47
            // Quit without doing anything if required variables are not set.
48
            return;
49
        }
50
51
        $metadata = $this->doc->getTitledata();
52
        if (!empty($metadata['type'][0])) {
53
            $type = $metadata['type'][0];
54
        } else {
55
            return;
56
        }
57
58
        switch ($type) {
59
            case 'newspaper':
60
            case 'ephemera':
61
                $this->forward('years', null, null, $requestData);
62
                break;
63
            case 'year':
64
                $this->forward('calendar', null, null, $requestData);
65
                break;
66
            case 'issue':
67
            default:
68
                break;
69
        }
70
71
    }
72
73
    /**
74
     * The Calendar Method
75
     *
76
     * @access public
77
     *
78
     * @param string $content: The PlugIn content
79
     * @param array $conf: The PlugIn configuration
80
     *
81
     * @return void
82
     */
83
    public function calendarAction()
84
    {
85
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
86
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
87
88
        // access arguments passed by the mainAction()
89
        $mainrequestData = $this->request->getArguments();
90
91
        // merge both arguments together --> passing id by GET parameter tx_dlf[id] should win
92
        $requestData = array_merge($requestData, $mainrequestData);
93
94
        // Load current document.
95
        $this->loadDocument($requestData);
96
        if ($this->doc === null) {
97
            // Quit without doing anything if required variables are not set.
98
            return;
99
        }
100
101
        $documents = $this->documentRepository->getChildrenOfYearAnchor($this->doc->uid, 'issue');
102
103
        $issues = [];
104
105
        // Process results.
106
        /** @var Document $document */
107
        foreach ($documents as $document) {
108
            // Set title for display in calendar view.
109
            if (!empty($document->getTitle())) {
110
                $title = $document->getTitle();
111
            } else {
112
                $title = !empty($document->getMetsLabel()) ? $document->getMetsLabel() : $document->getMetsOrderlabel();
113
                if (strtotime($title) !== false) {
114
                    $title = strftime('%x', strtotime($title));
115
                }
116
            }
117
            $issues[] = [
118
                'uid' => $document->getUid(),
119
                'title' => $title,
120
                'year' => $document->getYear()
121
            ];
122
        }
123
124
        //  We need an array of issues with year => month => day number as key.
125
        $calendarIssuesByYear = [];
126
        foreach ($issues as $issue) {
127
            $dateTimestamp = strtotime($issue['year']);
128
            if ($dateTimestamp !== false) {
129
                $_year = date('Y', $dateTimestamp);
130
                $_month = date('n', $dateTimestamp);
131
                $_day = date('j', $dateTimestamp);
132
                $calendarIssuesByYear[$_year][$_month][$_day][] = $issue;
133
            } else {
134
                $this->logger->warning('Document with UID ' . $issue['uid'] . 'has no valid date of publication');
135
            }
136
        }
137
        // Sort by years.
138
        ksort($calendarIssuesByYear);
139
        // Build calendar for year (default) or season.
140
        $iteration = 1;
141
        foreach ($calendarIssuesByYear as $year => $calendarIssuesByMonth) {
142
            // Sort by months.
143
            ksort($calendarIssuesByMonth);
144
            // Default: First month is January, last month is December.
145
            $firstMonth = 1;
146
            $lastMonth = 12;
147
            // Show calendar from first issue up to end of season if applicable.
148
            if (
149
                empty($this->settings['showEmptyMonths'])
150
                && count($calendarIssuesByYear) > 1
151
            ) {
152
                if ($iteration == 1) {
153
                    $firstMonth = (int) key($calendarIssuesByMonth);
154
                } elseif ($iteration == count($calendarIssuesByYear)) {
155
                    end($calendarIssuesByMonth);
156
                    $lastMonth = (int) key($calendarIssuesByMonth);
157
                }
158
            }
159
            $this->getCalendarYear($calendarIssuesByMonth, $year, $firstMonth, $lastMonth);
160
            $iteration++;
161
        }
162
        // Prepare list as alternative view.
163
        $issueData = [];
164
        foreach ($this->allIssues as $dayTimestamp => $issues) {
165
            $issueData[$dayTimestamp]['dateString'] = strftime('%A, %x', $dayTimestamp);
166
            $issueData[$dayTimestamp]['items'] = [];
167
            foreach ($issues as $issue) {
168
                $issueData[$dayTimestamp]['items'][] = $issue;
169
            }
170
        }
171
        $this->view->assign('issueData', $issueData);
172
173
        // Link to current year.
174
        $linkTitleData = $this->doc->getTitledata();
175
        $yearLinkTitle = !empty($linkTitleData['mets_orderlabel'][0]) ? $linkTitleData['mets_orderlabel'][0] : $linkTitleData['mets_label'][0];
176
177
        $this->view->assign('documentId', $this->doc->uid);
178
        $this->view->assign('yearLinkTitle', $yearLinkTitle);
179
        $this->view->assign('parentDocumentId', $this->doc->parentId);
180
        $this->view->assign('allYearDocTitle', $this->doc->getTitle($this->doc->parentId));
181
    }
182
183
    /**
184
     * The Years Method
185
     *
186
     * @access public
187
     *
188
     * @return void
189
     */
190
    public function yearsAction()
191
    {
192
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
193
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
194
195
        // access arguments passed by the mainAction()
196
        $mainrequestData = $this->request->getArguments();
197
198
        // merge both arguments together --> passing id by GET parameter tx_dlf[id] should win
199
        $requestData = array_merge($requestData, $mainrequestData);
200
201
        // Load current document.
202
        $this->loadDocument($requestData);
203
        if ($this->doc === null) {
204
            // Quit without doing anything if required variables are not set.
205
            return;
206
        }
207
208
        // Get all children of anchor. This should be the year anchor documents
209
        $documents = $this->documentRepository->getChildrenOfYearAnchor($this->doc->uid, 'year');
210
211
        $years = [];
212
        // Process results.
213
        /** @var Document $document */
214
        foreach ($documents as $document) {
215
            $years[] = [
216
                'title' => !empty($document->getMetsLabel()) ? $document->getMetsLabel() : (!empty($document->getMetsOrderlabel()) ? $document->getMetsOrderlabel() : $document->getTitle()),
217
                'uid' => $document->getUid()
218
            ];
219
        }
220
221
        $yearArray = [];
222
        if (count($years) > 0) {
223
            foreach ($years as $year) {
224
                $yearArray[] = [
225
                    'documentId' => $year['uid'],
226
                    'title' => $year['title']
227
                ];
228
            }
229
            $this->view->assign('yearName', $yearArray);
230
        }
231
232
        $this->view->assign('documentId', $this->doc->uid);
233
        $this->view->assign('allYearDocTitle', $this->doc->getTitle($this->doc->uid));
234
    }
235
236
    /**
237
     * Build calendar for a certain year
238
     *
239
     * @access protected
240
     *
241
     * @param array $calendarIssuesByMonth All issues sorted by month => day
242
     * @param int $year Gregorian year
243
     * @param int $firstMonth 1 for January, 2 for February, ... 12 for December
244
     * @param int $lastMonth 1 for January, 2 for February, ... 12 for December
245
     *
246
     * @return string Content for template subpart
247
     */
248
    protected function getCalendarYear($calendarIssuesByMonth, $year, $firstMonth = 1, $lastMonth = 12)
249
    {
250
        $calendarData = [];
251
        for ($i = $firstMonth; $i <= $lastMonth; $i++) {
252
            $calendarData[$i] = [
253
                'DAYMON_NAME' => strftime('%a', strtotime('last Monday')),
254
                'DAYTUE_NAME' => strftime('%a', strtotime('last Tuesday')),
255
                'DAYWED_NAME' => strftime('%a', strtotime('last Wednesday')),
256
                'DAYTHU_NAME' => strftime('%a', strtotime('last Thursday')),
257
                'DAYFRI_NAME' => strftime('%a', strtotime('last Friday')),
258
                'DAYSAT_NAME' => strftime('%a', strtotime('last Saturday')),
259
                'DAYSUN_NAME' => strftime('%a', strtotime('last Sunday')),
260
                'MONTHNAME'  => strftime('%B', strtotime($year . '-' . $i . '-1')) . ' ' . $year,
261
                'CALYEAR' => ($i == $firstMonth) ? $year : ''
262
            ];
263
264
            $firstOfMonth = strtotime($year . '-' . $i . '-1');
265
            $lastOfMonth = strtotime('last day of', ($firstOfMonth));
266
            $firstOfMonthStart = strtotime('last Monday', $firstOfMonth);
267
            // There are never more than 6 weeks in a month.
268
            for ($j = 0; $j <= 5; $j++) {
269
                $firstDayOfWeek = strtotime('+ ' . $j . ' Week', $firstOfMonthStart);
270
271
                $calendarData[$i]['week'][$j] = [
272
                    'DAYMON' => ['dayValue' => '&nbsp;'],
273
                    'DAYTUE' => ['dayValue' => '&nbsp;'],
274
                    'DAYWED' => ['dayValue' => '&nbsp;'],
275
                    'DAYTHU' => ['dayValue' => '&nbsp;'],
276
                    'DAYFRI' => ['dayValue' => '&nbsp;'],
277
                    'DAYSAT' => ['dayValue' => '&nbsp;'],
278
                    'DAYSUN' => ['dayValue' => '&nbsp;'],
279
                ];
280
                // Every week has seven days. ;-)
281
                for ($k = 0; $k <= 6; $k++) {
282
                    $currentDayTime = strtotime('+ ' . $k . ' Day', $firstDayOfWeek);
283
                    if (
284
                        $currentDayTime >= $firstOfMonth
285
                        && $currentDayTime <= $lastOfMonth
286
                    ) {
287
                        $dayLinks = '';
288
                        $dayLinksText = [];
289
                        $dayLinkDiv = [];
290
                        $currentMonth = date('n', $currentDayTime);
291
                        if (is_array($calendarIssuesByMonth[$currentMonth])) {
292
                            foreach ($calendarIssuesByMonth[$currentMonth] as $id => $day) {
293
                                if ($id == date('j', $currentDayTime)) {
294
                                    $dayLinks = $id;
295
                                    foreach ($day as $issue) {
296
                                        $dayLinkLabel = empty($issue['title']) ? strftime('%x', $currentDayTime) : $issue['title'];
297
298
                                        $dayLinksText[] = [
299
                                            'documentId' => $issue['uid'],
300
                                            'text' => $dayLinkLabel
301
                                        ];
302
303
                                        // Save issue for list view.
304
                                        $this->allIssues[$currentDayTime][] = [
305
                                            'documentId' => $issue['uid'],
306
                                            'text' => $dayLinkLabel
307
                                        ];
308
                                    }
309
                                }
310
                            }
311
                            $dayLinkDiv = $dayLinksText;
312
                        }
313
                        switch (strftime('%w', strtotime('+ ' . $k . ' Day', $firstDayOfWeek))) {
314
                            case '0':
315
                                $calendarData[$i]['week'][$j]['DAYSUN']['dayValue'] = strftime('%d', $currentDayTime);
316
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
317
                                    $calendarData[$i]['week'][$j]['DAYSUN']['issues'] = $dayLinkDiv;
318
                                }
319
                                break;
320
                            case '1':
321
                                $calendarData[$i]['week'][$j]['DAYMON']['dayValue'] = strftime('%d', $currentDayTime);
322
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
323
                                    $calendarData[$i]['week'][$j]['DAYMON']['issues'] = $dayLinkDiv;
324
                                }
325
                                break;
326
                            case '2':
327
                                $calendarData[$i]['week'][$j]['DAYTUE']['dayValue'] = strftime('%d', $currentDayTime);
328
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
329
                                    $calendarData[$i]['week'][$j]['DAYTUE']['issues'] = $dayLinkDiv;
330
                                }
331
                                break;
332
                            case '3':
333
                                $calendarData[$i]['week'][$j]['DAYWED']['dayValue'] = strftime('%d', $currentDayTime);
334
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
335
                                    $calendarData[$i]['week'][$j]['DAYWED']['issues'] = $dayLinkDiv;
336
                                }
337
                                break;
338
                            case '4':
339
                                $calendarData[$i]['week'][$j]['DAYTHU']['dayValue'] = strftime('%d', $currentDayTime);
340
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
341
                                    $calendarData[$i]['week'][$j]['DAYTHU']['issues'] = $dayLinkDiv;
342
                                }
343
                                break;
344
                            case '5':
345
                                $calendarData[$i]['week'][$j]['DAYFRI']['dayValue'] = strftime('%d', $currentDayTime);
346
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
347
                                    $calendarData[$i]['week'][$j]['DAYFRI']['issues'] = $dayLinkDiv;
348
                                }
349
                                break;
350
                            case '6':
351
                                $calendarData[$i]['week'][$j]['DAYSAT']['dayValue'] = strftime('%d', $currentDayTime);
352
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
353
                                    $calendarData[$i]['week'][$j]['DAYSAT']['issues'] = $dayLinkDiv;
354
                                }
355
                                break;
356
                        }
357
                    }
358
                }
359
            }
360
        }
361
        $this->view->assign('calendarData', $calendarData);
362
    }
363
}
364