Completed
Push — master ( 70dfe1...a97a1c )
by Torben
04:18
created

PageLayoutView   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 413
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 52
lcom 1
cbo 5
dl 0
loc 413
rs 7.44
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getEventPluginSummary() 0 28 2
A getUserRegPluginSummary() 0 15 1
B getSwitchableControllerActionTitle() 0 25 6
A showFieldsForListViewOnly() 0 15 4
A getPluginPidConfig() 0 10 2
A getRecordData() 0 17 2
B getStoragePage() 0 32 6
A getOrderSettings() 0 18 3
A getOrderDirectionSetting() 0 11 2
B getCategoryConjuction() 0 32 7
A getOverrideDemandSettings() 0 20 3
A getCategorySettings() 0 23 4
A renderSettingsAsTable() 0 18 1
B getFieldFromFlexform() 0 14 7
A getLanguageService() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like PageLayoutView often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PageLayoutView, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
5
 *
6
 * For the full copyright and license information, please read the
7
 * LICENSE.txt file that was distributed with this source code.
8
 */
9
10
namespace DERHANSEN\SfEventMgt\Hooks;
11
12
use TYPO3\CMS\Backend\Utility\BackendUtility as BackendUtilityCore;
13
use TYPO3\CMS\Core\Imaging\Icon;
14
use TYPO3\CMS\Core\Imaging\IconFactory;
15
use TYPO3\CMS\Core\Localization\LanguageService;
16
use TYPO3\CMS\Core\Page\PageRenderer;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
use TYPO3\CMS\Fluid\View\StandaloneView;
19
20
/**
21
 * Hook to display verbose information about plugin in Web>Page module
22
 */
23
class PageLayoutView
24
{
25
    /**
26
     * Path to the locallang file
27
     *
28
     * @var string
29
     */
30
    const LLPATH = 'LLL:EXT:sf_event_mgt/Resources/Private/Language/locallang_be.xlf:';
31
32
    /**
33
     * Data rendered in table of Plugin settings
34
     *
35
     * @var array
36
     */
37
    public $data = [];
38
39
    /**
40
     * Flexform information
41
     *
42
     * @var array
43
     */
44
    public $flexformData = [];
45
46
    /**
47
     * @var IconFactory
48
     */
49
    protected $iconFactory;
50
51
    /**
52
     * PageLayoutView constructor
53
     */
54
    public function __construct()
55
    {
56
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
57
    }
58
59
    /**
60
     * Returns information about this extension's event plugin
61
     *
62
     * @param array $params Parameters to the hook
63
     * @return string Information about plugin
64
     */
65
    public function getEventPluginSummary(array $params)
66
    {
67
        $header = htmlspecialchars($this->getLanguageService()->sL(self::LLPATH . 'plugin.title'));
68
69
        // Add flexform switchable controller actions
70
        $this->flexformData = GeneralUtility::xml2array($params['row']['pi_flexform']);
0 ignored issues
show
Documentation Bug introduced by
It seems like \TYPO3\CMS\Core\Utility\...['row']['pi_flexform']) of type * is incompatible with the declared type array of property $flexformData.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
71
72
        // Extend header by flexible controller action
73
        $action = htmlspecialchars($this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.mode')) . ': ';
74
        $action .= $this->getSwitchableControllerActionTitle();
75
76
        $this->getPluginPidConfig('listPid', 'additional');
77
        $this->getPluginPidConfig('detailPid', 'additional');
78
        $this->getPluginPidConfig('registrationPid', 'additional');
79
        $this->getPluginPidConfig('paymentPid', 'additional');
80
        $this->getStoragePage('settings.storagePage');
81
        $this->getOrderSettings('settings.orderField', 'settings.orderDirection');
82
        $this->getOverrideDemandSettings();
83
84
        if ($this->showFieldsForListViewOnly()) {
85
            $this->getCategoryConjuction();
86
            $this->getCategorySettings();
87
        }
88
89
        $result = $this->renderSettingsAsTable($header, $action, $this->data);
90
91
        return $result;
92
    }
93
94
    /**
95
     * Returns information about this extension's user registrations plugin
96
     *
97
     * @param array $params Parameters to the hook
98
     * @return string Information about plugin
99
     */
100
    public function getUserRegPluginSummary(array $params)
101
    {
102
        $header = htmlspecialchars($this->getLanguageService()->sL(self::LLPATH . 'plugin_userreg.title'));
103
104
        // Add flexform switchable controller actions
105
        $this->flexformData = GeneralUtility::xml2array($params['row']['pi_flexform']);
0 ignored issues
show
Documentation Bug introduced by
It seems like \TYPO3\CMS\Core\Utility\...['row']['pi_flexform']) of type * is incompatible with the declared type array of property $flexformData.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
106
107
        $this->getPluginPidConfig('registrationPid', 'sDEF');
108
        $this->getStoragePage('settings.userRegistration.storagePage');
109
        $this->getOrderSettings('settings.userRegistration.orderField', 'settings.userRegistration.orderDirection');
110
111
        $result = $this->renderSettingsAsTable($header, null, $this->data);
112
113
        return $result;
114
    }
