Passed
Pull Request — master (#166)
by
unknown
10:28 queued 47s
created

updateDocumentAction()   F

Complexity

Conditions 25
Paths 1695

Size

Total Lines 144
Code Lines 89

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
eloc 89
nc 1695
nop 2
dl 0
loc 144
rs 0
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
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\Helper\DocumentMapper;
19
use EWW\Dpf\Exceptions\AccessDeniedExcepion;
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Exceptions\AccessDeniedExcepion 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...
20
use EWW\Dpf\Security\DocumentVoter;
21
use EWW\Dpf\Security\Security;
22
use EWW\Dpf\Exceptions\DPFExceptionInterface;
23
use EWW\Dpf\Domain\Workflow\DocumentWorkflow;
24
use EWW\Dpf\Services\Transfer\DocumentTransferManager;
25
use EWW\Dpf\Services\Transfer\FedoraRepository;
26
use TYPO3\CMS\Core\Messaging\AbstractMessage;
27
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
28
29
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
30
31
class DocumentFormBackofficeController extends AbstractDocumentFormController
32
{
33
    /**
34
     * documentTransferManager
35
     *
36
     * @var \EWW\Dpf\Services\Transfer\DocumentTransferManager $documentTransferManager
37
     */
38
    protected $documentTransferManager;
39
40
    /**
41
     * fedoraRepository
42
     *
43
     * @var \EWW\Dpf\Services\Transfer\FedoraRepository $fedoraRepository
44
     */
45
    protected $fedoraRepository;
46
47
    /**
48
     * editingLockService
49
     *
50
     * @var \EWW\Dpf\Services\Document\EditingLockService
51
     * @inject
52
     */
53
    protected $editingLockService = null;
54
55
    /**
56
     * documentManager
57
     *
58
     * @var \EWW\Dpf\Services\Document\DocumentManager
59
     * @inject
60
     */
61
    protected $documentManager = null;
62
63
    /**
64
     * bookmarkRepository
65
     *
66
     * @var \EWW\Dpf\Domain\Repository\BookmarkRepository
67
     * @inject
68
     */
69
    protected $bookmarkRepository = null;
70
71
    /**
72
     * DocumentController constructor.
73
     */
74
    public function __construct()
75
    {
76
        parent::__construct();
77
78
        $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
79
        $this->documentTransferManager = $objectManager->get(DocumentTransferManager::class);
80
        $this->fedoraRepository = $objectManager->get(FedoraRepository::class);
81
        $this->documentTransferManager->setRemoteRepository($this->fedoraRepository);
82
    }
83
84
    public function arrayRecursiveDiff($aArray1, $aArray2) {
85
        $aReturn = array();
86
87
        foreach ($aArray1 as $mKey => $mValue) {
88
            if (array_key_exists($mKey, $aArray2)) {
89
                if (is_array($mValue)) {
90
                    $aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
91
                    if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
92
                } else {
93
                    if ($mValue != $aArray2[$mKey]) {
94
                        $aReturn[$mKey] = $mValue;
95
                    }
96
                }
97
            } else {
98
                $aReturn[$mKey] = $mValue;
99
            }
100
        }
101
        return $aReturn;
102
    }
103
104
105
    /**
106
     * action edit
107
     *
108
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
109
     * @param bool $suggestMod
110
     * @param bool activeFileTab
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\activeFileTab 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...
111
     * @ignorevalidation $documentForm
112
     * @return void
113
     */
114
    public function editAction(
115
        \EWW\Dpf\Domain\Model\DocumentForm $documentForm, bool $suggestMod = false, $activeFileTab = false
116
    )
117
    {
118
        /** @var \EWW\Dpf\Domain\Model\Document $document */
119
        $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
120
121
        if ($suggestMod) {
122
            $documentVoterAttribute = DocumentVoter::SUGGEST_MODIFICATION;
123
        } else {
124
            $documentVoterAttribute = DocumentVoter::EDIT;
125
        }
126
127
        if (!$this->authorizationChecker->isGranted($documentVoterAttribute, $document)) {
128
129
            if ($document->getCreator() !== $this->security->getUser()->getUid()) {
130
                $message = LocalizationUtility::translate(
131
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_edit.accessDenied',
132
                    'dpf',
133
                    array($document->getTitle())
134
                );
135
            } else {
136
                $message = LocalizationUtility::translate(
137
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_edit.failureBlocked',
138
                    'dpf',
139
                    array($document->getTitle())
140
                );
141
            }
142
143
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
144
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
145
            return FALSE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return FALSE returns the type false which is incompatible with the documented return type void.
Loading history...
146
        }
147
148
        $this->view->assign('document', $document);
149
        $this->view->assign('suggestMod', $suggestMod);
150
151
        $this->editingLockService->lock(
152
            ($document->getObjectIdentifier()? $document->getObjectIdentifier() : $document->getUid()),
153
            $this->security->getUser()->getUid()
154
        );
155
156
        $this->view->assign('activeFileTab', $activeFileTab);
157
        parent::editAction($documentForm);
158
    }
159
160
    /**
161
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
162
     * @param bool $restore
163
     */
164
    public function createSuggestionDocumentAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, $restore = FALSE)
165
    {
166
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
167
168
        $hasFilesFlag = true;
169
170
        $workingCopy = $this->documentRepository->findByUid($documentForm->getDocumentUid());
171
172
        if ($workingCopy->isTemporary()) {
173
            $workingCopy->setTemporary(false);
174
        }
175
176
        if (empty($workingCopy->getFileData())) {
177
            // no files are linked to the document
178
            $hasFilesFlag = false;
179
        }
180
181
        $newDocument = $this->objectManager->get(Document::class);
182
183
        $this->documentRepository->add($newDocument);
184
        $this->persistenceManager->persistAll();
185
186
        /* @var $document \EWW\Dpf\Domain\Model\Document */
187
        $document = $documentMapper->getDocument($documentForm);
188
189
        /* @var $newDocument \EWW\Dpf\Domain\Model\Document */
190
        $newDocument = $newDocument->copy($document);
191
192
        if ($document->getObjectIdentifier()) {
193
            $newDocument->setLinkedUid($document->getObjectIdentifier());
194
        } else {
195
            $newDocument->setLinkedUid($document->getUid());
196
        }
197
198
        $newDocument->setSuggestion(true);
199
        $newDocument->setComment($document->getComment());
200
201
        if ($restore) {
202
            $newDocument->setTransferStatus("RESTORE");
203
        }
204
205
        if (!$hasFilesFlag) {
206
            // Add or update files
207
            foreach ($documentForm->getNewFiles() as $newFile) {
208
                if ($newFile->getUID()) {
209
                    $this->fileRepository->update($newFile);
210
                } else {
211
                    $newFile->setDocument($newDocument);
212
                    $this->fileRepository->add($newFile);
213
                }
214
215
            }
216
        } else {
217
            // remove files for suggest object
218
            $newDocument->setFile($this->objectManager->get(ObjectStorage::class));
219
        }
220
221
222
        try {
223
            $newDocument->setCreator($this->security->getUser()->getUid());
224
            $this->documentRepository->add($newDocument);
225
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::SUCCESS;
0 ignored issues
show
Bug introduced by
The constant TYPO3\CMS\Core\Messaging\AbstractMessage::SUCCESS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
226
            $this->addFlashMessage("Success", '', $severity,false);
227
        } catch (\Throwable $t) {
228
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
229
            $this->addFlashMessage("Failed", '', $severity,false);
230
        }
231
232
        $this->redirectToDocumentList();
233
    }
234
235
236
    public function updateAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm)
