Passed
Push — master ( 2ba76b...3603b1 )
by Ralf
11:11
created

AbstractDocumentFormController   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 395
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 44
eloc 154
c 4
b 0
f 0
dl 0
loc 395
rs 8.8798

12 Methods

Rating   Name   Duplication   Size   Complexity  
A listAction() 0 15 3
A initializeNewAction() 0 20 4
B createAction() 0 78 11
A newAction() 0 11 3
A initializeCreateAction() 0 26 4
A initializeEditAction() 0 22 4
A editAction() 0 10 3
A redirectAfterUpdate() 0 3 1
A initializeUpdateAction() 0 25 4
A updateAction() 0 43 5
A cancelAction() 0 3 1
A redirectToList() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like AbstractDocumentFormController 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.

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 AbstractDocumentFormController, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace EWW\Dpf\Controller;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use EWW\Dpf\Domain\Model\Document;
18
use EWW\Dpf\Domain\Model\DocumentForm;
19
use EWW\Dpf\Domain\Model\File;
20
use EWW\Dpf\Helper\DocumentMapper;
21
use EWW\Dpf\Helper\FormDataReader;
22
use EWW\Dpf\Domain\Workflow\DocumentWorkflow;
23
use EWW\Dpf\Services\Email\Notifier;
24
use EWW\Dpf\Domain\Model\DepositLicenseLog;
25
26
27
/**
28
 * DocumentFormController
29
 */