115
116
    /**
117
     * Returns the current title of the switchableControllerAction
118
     *
119
     * @return string
120
     */
121
    protected function getSwitchableControllerActionTitle()
122
    {
123
        $title = '';
124
        $actions = $this->getFieldFromFlexform('switchableControllerActions');
125
        switch ($actions) {
126
            case 'Event->list':
127
                $title = $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.mode.list');
128
                break;
129
            case 'Event->detail;Event->icalDownload':
130
                $title = $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.mode.detail');
131
                break;
132
            case 'Event->registration;Event->saveRegistration;Event->saveRegistrationResult;Event->confirmRegistration;Event->cancelRegistration':
133
                $title = $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.mode.registration');
134
                break;
135
            case 'Event->search':
136
                $title = $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.mode.search');
137
                break;
138
            case 'Event->calendar':
139
                $title = $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.mode.calendar');
140
                break;
141
            default:
142
        }
143
144
        return $title;
145
    }
146
147
    /**
148
     * Returns, if fields, that are only visible for list view, should be shown
149
     *
150
     * @return bool
151
     */
152
    protected function showFieldsForListViewOnly()
153
    {
154
        $actions = $this->getFieldFromFlexform('switchableControllerActions');
155
        switch ($actions) {
156
            case 'Event->list':
157
            case 'Event->search':
158
            case 'Event->calendar':
159
                $result = true;
160
                break;
161
            default:
162
                $result = false;
163
        }
164
165
        return $result;
166
    }
167
168
    /**
169
     * Returns the PID config for the given PID
170
     *
171
     * @param string $pidSetting
172
     * @param $sheet
173
     */
174
    public function getPluginPidConfig($pidSetting, $sheet = 'sDEF')
175
    {
176
        $pid = (int)$this->getFieldFromFlexform('settings.' . $pidSetting, $sheet);
177
        if ($pid > 0) {
178
            $this->data[] = [
179
                'title' => $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.' . $pidSetting),
180
                'value' => $this->getRecordData($pid)
181
            ];
182
        }
183
    }
184
185
    /**
186
     * @param int $id
187
     * @param string $table
188
     * @return string
189
     */
190
    public function getRecordData($id, $table = 'pages')
191
    {
192
        $content = '';
193
        $record = BackendUtilityCore::getRecord($table, $id);
194
195
        if (is_array($record)) {
196
            $data = '<span data-toggle="tooltip" data-placement="top" data-title="id=' . $record['uid'] . '">'
197
                . $this->iconFactory->getIconForRecord($table, $record, Icon::SIZE_SMALL)->render()
198
                . '</span> ';
199
            $content = BackendUtilityCore::wrapClickMenuOnIcon($data, $table, $record['uid'], true, '', '+info');
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
200
201
            $linkTitle = htmlspecialchars(BackendUtilityCore::getRecordTitle($table, $record));
202
            $content .= $linkTitle;
203
        }
204
205
        return $content;
206
    }