237
    {
238
        if ($this->request->getArgument('documentData')['suggestMod']) {
239
            $restore = $this->request->getArgument('documentData')['suggestRestore'];
240
            $this->forward('createSuggestionDocument', null, null, ['documentForm' => $documentForm, 'restore' => $restore]);
241
        }
242
243
        if ($this->request->hasArgument('saveAndUpdate')) {
244
            $saveMode = 'saveAndUpdate';
245
        } elseif ($this->request->hasArgument('saveWorkingCopy')) {
246
            $saveMode = 'saveWorkingCopy';
247
        } else {
248
            $saveMode = null;
249
        }
250
251
        $this->forward(
252
253
            'updateDocument',
254
            NULL,
255
            NULL,
256
                [
257
                    'documentForm' => $documentForm,
258
                    'saveMode' => $saveMode
259
                ]
260
        );
261
    }
262
263
264
    /**
265
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
266
     * @param string $saveMode
267
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
268
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
269
     */
270
    public function updateDocumentAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, $saveMode = null)
271
    {
272
        try {
273
            /** @var \EWW\Dpf\Domain\Model\Document $document */
274
            $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
275
276
            if (
277
                !$this->authorizationChecker->isGranted(DocumentVoter::UPDATE, $document) ||
278
                (
279
                    $saveMode == 'saveWorkingCopy' &&
280
                    $this->security->getUser()->getUserRole() !== Security::ROLE_LIBRARIAN
281
                )
282
            ) {
283
                $message = LocalizationUtility::translate(
284
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.accessDenied',
285
                    'dpf',
286
                    array($document->getTitle())
287
                );
288
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
289
                $this->redirect(
290
                    'showDetails', 'Document',
291
                    null, ['document' => $document]
292
                );
293
            }
294
295
            /** @var  \EWW\Dpf\Helper\DocumentMapper $documentMapper */
296
            $documentMapper = $this->objectManager->get(DocumentMapper::class);
297
298
            /** @var \EWW\Dpf\Domain\Model\Document $updateDocument */
299
            $updateDocument = $documentMapper->getDocument($documentForm);
300
301
            $saveWorkingCopy = false;
302
            $workflowTransition = null;
303
304
            // Convert the temporary copy into a local working copy if needed.
305
            if ( $updateDocument->isTemporaryCopy() && $saveMode == 'saveWorkingCopy') {
306
                $saveWorkingCopy = true;
307
                $updateDocument->setTemporary(false);
308
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
309
            } elseif ($updateDocument->isTemporaryCopy() && $saveMode == 'saveAndUpdate') {
310
                $workflowTransition = DocumentWorkflow::TRANSITION_REMOTE_UPDATE;
311
            } elseif (
312
                $this->security->getUser()->getUserRole() === Security::ROLE_LIBRARIAN &&
313
                $updateDocument->getState() === DocumentWorkflow::STATE_REGISTERED_NONE
314
            ) {
315
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
316
            }
317
318
            if (
319
                $this->documentManager->update(
320
                    $updateDocument, $workflowTransition,
321
                    $documentForm->getDeletedFiles(), $documentForm->getNewFiles()
322
                )
323
            ) {
324
325
                $message = LocalizationUtility::translate(
326
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.success',
327
                    'dpf',
328
                    array($updateDocument->getTitle())
329
                );
330
                $this->addFlashMessage($message, '', AbstractMessage::OK);
331
332
                if ($this->security->getUser()->getUserRole() === Security::ROLE_LIBRARIAN) {
333
                    if ($saveWorkingCopy) {
334
                        if (
335
                            $this->bookmarkRepository->addBookmark(
336
                                $this->security->getUser()->getUid(), $updateDocument
337
                            )
338
                        ) {
339
                            $this->addFlashMessage(
340
                                LocalizationUtility::translate(
341
                                    "manager.workspace.bookmarkAdded", "dpf"
342
                                ),
343
                                '',
344
                                AbstractMessage::INFO
345
                            );
346
                        }
347
                    } else {
348
                        switch ($document->getState()) {
349
                            case DocumentWorkflow::STATE_POSTPONED_NONE:
350
                            case DocumentWorkflow::STATE_DISCARDED_NONE:
351
                            case DocumentWorkflow::STATE_NONE_INACTIVE:
352
                            case DocumentWorkflow::STATE_NONE_ACTIVE:
353
                            case DocumentWorkflow::STATE_NONE_DELETED:
354
355
                                if (
356
                                    $this->bookmarkRepository->removeBookmark(
357
                                        $updateDocument,
358
                                        $this->security->getUser()->getUid()
359
                                    )
360
                                ) {
361
                                    $this->addFlashMessage(
362
                                        LocalizationUtility::translate(
363
                                            "manager.workspace.bookmarkRemoved.singular", "dpf"
364
                                        ),
365
                                        '',
366
                                        AbstractMessage::INFO
367
                                    );
368
                                }
369
370
                                $this->redirectToDocumentList();
371
372
                                break;
373
                        }
374
                    }
375
                }
376
377
            } else {
378
                $message = LocalizationUtility::translate(
379
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
380
                    'dpf',
381
                    array($updateDocument->getTitle())
382
                );
383
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
384
            }
385
386
            if ($workflowTransition && $workflowTransition === DocumentWorkflow::TRANSITION_REMOTE_UPDATE) {
387
                $this->redirectToDocumentList();
388
            } else {
389
                $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
390
            }
391
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
392
            // A redirect always throws this exception, but in this case, however,
393
            // redirection is desired and should not lead to an exception handling
394
        } catch (\Exception $exception) {
395
396
            $severity = AbstractMessage::ERROR;
397
398
            if ($exception instanceof DPFExceptionInterface) {
399
                $key = $exception->messageLanguageKey();
400
            } else {
401
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
402
            }
403
404
            $exceptionMsg[] = LocalizationUtility::translate(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$exceptionMsg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $exceptionMsg = array(); before regardless.
Loading history...
405
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
406
                'dpf',
407
                array($updateDocument->getTitle())
408
            );
409
410
            $exceptionMsg[] = LocalizationUtility::translate($key, 'dpf');
411
412
            $this->addFlashMessage(implode(" ", $exceptionMsg), '', $severity, true);
413
            $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
414
        }
415
    }
