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
03:39
created

CalendarController::yearsAction()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 59
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 36
c 3
b 0
f 0
dl 0
loc 59
rs 8.4106
cc 7
nc 11
nop 0

How to fix   Long Method   

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
    /**
23
     * This holds all issues for the list view.
24
     *
25
     * @var array
26
     * @access protected
27
     */
28
    protected $allIssues = [];
29
30
    /**
31
     * The main method of the plugin
32
     *
33
     * @return void
34
     */
35
    public function mainAction()
36
    {
37
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
38
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
39
40
        // Set initial document (anchor or year file) if configured.
41
        if (empty($requestData['id']) && !empty($this->settings['initialDocument'])) {
42
            $requestData['id'] = $this->settings['initialDocument'];
43
        }
44
45
        // Load current document.
46
        $this->loadDocument($requestData);
47
        if ($this->doc === null) {
48
            // Quit without doing anything if required variables are not set.
49
            return;
50
        }
51
52
        $metadata = $this->doc->getTitledata();
53
        if (!empty($metadata['type'][0])) {
54
            $type = $metadata['type'][0];
55
        } else {
56
            return;
57
        }
58
59
        switch ($type) {
60
            case 'newspaper':
61
            case 'ephemera':
62
                $this->forward('years', null, null, $requestData);
63
                break;
64
            case 'year':
65
                $this->forward('calendar', null, null, $requestData);
66
                break;
67
            case 'issue':
68
            default:
69
                break;
70
        }
71
72
    }
73
74
    /**
75
     * The Calendar Method
76
     *
77
     * @access public
78
     *
79
     * @param string $content: The PlugIn content
80
     * @param array $conf: The PlugIn configuration
81
     *
82
     * @return void
83
     */
84
    public function calendarAction()
85
    {
86
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
87
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
88
89
        // access arguments passed by the mainAction()
90
        $mainrquestData = $this->request->getArguments();
91
92
        // merge both arguments together --> passing id by GET parameter tx_dlf[id] should win
93
        $requestData = array_merge($requestData, $mainrquestData);
94
95
        // Load current document.
96
        $this->loadDocument($requestData);
97
        if ($this->doc === null) {
98
            // Quit without doing anything if required variables are not set.
99
            return;
100
        }
101
102
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
103
            ->getQueryBuilderForTable('tx_dlf_documents');
104
105
        // Get all children of year anchor.
106
        $result = $queryBuilder
107
            ->select(
108
                'tx_dlf_documents.uid AS uid',
109
                'tx_dlf_documents.title AS title',
110
                'tx_dlf_documents.year AS year',
111
                'tx_dlf_documents.mets_label AS label',
112
                'tx_dlf_documents.mets_orderlabel AS orderlabel'
113
            )
114
            ->from('tx_dlf_documents')
115
            ->where(
116
                $queryBuilder->expr()->eq('tx_dlf_documents.structure', Helper::getUidFromIndexName('issue', 'tx_dlf_structures', $this->doc->cPid)),
117
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($this->doc->uid)),
118
                Helper::whereExpression('tx_dlf_documents')
119
            )
120
            ->orderBy('tx_dlf_documents.mets_orderlabel')
121
            ->execute();
122
123
        $issues = [];
124
125
        // Process results.
126
        while ($resArray = $result->fetch()) {
127
            // Set title for display in calendar view.
128
            if (!empty($resArray['title'])) {
129
                $title = $resArray['title'];
130
            } else {
131
                $title = !empty($resArray['label']) ? $resArray['label'] : $resArray['orderlabel'];
132
                if (strtotime($title) !== false) {
133
                    $title = strftime('%x', strtotime($title));
134
                }
135
            }
136
            $issues[] = [
137
                'uid' => $resArray['uid'],
138
                'title' => $title,
139
                'year' => $resArray['year']
140
            ];
141
        }
142
        //  We need an array of issues with year => month => day number as key.
143
        $calendarIssuesByYear = [];
144
        foreach ($issues as $issue) {
145
            $dateTimestamp = strtotime($issue['year']);
146
            if ($dateTimestamp !== false) {
147
                $_year = date('Y', $dateTimestamp);
148
                $_month = date('n', $dateTimestamp);
149
                $_day = date('j', $dateTimestamp);
150
                $calendarIssuesByYear[$_year][$_month][$_day][] = $issue;
151
            } else {
152
                $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

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