207
208
    /**
209
     * Get the storagePage
210
     *
211
     * @param string $field
212
     */
213
    public function getStoragePage($field)
214
    {
215
        $value = $this->getFieldFromFlexform($field);
216
217
        if (!empty($value)) {
218
            $pageIds = GeneralUtility::intExplode(',', $value, true);
219
            $pagesOut = [];
220
221
            foreach ($pageIds as $id) {
222
                $pagesOut[] = $this->getRecordData($id, 'pages');
223
            }
224
225
            $recursiveLevel = (int)$this->getFieldFromFlexform('settings.recursive');
226
            $recursiveLevelText = '';
227
            if ($recursiveLevel === 250) {
228
                $recursiveLevelText = $this->getLanguageService()->sL('LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.5');
229
            } elseif ($recursiveLevel > 0) {
230
                $recursiveLevelText = $this->getLanguageService()->sL('LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.' . $recursiveLevel);
231
            }
232
233
            if (!empty($recursiveLevelText)) {
234
                $recursiveLevelText = '<br />' .
235
                    htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_general.xlf:LGL.recursive')) . ' ' .
236
                    $recursiveLevelText;
237
            }
238
239
            $this->data[] = [
240
                'title' => $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_general.xlf:LGL.startingpoint'),
241
                'value' => implode(', ', $pagesOut) . $recursiveLevelText
242
            ];
243
        }
244
    }
245
246
    /**
247
     * Get order settings
248
     *
249
     * @param string $orderByField
250
     * @param string $orderDirectionField
251
     */
252
    public function getOrderSettings($orderByField, $orderDirectionField)
253
    {
254
        $orderField = $this->getFieldFromFlexform($orderByField);
255
        if (!empty($orderField)) {
256
            $text = $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.orderField.' . $orderField);
257
258
            // Order direction (asc, desc)
259
            $orderDirection = $this->getOrderDirectionSetting($orderDirectionField);
260
            if ($orderDirection) {
261
                $text .= ', ' . strtolower($orderDirection);
262
            }
263
264
            $this->data[] = [
265
                'title' => $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.orderField'),
266
                'value' => $text
267
            ];
268
        }
269
    }
270
271
    /**
272
     * Get order direction
273
     * @param string $orderDirectionField
274
     * @return string
275
     */
276
    public function getOrderDirectionSetting($orderDirectionField)
277
    {
278
        $text = '';
279
280
        $orderDirection = $this->getFieldFromFlexform($orderDirectionField);
281
        if (!empty($orderDirection)) {
282
            $text = $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.orderDirection.' . $orderDirection . 'ending');
283
        }
284
285
        return $text;
286
    }
287
288
    /**
289
     * Get category conjunction if a category is selected
290
     */
291
    public function getCategoryConjuction()
292
    {
293
        // If not category is selected, we do not need to display the category mode
294
        $categories = $this->getFieldFromFlexform('settings.category');
295
        if ($categories === null || $categories === '') {
296
            return;
297
        }
298
299
        $categoryConjunction = strtolower($this->getFieldFromFlexform('settings.categoryConjunction'));
300
        switch ($categoryConjunction) {
301
            case 'or':
302
            case 'and':
303
            case 'notor':
304
            case 'notand':
305
                $text = htmlspecialchars($this->getLanguageService()->sL(
306
                    self::LLPATH . 'flexforms_general.categoryConjunction.' . $categoryConjunction
307
                ));
308
                break;
309
            default:
310
                $text = htmlspecialchars($this->getLanguageService()->sL(
311
                    self::LLPATH . 'flexforms_general.categoryConjunction.ignore'
312
                ));
313
                $text .= ' <span class="label label-warning">' . htmlspecialchars($this->getLanguageService()->sL(
314
                    self::LLPATH . 'flexforms_general.possibleMisconfiguration'
315
                )) . '</span>';
316
        }
317
318
        $this->data[] = [
319
            'title' => $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.categoryConjunction'),
320
            'value' => $text
321
        ];
322
    }