416
417
    public function createAction(\EWW\Dpf\Domain\Model\DocumentForm $newDocumentForm)
418
    {
419
        /** @var \EWW\Dpf\Helper\DocumentMapper $documentMapper */
420
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
421
422
        /** @var \EWW\Dpf\Domain\Model\Document $document */
423
        $document = $documentMapper->getDocument($newDocumentForm);
424
425
        if (!$this->authorizationChecker->isGranted(DocumentVoter::CREATE, $document)) {
426
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.accessDenied';
427
            $args[] = $document->getTitle();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $args = array(); before regardless.
Loading history...
428
            $message = LocalizationUtility::translate($key, 'dpf', $args);
429
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
430
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
431
            return FALSE;
432
        }
433
434
        try {
435
            parent::createAction($newDocumentForm);
436
437
            $severity = AbstractMessage::OK;
438
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.ok';
439
            $message = LocalizationUtility::translate($key, 'dpf');
440
            $this->addFlashMessage(
441
                $message,
442
                '',
443
                $severity,
444
                true
445
            );
446
447
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
448
            // A redirect always throws this exception, but in this case, however,
449
            // redirection is desired and should not lead to an exception handling
450
        } catch (\Exception $exception) {
451
452
            $severity = AbstractMessage::ERROR;
453
454
            if ($exception instanceof DPFExceptionInterface) {
455
                $key = $exception->messageLanguageKey();
456
            } else {
457
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
458
            }
459
460
            $message[] = LocalizationUtility::translate($key, 'dpf');
461
462
            $this->addFlashMessage(
463
                implode(" ", $message),
464
                '',
465
                $severity,
466
                true
467
            );
468
        }
469
470
        $this->redirect('listWorkspace', 'Workspace');
471
    }