30
abstract class AbstractDocumentFormController extends AbstractController
31
{
32
33
    /**
34
     * documentRepository
35
     *
36
     * @var \EWW\Dpf\Domain\Repository\DocumentRepository
37
     * @TYPO3\CMS\Extbase\Annotation\Inject
38
     */
39
    protected $documentRepository = null;
40
41
    /**
42
     * fileRepository
43
     *
44
     * @var \EWW\Dpf\Domain\Repository\FileRepository
45
     * @TYPO3\CMS\Extbase\Annotation\Inject
46
     */
47
    protected $fileRepository = null;
48
49
    /**
50
     * documentTypeRepository
51
     *
52
     * @var \EWW\Dpf\Domain\Repository\DocumentTypeRepository
53
     * @TYPO3\CMS\Extbase\Annotation\Inject
54
     */
55
    protected $documentTypeRepository = null;
56
57
    /**
58
     * metadataGroupRepository
59
     *
60
     * @var \EWW\Dpf\Domain\Repository\MetadataGroupRepository
61
     * @TYPO3\CMS\Extbase\Annotation\Inject
62
     */
63
    protected $metadataGroupRepository = null;
64
65
    /**
66
     * metadataObjectRepository
67
     *
68
     * @var \EWW\Dpf\Domain\Repository\MetadataObjectRepository
69
     * @TYPO3\CMS\Extbase\Annotation\Inject
70
     */
71
    protected $metadataObjectRepository = null;
72
73
    /**
74
     * depositLicenseLogRepository
75
     *
76
     * @var \EWW\Dpf\Domain\Repository\DepositLicenseLogRepository
77
     * @TYPO3\CMS\Extbase\Annotation\Inject
78
     */
79
    protected $depositLicenseLogRepository = null;
80
81
    /**
82
     * persistence manager
83
     *
84
     * @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
85
     * @TYPO3\CMS\Extbase\Annotation\Inject
86
     */
87
    protected $persistenceManager;
88
89
    /**
90
     * fisDataService
91
     *
92
     * @var \EWW\Dpf\Services\FeUser\FisDataService
93
     * @TYPO3\CMS\Extbase\Annotation\Inject
94
     */
95
    protected $fisDataService = null;
96
97
    /**
98
     * action list
99
     *
100
     * @return void
101
     */
102
    public function listAction()
103
    {
104
        $documents = $this->documentRepository->findAll();
105
        $docTypes = $this->documentTypeRepository->getDocumentTypesAlphabetically();
106
107
        if ($this->request->hasArgument('message')) {
108
            $this->view->assign('message', $this->request->getArgument('message'));
109
        }
110
111
        if ($this->request->hasArgument('errorFiles')) {
112
            $this->view->assign('errorFiles', $this->request->getArgument('errorFiles'));
113
        }
114
115
        $this->view->assign('documentTypes', $docTypes);
116
        $this->view->assign('documents', $documents);
117
    }
118
119
    /**
120
     * initialize newAction
121
     *
122
     * @return void
123
     */
124
    public function initializeNewAction()
125
    {
126
127
        $requestArguments = $this->request->getArguments();
128
129
        if (array_key_exists('documentData', $requestArguments)) {
130
            die('Error: initializeNewAction');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
131
        } elseif (array_key_exists('documentType', $requestArguments)) {
132
            $docTypeUid   = $this->request->getArgument('documentType');
133
            $documentType = $this->documentTypeRepository->findByUid($docTypeUid);
0 ignored issues
show
Bug introduced by
$docTypeUid of type array|string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Extbase\Persis...Repository::findByUid(). ( Ignorable by Annotation )

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

133
            $documentType = $this->documentTypeRepository->findByUid(/** @scrutinizer ignore-type */ $docTypeUid);
Loading history...
134
            $document     = $this->objectManager->get(Document::class);
135
            $document->setDocumentType($documentType);
136
            $mapper  = $this->objectManager->get(DocumentMapper::class);
137
            $docForm = $mapper->getDocumentForm($document);
138
        } elseif (array_key_exists('newDocumentForm', $requestArguments)) {
139
            $docForm = $this->request->getArgument('newDocumentForm');
140
        }
141
142
        $requestArguments['newDocumentForm'] = $docForm;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $docForm does not seem to be defined for all execution paths leading up to this point.
Loading history...
143
        $this->request->setArguments($requestArguments);
144
    }
145
146
    /**
147
     * action new
148
     *
149
     * @param \EWW\Dpf\Domain\Model\DocumentForm $newDocumentForm
150
     * @param int $returnDocumentId
151
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("newDocumentForm")
152
     * @return void
153
     */
154
    public function newAction(DocumentForm $newDocumentForm = null, $returnDocumentId = 0)
155
    {
156
        $this->view->assign('returnDocumentId', $returnDocumentId);
157
        $this->view->assign('documentForm', $newDocumentForm);
158
159
        if (!empty($this->security->getUserAccessToGroups())) {
160
            $this->view->assign('currentUserAccessToGroup', $this->security->getUserAccessToGroups());
161
        }
162
163
        if ($this->fisDataService->getPersonData($this->security->getFisPersId())) {
164
            $this->view->assign('fisPersId', $this->security->getFisPersId());
165
        }
166
    }
167
168
    public function initializeCreateAction()
169
    {
170
171
        $requestArguments = $this->request->getArguments();
172
173
        if ($this->request->hasArgument('documentData')) {
174
            $documentData = $this->request->getArgument('documentData');
175
176
            $formDataReader = $this->objectManager->get(FormDataReader::class);
177
            $formDataReader->setFormData($documentData);
178
179
            $docForm                             = $formDataReader->getDocumentForm();
180
            $requestArguments['newDocumentForm'] = $docForm;
181
182
            $docTypeUid = $documentData['type'];
183
            $documentType = $this->documentTypeRepository->findByUid($docTypeUid);
184
            $virtualType = $documentType->getVirtualType();
185
186
            if (!$formDataReader->uploadError() || $virtualType === true) {
187
                $this->request->setArguments($requestArguments);
188
            } else {
189
                $t = $docForm->getNewFileNames();
190
                $this->redirect('list', 'DocumentForm', null, array('message' => 'UPLOAD_MAX_FILESIZE_ERROR', 'errorFiles' => $t));
191
            }
192
        } else {
193
            $this->redirectToList("UPLOAD_POST_SIZE_ERROR");
194
        }
195
    }
196
197
    /**
198
     * action create
199
     *
200
     * @param \EWW\Dpf\Domain\Model\DocumentForm $newDocumentForm
201
     * @return void
202
     */
203
    public function createAction(DocumentForm $newDocumentForm)
204
    {
205
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
206
207
        /* @var $newDocument \EWW\Dpf\Domain\Model\Document */
208
        $newDocument    = $documentMapper->getDocument($newDocumentForm);
209
210
        $workflow = $this->objectManager->get(DocumentWorkflow::class)->getWorkflow();
211
212
        if ($this->request->getPluginName() === "Backoffice") {
213
            $newDocument->setCreator($this->security->getUser()->getUid());
214
            $workflow->apply($newDocument, DocumentWorkflow::TRANSITION_CREATE);
215
        } else {
216
            $workflow->apply($newDocument, DocumentWorkflow::TRANSITION_CREATE_REGISTER);
217
        }
218
219
        // xml data fields are limited to 64 KB
220
        if (strlen($newDocument->getXmlData()) >= Document::XML_DATA_SIZE_LIMIT) {
221
            throw new \EWW\Dpf\Exceptions\DocumentMaxSizeErrorException("Maximum document size exceeded.");
222
        }
223
224
        $this->documentRepository->add($newDocument);
225
        $this->persistenceManager->persistAll();
226
227
        $newDocument = $this->documentRepository->findByUid($newDocument->getUid());
228
        $this->persistenceManager->persistAll();
229
230
        $depositLicenseLog = $this->depositLicenseLogRepository->findOneByProcessNumber($newDocument->getProcessNumber());
0 ignored issues
show
Bug introduced by
The method findOneByProcessNumber() does not exist on EWW\Dpf\Domain\Repositor...sitLicenseLogRepository. 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

230
        /** @scrutinizer ignore-call */ 
231
        $depositLicenseLog = $this->depositLicenseLogRepository->findOneByProcessNumber($newDocument->getProcessNumber());
Loading history...
231
        if (empty($depositLicenseLog) && $newDocument->getDepositLicense()) {
232
            // Only if there was no deposit license a notification may be sent
233
234
            /** @var DepositLicenseLog $depositLicenseLog */
235
            $depositLicenseLog = $this->objectManager->get(DepositLicenseLog::class);
236
            $depositLicenseLog->setUsername($this->security->getUsername());
237
            $depositLicenseLog->setObjectIdentifier($newDocument->getObjectIdentifier());
238
            $depositLicenseLog->setProcessNumber($newDocument->getProcessNumber());
239
            $depositLicenseLog->setTitle($newDocument->getTitle());
240
            $depositLicenseLog->setUrn($newDocument->getPrimaryUrn());
241
            $depositLicenseLog->setLicenceUri($newDocument->getDepositLicense());
242
243
            if ($newDocument->getFileData()) {
244
245
                $fileList = [];
246
                foreach ($newDocument->getFile() as $file) {
247
                    if (!$file->isFileGroupDeleted()) {
248
                        $fileList[] = $file->getTitle();
249
                    }
250
                }
251
                $depositLicenseLog->setFileNames(implode(", ", $fileList));
252
            }
253
254
            $this->depositLicenseLogRepository->add($depositLicenseLog);
255
256
            /** @var Notifier $notifier */
257
            $notifier = $this->objectManager->get(Notifier::class);
258
            $notifier->sendDepositLicenseNotification($newDocument);
259
        }
260
261
        // Add or update files
262
        $newFiles = $newDocumentForm->getNewFiles();
263
264
        if (is_array($newFiles)) {
0 ignored issues
show
introduced by
The condition is_array($newFiles) is always true.
Loading history...
265
            foreach ($newFiles as $newFile) {
266
267
                if ($newFile->getUID()) {
268
                    $this->fileRepository->update($newFile);
269
                } else {
270
                    $newFile->setDocument($newDocument);
271
                    $this->fileRepository->add($newFile);
272
                    $newDocument->addFile($newFile);
273
                    $this->documentRepository->update($newDocument);
274
                }
275
            }
276
        }
277
        $this->persistenceManager->persistAll();
278
279
        // index the document
280
        $this->signalSlotDispatcher->dispatch(AbstractController::class, 'indexDocument', [$newDocument]);
281
282
    }
283
284
    public function initializeEditAction()
285
    {
286
        $requestArguments = $this->request->getArguments();
287
288
        if (array_key_exists('document', $requestArguments)) {
289
290
            $document = $this->documentManager->read(
291
                $this->request->getArgument('document'),
292
                $this->security->getUser()->getUID()
293
            );
294
295
            if ($document) {
296
                $mapper = $this->objectManager->get(DocumentMapper::class);
297
                $documentForm = $mapper->getDocumentForm($document);
298
            }
299
300
        } elseif (array_key_exists('documentForm', $requestArguments)) {
301
            $documentForm = $this->request->getArgument('documentForm');
302
        }
303
304
        $requestArguments['documentForm'] = $documentForm;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $documentForm does not seem to be defined for all execution paths leading up to this point.
Loading history...
305
        $this->request->setArguments($requestArguments);
306
    }
307
308
    /**
309
     * action edit
310
     *
311
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
312
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("documentForm")
313
     * @return void
314
     */
315
    public function editAction(DocumentForm $documentForm)
316
    {
317
        $this->view->assign('documentForm', $documentForm);
318
319
        if (!empty($this->security->getUserAccessToGroups())) {
320
            $this->view->assign('currentUserAccessToGroup', $this->security->getUserAccessToGroups());
321
        }
322
323
        if ($this->fisDataService->getPersonData($this->security->getFisPersId())) {
324
            $this->view->assign('fisPersId', $this->security->getFisPersId());
325
        }
326
    }
327
328
    public function initializeUpdateAction()
329
    {
330
        $requestArguments = $this->request->getArguments();
331
332
        if ($this->request->hasArgument('documentData')) {
333
            $documentData = $this->request->getArgument('documentData');
334
335
            $formDataReader = $this->objectManager->get(FormDataReader::class);
336
            $formDataReader->setFormData($documentData);
337
            $docForm = $formDataReader->getDocumentForm();
338
339
            $requestArguments['documentForm'] = $docForm;
340
341
            $docTypeUid = $documentData['type'];
342
            $documentType = $this->documentTypeRepository->findByUid($docTypeUid);
343
            $virtualType = $documentType->getVirtualType();
344
345
            if (!$formDataReader->uploadError() || $virtualType === true) {
346
                $this->request->setArguments($requestArguments);
347
            } else {
348
                $t = $docForm->getNewFileNames();
349
                $this->redirect('list', 'Document', null, array('message' => 'UPLOAD_MAX_FILESIZE_ERROR', 'errorFiles' => $t));
350
            }
351
        } else {
352
            $this->redirectToList("UPLOAD_POST_SIZE_ERROR");
353
        }
354
    }
355
356
    /**
357
     * action update
358
     *
359
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
360
     * @return void
361
     */
362
    public function updateAction(DocumentForm $documentForm)
363
    {
364
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
365
366
        /* @var $updateDocument \EWW\Dpf\Domain\Model\Document */
367
        $updateDocument = $documentMapper->getDocument($documentForm);
368
369
        // xml data fields are limited to 64 KB
370
        if (strlen($updateDocument->getXmlData()) >= Document::XML_DATA_SIZE_LIMIT) {
371
            throw new \EWW\Dpf\Exceptions\DocumentMaxSizeErrorException("Maximum document size exceeded.");
372
        }
373
374
        // add document to local es index
375
        $elasticsearchMapper = $this->objectManager->get(ElasticsearchMapper::class);
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\ElasticsearchMapper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
376
        $json                = $elasticsearchMapper->getElasticsearchJson($updateDocument);
377
378
        $elasticsearchRepository = $this->objectManager->get(ElasticsearchRepository::class);
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\ElasticsearchRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
379
        // send document to index
380
        $elasticsearchRepository->add($updateDocument, $json);
381
382
        $updateDocument->setChanged(true);
383
        $this->documentRepository->update($updateDocument);
384
385
386
        // Delete files
387
        foreach ($documentForm->getDeletedFiles() as $deleteFile) {
388
            $deleteFile->setStatus(File::STATUS_DELETED);
389
            $this->fileRepository->update($deleteFile);
390
        }
391
392
        // Add or update files
393
        foreach ($documentForm->getNewFiles() as $newFile) {
394
395
            if ($newFile->getUID()) {
396
                $this->fileRepository->update($newFile);
397
            } else {
398
                $updateDocument->addFile($newFile);
399
            }
400
401
        }
402
403
        // index the document
404
        $this->signalSlotDispatcher->dispatch(AbstractController::class, 'indexDocument', [$updateDocument]);
405
    }
406
407
    /**
408
     * action cancel
409
     *
410
     * @return void
411
     */
412
    public function cancelAction()
413
    {
414
        $this->redirectToList();
415
    }
416
417
    protected function redirectAfterUpdate()
418
    {
419
        $this->redirect('list');
420
    }
421
422
    protected function redirectToList($message = null)
0 ignored issues
show
Unused Code introduced by
The parameter $message is not used and could be removed. ( Ignorable by Annotation )

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

422
    protected function redirectToList(/** @scrutinizer ignore-unused */ $message = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
423
    {
424
        $this->redirect('list');
425
    }
426
427
}
428