323
324
    /**
325
     * Get information if override demand setting is disabled or not
326
     */
327
    public function getOverrideDemandSettings()
328
    {
329
        $field = $this->getFieldFromFlexform('settings.disableOverrideDemand', 'additional');
330
331
        if ($field == 1) {
332
            $text = '<i class="fa fa-check"></i>';
333
334
            // Check if plugin action is "calendar" and if so, show warning that calendar action will not work
335
            $action = $this->getFieldFromFlexform('switchableControllerActions');
336
            if ($action === 'Event->calendar') {
337
                $text .= ' <span class="label label-danger">' .
338
                    htmlspecialchars($this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.pluginCalendarMisonfiguration')) . '</span>';
339
            }
340
341
            $this->data[] = [
342
                'title' => $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.disableOverrideDemand'),
343
                'value' => $text
344
            ];
345
        }
346
    }
347
348
    /**
349
     * Get category settings
350
     */
351
    public function getCategorySettings()
352
    {
353
        $categories = GeneralUtility::intExplode(',', $this->getFieldFromFlexform('settings.category'), true);
354
        if (count($categories) > 0) {
355
            $categoriesOut = [];
356
            foreach ($categories as $id) {
357
                $categoriesOut[] = $this->getRecordData($id, 'sys_category');
358
            }
359
360
            $this->data[] = [
361
                'title' => $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.category'),
362
                'value' => implode(', ', $categoriesOut)
363
            ];
364
365
            $includeSubcategories = $this->getFieldFromFlexform('settings.includeSubcategories');
366
            if ((int)$includeSubcategories === 1) {
367
                $this->data[] = [
368
                    'title' => $this->getLanguageService()->sL(self::LLPATH . 'flexforms_general.includeSubcategories'),
369
                    'value' => '<i class="fa fa-check"></i>'
370
                ];
371
            }
372
        }
373
    }
374
375
    /**
376
     * Render the settings as table for Web>Page module
377
     * System settings are displayed in mono font
378
     *
379
     * @param string $header
380
     * @param string $action
381
     * @param array $data
382
     * @return string
383
     */
384
    protected function renderSettingsAsTable($header, $action, $data)
385
    {
386
        $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
387
        $pageRenderer->loadRequireJsModule('TYPO3/CMS/News/PageLayout');
388
        $pageRenderer->addCssFile('EXT:sf_event_mgt/Resources/Public/Css/Backend/PageLayoutView.css');
389
390
        $view = GeneralUtility::makeInstance(StandaloneView::class);
391
        $view->setTemplatePathAndFilename(
392
            GeneralUtility::getFileAbsFileName('EXT:sf_event_mgt/Resources/Private/Backend/PageLayoutView.html')
393
        );
394
        $view->assignMultiple([
395
            'header' => $header,
396
            'action' => $action,
397
            'data' => $data
398
        ]);
399
400
        return $view->render();
401
    }
402
403
    /**
404
     * Get field value from flexform configuration,
405
     * including checks if flexform configuration is available
406
     *
407
     * @param string $key name of the key
408
     * @param string $sheet name of the sheet
409
     * @return string|null if nothing found, value if found
410
     */
411
    public function getFieldFromFlexform($key, $sheet = 'sDEF')
412
    {
413
        $flexform = $this->flexformData;
414
        if (isset($flexform['data'])) {
415
            $flexform = $flexform['data'];
416
            if (is_array($flexform) && is_array($flexform[$sheet]) && is_array($flexform[$sheet]['lDEF'])
417
                && is_array($flexform[$sheet]['lDEF'][$key]) && isset($flexform[$sheet]['lDEF'][$key]['vDEF'])
418
            ) {
419
                return $flexform[$sheet]['lDEF'][$key]['vDEF'];
420
            }
421
        }
422
423
        return null;
424
    }
425
426
    /**
427
     * Return language service instance
428
     *
429
     * @return LanguageService
430
     */
431
    public function getLanguageService(): LanguageService
432
    {
433
        return $GLOBALS['LANG'];
434
    }
435
}
436