Passed
Pull Request — master (#166)
by
unknown
14:46 queued 04:32
created

  B

Complexity

Conditions 6
Paths 36

Size

Total Lines 61
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 40
c 0
b 0
f 0
nc 36
nop 1
dl 0
loc 61
rs 8.6577

How to fix   Long Method   

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
            // +++delete+++ $workingCopy->setEditorUid(0);
175
        }
176
177
        if (empty($workingCopy->getFileData())) {
178
            // no files are linked to the document
179
            $hasFilesFlag = false;
180
        }
181
182
        $newDocument = $this->objectManager->get(Document::class);
183
184
        $this->documentRepository->add($newDocument);
185
        $this->persistenceManager->persistAll();
186
187
        /* @var $document \EWW\Dpf\Domain\Model\Document */
188
        $document = $documentMapper->getDocument($documentForm);
189
190
        /* @var $newDocument \EWW\Dpf\Domain\Model\Document */
191
        $newDocument = $newDocument->copy($document);
192
193
        if ($document->getObjectIdentifier()) {
194
            $newDocument->setLinkedUid($document->getObjectIdentifier());
195
        } else {
196
            $newDocument->setLinkedUid($document->getUid());
197
        }
198
199
        $newDocument->setSuggestion(true);
200
        $newDocument->setComment($document->getComment());
201
202
        if ($restore) {
203
            $newDocument->setTransferStatus("RESTORE");
204
        }
205
206
        if (!$hasFilesFlag) {
207
            // Add or update files
208
            foreach ($documentForm->getNewFiles() as $newFile) {
209
                if ($newFile->getUID()) {
210
                    $this->fileRepository->update($newFile);
211
                } else {
212
                    $newFile->setDocument($newDocument);
213
                    $this->fileRepository->add($newFile);
214
                }
215
216
            }
217
        } else {
218
            // remove files for suggest object
219
            $newDocument->setFile($this->objectManager->get(ObjectStorage::class));
220
        }
221
222
223
        try {
224
            $newDocument->setCreator($this->security->getUser()->getUid());
225
            $this->documentRepository->add($newDocument);
226
            $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...
227
            $this->addFlashMessage("Success", '', $severity,false);
228
        } catch (\Throwable $t) {
229
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
230
            $this->addFlashMessage("Failed", '', $severity,false);
231
        }
232
233
        $this->redirectToDocumentList();
234
    }
235
236
237
    public function updateAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm)
238
    {
239
        if ($this->request->getArgument('documentData')['suggestMod']) {
240
            $restore = $this->request->getArgument('documentData')['suggestRestore'];
241
            $this->forward('createSuggestionDocument', null, null, ['documentForm' => $documentForm, 'restore' => $restore]);
242
        }
243
244
        if ($this->request->hasArgument('saveAndUpdate')) {
245
            $saveMode = 'saveAndUpdate';
246
        } elseif ($this->request->hasArgument('saveWorkingCopy')) {
247
            $saveMode = 'saveWorkingCopy';
248
        } else {
249
            $saveMode = null;
250
        }
251
252
        $this->forward(
253
254
            'updateDocument',
255
            NULL,
256
            NULL,
257
                [
258
                    'documentForm' => $documentForm,
259
                    'saveMode' => $saveMode
260
                ]
261
        );
262
    }
263
264
265
    /**
266
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
267
     * @param string $saveMode
268
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
269
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
270
     */
271
    public function updateDocumentAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, $saveMode = null)
