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 (#436)
by Alexander
04:35
created

Calendar::getCalendarYear()   D

Complexity

Conditions 28
Paths 97

Size

Total Lines 107
Code Lines 82

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 82
c 0
b 0
f 0
dl 0
loc 107
rs 4.1666
cc 28
nc 97
nop 4

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\Plugin;
14
15
use Kitodo\Dlf\Common\Helper;
16
use TYPO3\CMS\Core\Database\ConnectionPool;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
19
/**
20
 * Plugin 'Calendar' for the 'dlf' extension
21
 *
22
 * @author Alexander Bigga <[email protected]>
23
 * @author Sebastian Meyer <[email protected]>
24
 * @package TYPO3
25
 * @subpackage dlf
26
 * @access public
27
 */
28
class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin
29
{
30
    public $scriptRelPath = 'Classes/Plugin/Calendar.php';
31
32
    /**
33
     * This holds all issues for the list view.
34
     *
35
     * @var array
36
     * @access protected
37
     */
38
    protected $allIssues = [];
39
40
    /**
41
     * The main method of the PlugIn
42
     *
43
     * @access public
44
     *
45
     * @param string $content: The PlugIn content
46
     * @param array $conf: The PlugIn configuration
47
     *
48
     * @return string The content that is displayed on the website
49
     */
50
    public function main($content, $conf)
51
    {
52
        // Nothing to do here.
53
        return $content;
54
    }
55
56
    /**
57
     * The Calendar Method
58
     *
59
     * @access public
60
     *
61
     * @param string $content: The PlugIn content
62
     * @param array $conf: The PlugIn configuration
63
     *
64
     * @return string The content that is displayed on the website
65
     */
66
    public function calendar($content, $conf)
67
    {
68
        $this->init($conf);
69
        // Load current document.
70
        $this->loadDocument();
71
        if ($this->doc === null) {
72
            // Quit without doing anything if required variables are not set.
73
            return $content;
74
        }
75
        // Load template file.
76
        $this->getTemplate('###TEMPLATECALENDAR###');
77
78
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
79
            ->getQueryBuilderForTable('tx_dlf_documents');
80
81
        // Get all children of year anchor.
82
        $result = $queryBuilder
83
            ->select(
84
                'tx_dlf_documents.uid AS uid',
85
                'tx_dlf_documents.title AS title',
86
                'tx_dlf_documents.year AS year',
87
                'tx_dlf_documents.mets_label AS label',
88
                'tx_dlf_documents.mets_orderlabel AS orderlabel'
89
            )
90
            ->from('tx_dlf_documents')
91
            ->where(
92
                $queryBuilder->expr()->eq('tx_dlf_documents.structure', Helper::getUidFromIndexName('issue', 'tx_dlf_structures', $this->doc->pid)),
93
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($this->doc->uid)),
94
                Helper::whereExpression('tx_dlf_documents')
95
            )
96
            ->orderBy('tx_dlf_documents.mets_orderlabel')
97
            ->execute();
98
99
        $issues = [];
100
101
        // Process results.
102
        while ($resArray = $result->fetch()) {
103
            // Set title for display in calendar view.
104
            if (!empty($resArray['title'])) {
105
                $title = $resArray['title'];
106
            } else {
107
                $title = !empty($resArray['label']) ? $resArray['label'] : $resArray['orderlabel'];
108
                if (strtotime($title) !== false) {
109
                    $title = strftime('%x', strtotime($title));
110
                }
111
            }
112
            $issues[] = [
113
                'uid' => $resArray['uid'],
114
                'title' => $title,
115
                'year' => $resArray['year']
116
            ];
117
        }
118
        //  We need an array of issues with year => month => day number as key.
119
        $calendarIssuesByYear = [];
120
        foreach ($issues as $issue) {
121
            $dateTimestamp = strtotime($issue['year']);
122
            if ($dateTimestamp !== false) {
123
                $_year = date('Y', $dateTimestamp);
124
                $_month = date('n', $dateTimestamp);
125
                $_day = date('j', $dateTimestamp);
126
                $calendarIssuesByYear[$_year][$_month][$_day][] = $issue;
127
            } else {
128
                Helper::devLog('Document with UID ' . $issue['uid'] . 'has no valid date of publication', DEVLOG_SEVERITY_WARNING);
129
            }
130
        }
131
        // Sort by years.
132
        ksort($calendarIssuesByYear);
133
        // Build calendar for year (default) or season.
134
        $subPartContent = '';
135
        $iteration = 1;
136
        foreach ($calendarIssuesByYear as $year => $calendarIssuesByMonth) {
137
            // Sort by months.
138
            ksort($calendarIssuesByMonth);
139
            // Default: First monath is January, last month is December.
140
            $firstMonth = 1;
141
            $lastMonth = 12;
142
            // Show calendar from first issue up to end of season if applicable.
143
            if (
144
                empty($this->conf['showEmptyMonths'])
145
                && count($calendarIssuesByYear) > 1
146
            ) {
147
                if ($iteration == 1) {
148
                    $firstMonth = (int) key($calendarIssuesByMonth);
149
                } elseif ($iteration == count($calendarIssuesByYear)) {
150
                    end($calendarIssuesByMonth);
151
                    $lastMonth = (int) key($calendarIssuesByMonth);
152
                }
153
            }
154
            $subPartContent .= $this->getCalendarYear($calendarIssuesByMonth, $year, $firstMonth, $lastMonth);
155
            $iteration++;
156
        }
157
        // Prepare list as alternative view.
158
        $subPartContentList = '';
159
        // Get subpart templates.
160
        $subParts['list'] = $this->templateService->getSubpart($this->template, '###ISSUELIST###');
161
        $subParts['singleday'] = $this->templateService->getSubpart($subParts['list'], '###SINGLEDAY###');
162
        foreach ($this->allIssues as $dayTimestamp => $issues) {
163
            $markerArrayDay['###DATE_STRING###'] = strftime('%A, %x', $dayTimestamp);
164
            $markerArrayDay['###ITEMS###'] = '';
165
            foreach ($issues as $issue) {
166
                $markerArrayDay['###ITEMS###'] .= $issue;
167
            }
168
            $subPartContentList .= $this->templateService->substituteMarkerArray($subParts['singleday'], $markerArrayDay);
169
        }
170
        $this->template = $this->templateService->substituteSubpart($this->template, '###SINGLEDAY###', $subPartContentList);
171
        // Link to current year.
172
        $linkConf = [
173
            'useCacheHash' => 1,
174
            'parameter' => $this->conf['targetPid'],
175
            'additionalParams' => '&' . $this->prefixId . '[id]=' . urlencode($this->doc->uid),
176
        ];
177
        $linkTitleData = $this->doc->getTitledata();
178
        $linkTitle = !empty($linkTitleData['mets_orderlabel'][0]) ? $linkTitleData['mets_orderlabel'][0] : $linkTitleData['mets_label'][0];
179
        $yearLink = $this->cObj->typoLink($linkTitle, $linkConf);
180
        // Link to years overview.
181
        $linkConf = [
182
            'useCacheHash' => 1,
183
            'parameter' => $this->conf['targetPid'],
184
            'additionalParams' => '&' . $this->prefixId . '[id]=' . urlencode($this->doc->parentId),
185
        ];
186
        $allYearsLink = $this->cObj->typoLink($this->pi_getLL('allYears', '', true) . ' ' . $this->doc->getTitle($this->doc->parentId), $linkConf);
187
        // Fill marker array.
188
        $markerArray = [
189
            '###CALENDARVIEWACTIVE###' => count($this->allIssues) > 5 ? 'active' : '',
190
            '###LISTVIEWACTIVE###' => count($this->allIssues) < 6 ? 'active' : '',
191
            '###CALYEAR###' => $yearLink,
192
            '###CALALLYEARS###' => $allYearsLink,
193
            '###LABEL_CALENDAR###' => $this->pi_getLL('label.view_calendar'),
194
            '###LABEL_LIST_VIEW###' => $this->pi_getLL('label.view_list'),
195
        ];
196
        $this->template = $this->templateService->substituteMarkerArray($this->template, $markerArray);
197
        return $this->templateService->substituteSubpart($this->template, '###CALMONTH###', $subPartContent);
198
    }
199
200
    /**
201
     * Build calendar for a certain year
202
     *
203
     * @access protected
204
     *
205
     * @param array $calendarIssuesByMonth All issues sorted by month => day
206
     * @param int $year Gregorian year
207
     * @param int $firstMonth 1 for January, 2 for February, ... 12 for December
208
     * @param int $lastMonth 1 for January, 2 for February, ... 12 for December
209
     *
210
     * @return string Content for template subpart
211
     */
212
    protected function getCalendarYear($calendarIssuesByMonth, $year, $firstMonth = 1, $lastMonth = 12)
213
    {
214
        // Get subpart templates.
215
        $subPartContent = '';
216
        $subParts['month'] = $this->templateService->getSubpart($this->template, '###CALMONTH###');
217
        $subParts['week'] = $this->templateService->getSubpart($subParts['month'], '###CALWEEK###');
218
        for ($i = $firstMonth; $i <= $lastMonth; $i++) {
219
            $markerArray = [
220
                '###DAYMON_NAME###' => strftime('%a', strtotime('last Monday')),
221
                '###DAYTUE_NAME###' => strftime('%a', strtotime('last Tuesday')),
222
                '###DAYWED_NAME###' => strftime('%a', strtotime('last Wednesday')),
223
                '###DAYTHU_NAME###' => strftime('%a', strtotime('last Thursday')),
224
                '###DAYFRI_NAME###' => strftime('%a', strtotime('last Friday')),
225
                '###DAYSAT_NAME###' => strftime('%a', strtotime('last Saturday')),
226
                '###DAYSUN_NAME###' => strftime('%a', strtotime('last Sunday')),
227
                '###MONTHNAME###'  => strftime('%B', strtotime($year . '-' . $i . '-1')) . ' ' . $year,
228
                '###CALYEAR###' => ($i == $firstMonth) ? '<div class="year">' . $year . '</div>' : ''
229
            ];
230
            // Fill the month markers.
231
            $subPartContentMonth = $this->templateService->substituteMarkerArray($subParts['month'], $markerArray);
232
            // Reset week content of new month.
233
            $subPartContentWeek = '';
234
            $firstOfMonth = strtotime($year . '-' . $i . '-1');
235
            $lastOfMonth = strtotime('last day of', ($firstOfMonth));
236
            $firstOfMonthStart = strtotime('last Monday', $firstOfMonth);
237
            // There are never more than 6 weeks in a month.
238
            for ($j = 0; $j <= 5; $j++) {
239
                $firstDayOfWeek = strtotime('+ ' . $j . ' Week', $firstOfMonthStart);
240
                $weekArray = [
241
                    '###DAYMON###' => '&nbsp;',
242
                    '###DAYTUE###' => '&nbsp;',
243
                    '###DAYWED###' => '&nbsp;',
244
                    '###DAYTHU###' => '&nbsp;',
245
                    '###DAYFRI###' => '&nbsp;',
246
                    '###DAYSAT###' => '&nbsp;',
247
                    '###DAYSUN###' => '&nbsp;',
248
                ];
249
                // Every week has seven days. ;-)
250
                for ($k = 0; $k <= 6; $k++) {
251
                    $currentDayTime = strtotime('+ ' . $k . ' Day', $firstDayOfWeek);
252
                    if (
253
                        $currentDayTime >= $firstOfMonth
254
                        && $currentDayTime <= $lastOfMonth
255
                    ) {
256
                        $dayLinks = '';
257
                        $dayLinksText = [];
258
                        $dayLinksList = '';
259
                        $currentMonth = date('n', $currentDayTime);
260
                        if (is_array($calendarIssuesByMonth[$currentMonth])) {
261
                            foreach ($calendarIssuesByMonth[$currentMonth] as $id => $day) {
262
                                if ($id == date('j', $currentDayTime)) {
263
                                    $dayLinks = $id;
264
                                    foreach ($day as $issue) {
265
                                        $dayLinkLabel = empty($issue['title']) ? strftime('%x', $currentDayTime) : $issue['title'];
266
                                        $linkConf = [
267
                                            'useCacheHash' => 1,
268
                                            'parameter' => $this->conf['targetPid'],
269
                                            'additionalParams' => '&' . $this->prefixId . '[id]=' . urlencode($issue['uid']),
270
                                            'ATagParams' => ' class="title"',
271
                                        ];
272
                                        $dayLinksText[] = $this->cObj->typoLink($dayLinkLabel, $linkConf);
273
                                        // Save issue for list view.
274
                                        $this->allIssues[$currentDayTime][] = $this->cObj->typoLink($dayLinkLabel, $linkConf);
275
                                    }
276
                                }
277
                            }
278
                            if (!empty($dayLinksText)) {
279
                                $dayLinksList = '<ul>';
280
                                foreach ($dayLinksText as $link) {
281
                                    $dayLinksList .= '<li>' . $link . '</li>';
282
                                }
283
                                $dayLinksList .= '</ul>';
284
                            }
285
                            $dayLinkDiv = '<div class="issues"><h4>' . strftime('%d', $currentDayTime) . '</h4><div>' . $dayLinksList . '</div></div>';
286
                        }
287
                        switch (strftime('%w', strtotime('+ ' . $k . ' Day', $firstDayOfWeek))) {
288
                            case '0':
289
                                $weekArray['###DAYSUN###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
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...
290
                                break;
291
                            case '1':
292
                                $weekArray['###DAYMON###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
293
                                break;
294
                            case '2':
295
                                $weekArray['###DAYTUE###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
296
                                break;
297
                            case '3':
298
                                $weekArray['###DAYWED###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
299
                                break;
300
                            case '4':
301
                                $weekArray['###DAYTHU###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
302
                                break;
303
                            case '5':
304
                                $weekArray['###DAYFRI###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
305
                                break;
306
                            case '6':
307
                                $weekArray['###DAYSAT###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
308
                                break;
309
                        }
310
                    }
311
                }
312
                // Fill the weeks.
313
                $subPartContentWeek .= $this->templateService->substituteMarkerArray($subParts['week'], $weekArray);
314
            }
315
            // Fill the week markers with the week entries.
316
            $subPartContent .= $this->templateService->substituteSubpart($subPartContentMonth, '###CALWEEK###', $subPartContentWeek);
317
        }
318
        return $subPartContent;
319
    }
320
321
    /**
322
     * The Years Method
323
     *
324
     * @access public
325
     *
326
     * @param string $content: The PlugIn content
327
     * @param array $conf: The PlugIn configuration
328
     *
329
     * @return string The content that is displayed on the website
330
     */
331
    public function years($content, $conf)
332
    {
333
        $this->init($conf);
334
        // Load current document.
335
        $this->loadDocument();
336
        if ($this->doc === null) {
337
            // Quit without doing anything if required variables are not set.
338
            return $content;
339
        }
340
        // Load template file.
341
        $this->getTemplate('###TEMPLATEYEAR###');
342
        // Get subpart templates
343
        $subparts['year'] = $this->templateService->getSubpart($this->template, '###LISTYEAR###');
344
        // Get the title of the anchor file
345
        $titleAnchor = $this->doc->getTitle($this->doc->uid);
346
347
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
348
            ->getQueryBuilderForTable('tx_dlf_documents');
349
350
        // Get all children of anchor. This should be the year anchor documents
351
        $result = $queryBuilder
352
            ->select(
353
                'tx_dlf_documents.uid AS uid',
354
                'tx_dlf_documents.title AS title',
355
                'tx_dlf_documents.mets_label AS label',
356
                'tx_dlf_documents.mets_orderlabel AS orderlabel'
357
            )
358
            ->from('tx_dlf_documents')
359
            ->where(
360
                $queryBuilder->expr()->eq('tx_dlf_documents.structure', Helper::getUidFromIndexName('year', 'tx_dlf_structures', $this->doc->pid)),
361
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($this->doc->uid)),
362
                Helper::whereExpression('tx_dlf_documents')
363
            )
364
            ->orderBy('tx_dlf_documents.volume_sorting')
365
            ->execute();
366
367
        $years = [];
368
        // Process results.
369
        while ($resArray = $result->fetch()) {
370
            $years[] = [
371
                'title' => !empty($resArray['label']) ? $resArray['label'] : (!empty($resArray['orderlabel']) ? $resArray['orderlabel'] : $resArray['title']),
372
                'uid' => $resArray['uid']
373
            ];
374
        }
375
        $subYearPartContent = '';
376
        if (count($years) > 0) {
377
            foreach ($years as $year) {
378
                $linkConf = [
379
                    'useCacheHash' => 1,
380
                    'parameter' => $this->conf['targetPid'],
381
                    'additionalParams' => '&' . $this->prefixId . '[id]=' . urlencode($year['uid']),
382
                    'title' => $titleAnchor . ': ' . $year['title']
383
                ];
384
                $yearArray = [
385
                    '###YEARNAME###' => $this->cObj->typoLink($year['title'], $linkConf),
386
                ];
387
                $subYearPartContent .= $this->templateService->substituteMarkerArray($subparts['year'], $yearArray);
388
            }
389
        }
390
        // Link to years overview (should be itself here)
391
        $linkConf = [
392
            'useCacheHash' => 1,
393
            'parameter' => $this->conf['targetPid'],
394
            'additionalParams' => '&' . $this->prefixId . '[id]=' . $this->doc->uid,
395
        ];
396
        $allYearsLink = $this->cObj->typoLink($this->pi_getLL('allYears', '', true) . ' ' . $this->doc->getTitle($this->doc->uid), $linkConf);
397
        // Fill markers.
398
        $markerArray = [
399
            '###LABEL_CHOOSE_YEAR###' => $this->pi_getLL('label.please_choose_year'),
400
            '###CALALLYEARS###' => $allYearsLink
401
        ];
402
        $this->template = $this->templateService->substituteMarkerArray($this->template, $markerArray);
403
        // Fill the week markers
404
        return $this->templateService->substituteSubpart($this->template, '###LISTYEAR###', $subYearPartContent);
405
    }
406
}
407