Completed
Push — feature/510-refactor-admin-mod... ( 914967 )
by Torben
04:09
created

AdministrationController::initializeView()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.8657
c 0
b 0
f 0
cc 6
nc 5
nop 1
1
<?php
2
namespace DERHANSEN\SfEventMgt\Controller;
3
4
/*
5
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
6
 *
7
 * For the full copyright and license information, please read the
8
 * LICENSE.txt file that was distributed with this source code.
9
 */
10
11
use DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand;
12
use DERHANSEN\SfEventMgt\Domain\Model\Dto\SearchDemand;
13
use DERHANSEN\SfEventMgt\Domain\Model\Event;
14
use DERHANSEN\SfEventMgt\Service;
15
use TYPO3\CMS\Backend\View\BackendTemplateView;
16
use TYPO3\CMS\Core\Utility\DebugUtility;
17
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
18
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
19
20
/**
21
 * AdministrationController
22
 *
23
 * @author Torben Hansen <[email protected]>
24
 */
25
class AdministrationController extends AbstractController
26
{
27
    /**
28
     * Backend Template Container
29
     *
30
     * @var string
31
     */
32
    protected $defaultViewObjectName = \TYPO3\CMS\Backend\View\BackendTemplateView::class;
33
34
    /**
35
     * CustomNotificationLogRepository
36
     *
37
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository
38
     */
39
    protected $customNotificationLogRepository = null;
40
41
    /**
42
     * ExportService
43
     *
44
     * @var \DERHANSEN\SfEventMgt\Service\ExportService
45
     */
46
    protected $exportService = null;
47
48
    /**
49
     * SettingsService
50
     *
51
     * @var \DERHANSEN\SfEventMgt\Service\SettingsService
52
     */
53
    protected $settingsService = null;
54
55
    /**
56
     * Backend User Session Service
57
     *
58
     * @var \DERHANSEN\SfEventMgt\Service\BeUserSessionService
59
     */
60
    protected $beUserSessionService = null;
61
62
    /**
63
     * The current page uid
64
     *
65
     * @var int
66
     */
67
    protected $pid = 0;
68
69
    /**
70
     * BackendTemplateContainer
71
     *
72
     * @var BackendTemplateView
73
     */
74
    protected $view;
75
76
    /**
77
     * DI for $customNotificationLogRepository
78
     *
79
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
80
     */
81
    public function injectCustomNotificationLogRepository(
82
        \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
83
    ) {
84
        $this->customNotificationLogRepository = $customNotificationLogRepository;
85
    }
86
87
    /**
88
     * DI for $exportService
89
     *
90
     * @param Service\ExportService $exportService
91
     */
92
    public function injectExportService(\DERHANSEN\SfEventMgt\Service\ExportService $exportService)
93
    {
94
        $this->exportService = $exportService;
95
    }
96
97
    /**
98
     * DI for $settingsService
99
     *
100
     * @param Service\SettingsService $settingsService
101
     */
102
    public function injectSettingsService(\DERHANSEN\SfEventMgt\Service\SettingsService $settingsService)
103
    {
104
        $this->settingsService = $settingsService;
105
    }
106
107
    /**
108
     * DI for $beUserSessionService
109
     *
110
     * @param Service\BeUserSessionService $beUserSessionService
111
     */
112
    public function injectBeUserSessionService(\DERHANSEN\SfEventMgt\Service\BeUserSessionService $beUserSessionService)
113
    {
114
        $this->beUserSessionService = $beUserSessionService;
115
    }
116
117
    /**
118
     * Set up the doc header properly here
119
     *
120
     * @param ViewInterface $view
121
     */
122
    protected function initializeView(ViewInterface $view)
123
    {
124
        /** @var BackendTemplateView $view */
125
        parent::initializeView($view);
126
        if ($this->actionMethodName === 'listAction'
127
            || $this->actionMethodName === 'indexNotifyAction'
128
            || $this->actionMethodName === 'settingsErrorAction') {
129
            //$this->generateMenu();
130
            //$this->registerDocheaderButtons();
131
132
            $pageRenderer = $this->view->getModuleTemplate()->getPageRenderer();
133
            $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DateTimePicker');
134
135
            $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ?
136
                ['MM-DD-YYYY', 'HH:mm MM-DD-YYYY']:
137
                ['DD-MM-YYYY', 'HH:mm DD-MM-YYYY'];
138
            $pageRenderer->addInlineSetting('DateTimePicker', 'DateFormat', $dateFormat);
139
140
            $this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
141
            if ($view instanceof BackendTemplateView) {
142
                $view->getModuleTemplate()->getPageRenderer()->addCssFile(
143
                    'EXT:sf_event_mgt/Resources/Public/Css/administration.css'
144
                );
145
            }
146
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
147
        }
148
    }
149
150
151
152
    /**
153
     * Initialize action
154
     *
155
     * @return void
156
     */
157
    public function initializeAction()
158
    {
159
        $this->pid = (int)\TYPO3\CMS\Core\Utility\GeneralUtility::_GET('id');
160
    }
161
162
    /**
163
     * Set date format for fields startDate and endDate
164
     *
165
     * @return void
166
     */
167
    public function initializeListAction()
168
    {
169
        if ($this->settings === null) {
170
            $this->redirect('settingsError');
171
        }
172
        $this->arguments->getArgument('searchDemand')
173
            ->getPropertyMappingConfiguration()->forProperty('startDate')
174
            ->setTypeConverterOption(
175
                DateTimeConverter::class,
176
                DateTimeConverter::CONFIGURATION_DATE_FORMAT,
177
                $this->settings['search']['dateFormat']
178
            );
179
        $this->arguments->getArgument('searchDemand')
180
            ->getPropertyMappingConfiguration()->forProperty('endDate')
181
            ->setTypeConverterOption(
182
                DateTimeConverter::class,
183
                DateTimeConverter::CONFIGURATION_DATE_FORMAT,
184
                $this->settings['search']['dateFormat']
185
            );
186
    }
187
188
    /**
189
     * List action for backend module
190
     *
191
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\SearchDemand $searchDemand SearchDemand
192
     * @param int $messageId MessageID
193
     *
194
     * @return void
195
     */
196
    public function listAction(SearchDemand $searchDemand = null, $messageId = null)
197
    {
198
        /** @var EventDemand $demand */
199
        $demand = $this->objectManager->get(EventDemand::class);
200
201
        if ($searchDemand !== null) {
202
            $searchDemand->setFields($this->settings['search']['fields']);
203
204
            $sessionData = [];
205
            $sessionData['searchDemand'] = $searchDemand;
206
            $this->beUserSessionService->saveSessionData($sessionData);
207
        } else {
208
            // Try to restore search demand from Session
209
            $searchDemand = $this->beUserSessionService->getSessionDataByKey('searchDemand');
210
        }
211
212
        $demand->setSearchDemand($searchDemand);
213
214
        if ($this->pid > 0) {
215
            $demand->setStoragePage($this->pid);
216
        }
217
218
        $variables = [];
219
        if ($messageId !== null && is_numeric($messageId)) {
220
            $variables['showMessage'] = true;
221
            $variables['messageTitleKey'] = 'administration.message-' . $messageId . '.title';
222
            $variables['messageContentKey'] = 'administration.message-' . $messageId . '.content';
223
        }
224
225
        $variables['events'] = $this->eventRepository->findDemanded($demand);
226
        $variables['searchDemand'] = $searchDemand;
227
        $variables['csvExportPossible'] = $this->getBackendUser()->getDefaultUploadTemporaryFolder() !== null;
228
        $this->view->assignMultiple($variables);
229
    }
230
231
    /**
232
     * Export registrations for a given event
233
     *
234
     * @param int $eventUid Event UID
235
     *
236
     * @return void
237
     */
238
    public function exportAction($eventUid)
239
    {
240
        $this->exportService->downloadRegistrationsCsv($eventUid, $this->settings['csvExport']);
241
        exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method exportAction() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
242
    }
243
244
    /**
245
     * Calls the handleExpiredRegistrations Service
246
     *
247
     * @return void
248
     */
249
    public function handleExpiredRegistrationsAction()
250
    {
251
        $this->registrationService->handleExpiredRegistrations($this->settings['registration']['deleteExpiredRegistrations']);
252
        $this->redirect('list', 'Administration', 'SfEventMgt', ['demand' => null, 'messageId' => 1]);
253
    }
254
255
    /**
256
     * The index notify action
257
     *
258
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
259
     *
260
     * @return void
261
     */
262
    public function indexNotifyAction(Event $event)
263
    {
264
        $customNotifications = $this->settingsService->getCustomNotifications($this->settings);
265
        $logEntries = $this->customNotificationLogRepository->findByEvent($event);
0 ignored issues
show
Documentation Bug introduced by
The method findByEvent does not exist on object<DERHANSEN\SfEvent...ificationLogRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
266
        $this->view->assignMultiple([
267
            'event' => $event,
268
            'customNotifications' => $customNotifications,
269
            'logEntries' => $logEntries,
270
        ]);
271
    }
272
273
    /**
274
     * Notify action
275
     *
276
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
277
     * @param string $customNotification CustomNotification
278
     *
279
     * @return void
280
     */
281
    public function notifyAction(Event $event, $customNotification)
282
    {
283
        $customNotifications = $this->settingsService->getCustomNotifications($this->settings);
284
        $result = $this->notificationService->sendCustomNotification($event, $customNotification, $this->settings);
285
        $this->notificationService->createCustomNotificationLogentry(
286
            $event,
287
            $customNotifications[$customNotification],
288
            $result
289
        );
290
        $this->redirect('list', 'Administration', 'SfEventMgt', ['demand' => null, 'messageId' => 2]);
291
    }
292
293
    /**
294
     * Shows the settings error view
295
     *
296
     * @return void
297
     */
298
    public function settingsErrorAction()
299
    {
300
    }
301
302
    /**
303
     * Suppress default validation messages
304
     *
305
     * @return bool
306
     */
307
    protected function getErrorFlashMessage()
308
    {
309
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type of the parent method TYPO3\CMS\Extbase\Mvc\Co...r::getErrorFlashMessage of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
310
    }
311
312
    /**
313
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
314
     */
315
    protected function getBackendUser()
316
    {
317
        return $GLOBALS['BE_USER'];
318
    }
319
}
320