272
    {
273
        try {
274
            /** @var \EWW\Dpf\Domain\Model\Document $document */
275
            $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
276
277
            if (
278
                !$this->authorizationChecker->isGranted(DocumentVoter::UPDATE, $document) ||
279
                ($saveMode == 'saveWorkingCopy' && $this->security->getUserRole() !== Security::ROLE_LIBRARIAN)
280
            ) {
281
                $message = LocalizationUtility::translate(
282
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.accessDenied',
283
                    'dpf',
284
                    array($document->getTitle())
285
                );
286
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
287
                $this->redirect(
288
                    'showDetails', 'Document',
289
                    null, ['document' => $document]
290
                );
291
            }
292
293
            /** @var  \EWW\Dpf\Helper\DocumentMapper $documentMapper */
294
            $documentMapper = $this->objectManager->get(DocumentMapper::class);
295
296
            /** @var \EWW\Dpf\Domain\Model\Document $updateDocument */
297
            $updateDocument = $documentMapper->getDocument($documentForm);
298
299
            $saveWorkingCopy = false;
300
            $workflowTransition = null;
301
302
            // Convert the temporary copy into a local working copy if needed.
303
            if ( $updateDocument->isTemporaryCopy() && $saveMode == 'saveWorkingCopy') {
304
                $saveWorkingCopy = true;
305
                $updateDocument->setTemporary(false);
306
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
307
            } elseif ($updateDocument->isTemporaryCopy() && $saveMode == 'saveAndUpdate') {
308
                $workflowTransition = DocumentWorkflow::TRANSITION_REMOTE_UPDATE;
309
            } elseif (
310
                $this->security->getUserRole() === Security::ROLE_LIBRARIAN &&
311
                $updateDocument->getState() === DocumentWorkflow::STATE_REGISTERED_NONE
312
            ) {
313
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
314
            }
315
316
            if (
317
                $this->documentManager->update(
318
                    $updateDocument, $workflowTransition,
319
                    $documentForm->getDeletedFiles(), $documentForm->getNewFiles()
320
                )
321
            ) {
322
323
                $message = LocalizationUtility::translate(
324
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.success',
325
                    'dpf',
326
                    array($updateDocument->getTitle())
327
                );
328
                $this->addFlashMessage($message, '', AbstractMessage::OK);
329
330
                if ($this->security->getUserRole() === Security::ROLE_LIBRARIAN) {
331
                    if ($saveWorkingCopy) {
332
                        if(
333
                            $this->bookmarkRepository->addBookmark(
334
                                $this->security->getUser()->getUid(), $updateDocument
335
                            )
336
                        ) {
337
                            $this->addFlashMessage(
338
                                LocalizationUtility::translate("manager.workspace.bookmarkAdded","dpf"), '',
339
                                AbstractMessage::INFO
340
                            );
341
                        }
342
                    } else {
343
                        switch ($document->getState()) {
344
                            case DocumentWorkflow::STATE_POSTPONED_NONE:
345
                            case DocumentWorkflow::STATE_DISCARDED_NONE:
346
                            case DocumentWorkflow::STATE_NONE_INACTIVE:
347
                            case DocumentWorkflow::STATE_NONE_ACTIVE:
348
                            case DocumentWorkflow::STATE_NONE_DELETED:
349
350
                                if (
351
                                    $this->bookmarkRepository->removeBookmark(
352
                                        $updateDocument,
353
                                        $this->security->getUser()->getUid()
354
                                    )
355
                                ) {
356
                                    $this->addFlashMessage(
357
                                        LocalizationUtility::translate("manager.workspace.bookmarkRemoved.singular","dpf"), '',
358
                                        AbstractMessage::INFO
359
                                    );
360
                                }
361
362
                                $this->redirectToDocumentList();
363
364
                                break;
365
                        }
366
                    }
367
                }
368
369
            } else {
370
                $message = LocalizationUtility::translate(
371
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
372
                    'dpf',
373
                    array($updateDocument->getTitle())
374
                );
375
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
376
            }
377
378
            if ($workflowTransition && $workflowTransition === DocumentWorkflow::TRANSITION_REMOTE_UPDATE) {
379
                $this->redirectToDocumentList();
380
            } else {
381
                $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
382
            }
383
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
384
            // A redirect always throws this exception, but in this case, however,
385
            // redirection is desired and should not lead to an exception handling
386
        } catch (\Exception $exception) {
387
388
            $severity = AbstractMessage::ERROR;
389
390
            if ($exception instanceof DPFExceptionInterface) {
391
                $key = $exception->messageLanguageKey();
392
            } else {
393
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
394
            }
395
396
            $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...
397
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
398
                'dpf',
399
                array($updateDocument->getTitle())
400
            );
401
402
            $exceptionMsg[] = LocalizationUtility::translate($key, 'dpf');
403
404
            $this->addFlashMessage(implode(" ", $exceptionMsg), '', $severity,true);
405
            $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
406
        }
407
    }
408
409
    public function createAction(\EWW\Dpf\Domain\Model\DocumentForm $newDocumentForm)
410
    {
411
        /** @var \EWW\Dpf\Helper\DocumentMapper $documentMapper */
412
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
413
414
        /** @var \EWW\Dpf\Domain\Model\Document $document */
415
        $document = $documentMapper->getDocument($newDocumentForm);
416
417
        if (!$this->authorizationChecker->isGranted(DocumentVoter::CREATE, $document)) {
418
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.accessDenied';
419
            $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...
420
            $message = LocalizationUtility::translate($key, 'dpf', $args);
421
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
422
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
423
            return FALSE;
424
        }
425
426
        try {
427
            parent::createAction($newDocumentForm);
428
429
            $severity = AbstractMessage::OK;
430
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.ok';
431
            $message = LocalizationUtility::translate($key, 'dpf');
432
            $this->addFlashMessage(
433
                $message,
434
                '',
435
                $severity,
436
                true
437
            );
438
439
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
440
            // A redirect always throws this exception, but in this case, however,
441
            // redirection is desired and should not lead to an exception handling
442
        } catch (\Exception $exception) {
443
444
            $severity = AbstractMessage::ERROR;
445
446
            if ($exception instanceof DPFExceptionInterface) {
447
                $key = $exception->messageLanguageKey();
448
            } else {
449
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
450
            }
451
452
            $message[] = LocalizationUtility::translate($key, 'dpf');
453
454
            $this->addFlashMessage(
455
                implode(" ", $message),
456
                '',
457
                $severity,
458
                true
459
            );
460
        }
461
462
        $this->redirect('listWorkspace', 'Workspace');
463
    }
464
465
466
    /**
467
     * action cancel edit
468
     *
469
     * @param integer $documentUid
470
     * @param bool $documentList
471
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
472
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
473
     *
474
     * @return void
475
     */
476
    public function cancelEditAction($documentUid = 0, $documentList = false)
477
    {
478
        if ($documentList) {
479
            $this->redirectToDocumentList();
480
        }
481
482
        if ($documentUid) {
483
            /** @var $document \EWW\Dpf\Domain\Model\Document */
484
            $document = $this->documentRepository->findByUid($documentUid);
485
486
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
487
        }
488
    }
489
490
    public function initializeAction()
491
    {
492
        $this->authorizationChecker->denyAccessUnlessLoggedIn();
493
494
        parent::initializeAction();
495
496
    }
497
498
    /**
499
     * Redirect to the current document list.
500
     *
501
     * @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...
502
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
503
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
504
     */
505
    protected function redirectToDocumentList($message = null)
506
    {
507
        list($action, $controller, $redirectUri) = $this->session->getListAction();
508
509
        if ($redirectUri) {
510
            $this->redirectToUri($redirectUri);
511
        } else {
512
            $this->redirect($action, $controller, null, array('message' => $message));;
513
        }
514
    }
515
516
517
}
518