472
473
474
    /**
475
     * action cancel edit
476
     *
477
     * @param integer $documentUid
478
     * @param bool $documentList
479
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
480
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
481
     *
482
     * @return void
483
     */
484
    public function cancelEditAction($documentUid = 0, $documentList = false)
485
    {
486
        if ($documentList) {
487
            $this->redirectToDocumentList();
488
        }
489
490
        if ($documentUid) {
491
            /** @var $document \EWW\Dpf\Domain\Model\Document */
492
            $document = $this->documentRepository->findByUid($documentUid);
493
494
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
495
        }
496
    }
497
498
    public function initializeAction()
499
    {
500
        $this->authorizationChecker->denyAccessUnlessLoggedIn();
501
502
        parent::initializeAction();
503
504
    }
505
506
    /**
507
     * Redirect to the current document list.
508
     *
509
     * @param null $message
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $message is correct as it would always require null to be passed?
Loading history...
510
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
511
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
512
     */
513
    protected function redirectToDocumentList($message = null)
514
    {
515
        list($action, $controller, $redirectUri) = $this->session->getListAction();
516
517
        if ($redirectUri) {
518
            $this->redirectToUri($redirectUri);
519
        } else {
520
            $this->redirect($action, $controller, null, array('message' => $message));
521
        }
522
    }
523
524
525
}
526