Completed
Push — master ( ce3674...ce3674 )
by
unknown
15s queued 12s
created

CalendarController::getCalendarYear()   D

Complexity

Conditions 26
Paths 67

Size

Total Lines 114
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
eloc 84
nc 67
nop 4
dl 0
loc 114
rs 4.1666
c 0
b 0
f 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\Domain\Model\Document;
16
use Kitodo\Dlf\Domain\Repository\StructureRepository;
17
use TYPO3\CMS\Core\Database\ConnectionPool;
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
20
/**
21
 * Controller class for the plugin 'Calendar'.
22
 *
23
 * @author Alexander Bigga <[email protected]>
24
 * @author Sebastian Meyer <[email protected]>
25
 * @package TYPO3
26
 * @subpackage dlf
27
 * @access public
28
 */
29
class CalendarController extends AbstractController
30
{
31
    /**
32
     * @var StructureRepository
33
     */
34
    protected $structureRepository;
35
36
    /**
37
     * @param StructureRepository $structureRepository
38
     */
39
    public function injectStructureRepository(StructureRepository $structureRepository)
40
    {
41
        $this->structureRepository = $structureRepository;
42
    }
43
44
    /**
45
     * This holds all issues for the list view.
46
     *
47
     * @var array
48
     * @access protected
49
     */
50
    protected $allIssues = [];
51
52
    /**
53
     * The main method of the plugin
54
     *
55
     * @return void
56
     */
57
    public function mainAction()
58
    {
59
        // Set initial document (anchor or year file) if configured.
60
        if (empty($this->requestData['id']) && !empty($this->settings['initialDocument'])) {
61
            $this->requestData['id'] = $this->settings['initialDocument'];
62
        }
63
64
        // Load current document.
65
        $this->loadDocument($this->requestData);
66
        if ($this->document === null) {
67
            // Quit without doing anything if required variables are not set.
68
            return;
69
        }
70
71
        $metadata = $this->document->getDoc()->getTitledata();
72
        if (!empty($metadata['type'][0])) {
73
            $type = $metadata['type'][0];
74
        } else {
75
            return;
76
        }
77
78
        switch ($type) {
79
            case 'newspaper':
80
            case 'ephemera':
81
                $this->forward('years', null, null, $this->requestData);
82
                break;
83
            case 'year':
84
                $this->forward('calendar', null, null, $this->requestData);
85
                break;
86
            case 'issue':
87
            default:
88
                break;
89
        }
90
91
    }
92
93
    /**
94
     * The Calendar Method
95
     *
96
     * @access public
97
     *
98
     * @param string $content: The PlugIn content
99
     * @param array $conf: The PlugIn configuration
100
     *
101
     * @return void
102
     */
103
    public function calendarAction()
104
    {
105
        // access arguments passed by the mainAction()
106
        $mainrequestData = $this->request->getArguments();
107
108
        // merge both arguments together --> passing id by GET parameter tx_dlf[id] should win
109
        $this->requestData = array_merge($this->requestData, $mainrequestData);
110
111
        // Load current document.
112
        $this->loadDocument($this->requestData);
113
        if ($this->document === null) {
114
            // Quit without doing anything if required variables are not set.
115
            return;
116
        }
117
118
        $documents = $this->documentRepository->getChildrenOfYearAnchor($this->document->getUid(), $this->structureRepository->findOneByIndexName('issue'));
0 ignored issues
show
Bug introduced by
The method findOneByIndexName() does not exist on Kitodo\Dlf\Domain\Repository\StructureRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

118
        $documents = $this->documentRepository->getChildrenOfYearAnchor($this->document->getUid(), $this->structureRepository->/** @scrutinizer ignore-call */ findOneByIndexName('issue'));
Loading history...
119
120
        $issues = [];
121
122
        // Process results.
123
        /** @var Document $document */
124
        foreach ($documents as $document) {
125
            // Set title for display in calendar view.
126
            if (!empty($document->getTitle())) {
127
                $title = $document->getTitle();
128
            } else {
129
                $title = !empty($document->getMetsLabel()) ? $document->getMetsLabel() : $document->getMetsOrderlabel();
130
                if (strtotime($title) !== false) {
131
                    $title = strftime('%x', strtotime($title));
132
                }
133
            }
134
            $issues[] = [
135
                'uid' => $document->getUid(),
136
                'title' => $title,
137
                'year' => $document->getYear()
138
            ];
139
        }
140
141
        //  We need an array of issues with year => month => day number as key.
142
        $calendarIssuesByYear = [];
143
        foreach ($issues as $issue) {
144
            $dateTimestamp = strtotime($issue['year']);
145
            if ($dateTimestamp !== false) {
146
                $_year = date('Y', $dateTimestamp);
147
                $_month = date('n', $dateTimestamp);
148
                $_day = date('j', $dateTimestamp);
149
                $calendarIssuesByYear[$_year][$_month][$_day][] = $issue;
150
            } else {
151
                $this->logger->warning('Document with UID ' . $issue['uid'] . 'has no valid date of publication');
0 ignored issues
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

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