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
04:50 queued 02:02
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
    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
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
219
            ->getQueryBuilderForTable('tx_dlf_documents');
220
221
        // Get all children of anchor. This should be the year anchor documents
222
        $result = $queryBuilder
223
            ->select(
224
                'tx_dlf_documents.uid AS uid',
225
                'tx_dlf_documents.title AS title',
226
                'tx_dlf_documents.mets_label AS label',
227
                'tx_dlf_documents.mets_orderlabel AS orderlabel'
228
            )
229
            ->from('tx_dlf_documents')
230
            ->where(
231
                $queryBuilder->expr()->eq('tx_dlf_documents.structure', Helper::getUidFromIndexName('year', 'tx_dlf_structures', $this->doc->cPid)),
232
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($this->doc->uid)),
233
                Helper::whereExpression('tx_dlf_documents')
234
            )
235
            ->orderBy('tx_dlf_documents.mets_orderlabel')
236
            ->execute();
237
238
        $years = [];
239
        // Process results.
240
        while ($resArray = $result->fetch()) {
241
            $years[] = [
242
                'title' => !empty($resArray['label']) ? $resArray['label'] : (!empty($resArray['orderlabel']) ? $resArray['orderlabel'] : $resArray['title']),
243
                'uid' => $resArray['uid']
244
            ];
245
        }
246
        $yearArray = [];
247
        if (count($years) > 0) {
248
            foreach ($years as $year) {
249
                $yearArray[] = [
250
                    'documentId' => $year['uid'],
251
                    'title' => $year['title']
252
                ];
253
            }
254
            $this->view->assign('yearName', $yearArray);
255
        }
256
257
        $this->view->assign('documentId', $this->doc->uid);
258
        $this->view->assign('allYearDocTitle', $this->doc->getTitle($this->doc->uid));
259
    }
260
261
    /**
262
     * Build calendar for a certain year
263
     *
264
     * @access protected
265
     *
266
     * @param array $calendarIssuesByMonth All issues sorted by month => day
267
     * @param int $year Gregorian year
268
     * @param int $firstMonth 1 for January, 2 for February, ... 12 for December
269
     * @param int $lastMonth 1 for January, 2 for February, ... 12 for December
270
     *
271
     * @return string Content for template subpart
272
     */
273
    protected function getCalendarYear($calendarIssuesByMonth, $year, $firstMonth = 1, $lastMonth = 12)
274
    {
275
        $calendarData = [];
276
        for ($i = $firstMonth; $i <= $lastMonth; $i++) {
277
            $calendarData[$i] = [
278
                'DAYMON_NAME' => strftime('%a', strtotime('last Monday')),
279
                'DAYTUE_NAME' => strftime('%a', strtotime('last Tuesday')),
280
                'DAYWED_NAME' => strftime('%a', strtotime('last Wednesday')),
281
                'DAYTHU_NAME' => strftime('%a', strtotime('last Thursday')),
282
                'DAYFRI_NAME' => strftime('%a', strtotime('last Friday')),
283
                'DAYSAT_NAME' => strftime('%a', strtotime('last Saturday')),
284
                'DAYSUN_NAME' => strftime('%a', strtotime('last Sunday')),
285
                'MONTHNAME'  => strftime('%B', strtotime($year . '-' . $i . '-1')) . ' ' . $year,
286
                'CALYEAR' => ($i == $firstMonth) ? $year : ''
287
            ];
288
289
            $firstOfMonth = strtotime($year . '-' . $i . '-1');
290
            $lastOfMonth = strtotime('last day of', ($firstOfMonth));
291
            $firstOfMonthStart = strtotime('last Monday', $firstOfMonth);
292
            // There are never more than 6 weeks in a month.
293
            for ($j = 0; $j <= 5; $j++) {
294
                $firstDayOfWeek = strtotime('+ ' . $j . ' Week', $firstOfMonthStart);
295
296
                $calendarData[$i]['week'][$j] = [
297
                    'DAYMON' => ['dayValue' => '&nbsp;'],
298
                    'DAYTUE' => ['dayValue' => '&nbsp;'],
299
                    'DAYWED' => ['dayValue' => '&nbsp;'],
300
                    'DAYTHU' => ['dayValue' => '&nbsp;'],
301
                    'DAYFRI' => ['dayValue' => '&nbsp;'],
302
                    'DAYSAT' => ['dayValue' => '&nbsp;'],
303
                    'DAYSUN' => ['dayValue' => '&nbsp;'],
304
                ];
305
                // Every week has seven days. ;-)
306
                for ($k = 0; $k <= 6; $k++) {
307
                    $currentDayTime = strtotime('+ ' . $k . ' Day', $firstDayOfWeek);
308
                    if (
309
                        $currentDayTime >= $firstOfMonth
310
                        && $currentDayTime <= $lastOfMonth
311
                    ) {
312
                        $dayLinks = '';
313
                        $dayLinksText = [];
314
                        $currentMonth = date('n', $currentDayTime);
315
                        if (is_array($calendarIssuesByMonth[$currentMonth])) {
316
                            foreach ($calendarIssuesByMonth[$currentMonth] as $id => $day) {
317
                                if ($id == date('j', $currentDayTime)) {
318
                                    $dayLinks = $id;
319
                                    foreach ($day as $issue) {
320
                                        $dayLinkLabel = empty($issue['title']) ? strftime('%x', $currentDayTime) : $issue['title'];
321
322
                                        $dayLinksText[] = [
323
                                            'documentId' => $issue['uid'],
324
                                            'text' => $dayLinkLabel
325
                                        ];
326
327
                                        // Save issue for list view.
328
                                        $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...
329
                                            'documentId' => $issue['uid'],
330
                                            'text' => $dayLinkLabel
331
                                        ];
332
                                    }
333
                                }
334
                            }
335
                            $dayLinkDiv = $dayLinksText;
336
                        }
337
                        switch (strftime('%w', strtotime('+ ' . $k . ' Day', $firstDayOfWeek))) {
338
                            case '0':
339
                                $calendarData[$i]['week'][$j]['DAYSUN']['dayValue'] = strftime('%d', $currentDayTime);
340
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
341
                                    $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...
342
                                }
343
                                break;
344
                            case '1':
345
                                $calendarData[$i]['week'][$j]['DAYMON']['dayValue'] = strftime('%d', $currentDayTime);
346
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
347
                                    $calendarData[$i]['week'][$j]['DAYMON']['issues'] = $dayLinkDiv;
348
                                }
349
                                break;
350
                            case '2':
351
                                $calendarData[$i]['week'][$j]['DAYTUE']['dayValue'] = strftime('%d', $currentDayTime);
352
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
353
                                    $calendarData[$i]['week'][$j]['DAYTUE']['issues'] = $dayLinkDiv;
354
                                }
355
                                break;
356
                            case '3':
357
                                $calendarData[$i]['week'][$j]['DAYWED']['dayValue'] = strftime('%d', $currentDayTime);
358
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
359
                                    $calendarData[$i]['week'][$j]['DAYWED']['issues'] = $dayLinkDiv;
360
                                }
361
                                break;
362
                            case '4':
363
                                $calendarData[$i]['week'][$j]['DAYTHU']['dayValue'] = strftime('%d', $currentDayTime);
364
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
365
                                    $calendarData[$i]['week'][$j]['DAYTHU']['issues'] = $dayLinkDiv;
366
                                }
367
                                break;
368
                            case '5':
369
                                $calendarData[$i]['week'][$j]['DAYFRI']['dayValue'] = strftime('%d', $currentDayTime);
370
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
371
                                    $calendarData[$i]['week'][$j]['DAYFRI']['issues'] = $dayLinkDiv;
372
                                }
373
                                break;
374
                            case '6':
375
                                $calendarData[$i]['week'][$j]['DAYSAT']['dayValue'] = strftime('%d', $currentDayTime);
376
                                if ((int) $dayLinks === (int) date('j', $currentDayTime)) {
377
                                    $calendarData[$i]['week'][$j]['DAYSAT']['issues'] = $dayLinkDiv;
378
                                }
379
                                break;
380
                        }
381
                    }
382
                }
383
            }
384
        }
385
        $this->view->assign('calendarData', $calendarData);
386
    }
387
}
388