Passed
Pull Request — master (#166)
by
unknown
21:05
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
                (
280
                    $saveMode == 'saveWorkingCopy' &&
281
                    $this->security->getUser()->getUserRole() !== Security::ROLE_LIBRARIAN
282
                )
283
            ) {
284
                $message = LocalizationUtility::translate(
285
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.accessDenied',
286
                    'dpf',
287
                    array($document->getTitle())
288
                );
289
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
290
                $this->redirect(
291
                    'showDetails', 'Document',
292
                    null, ['document' => $document]
293
                );
294
            }
295
296
            /** @var  \EWW\Dpf\Helper\DocumentMapper $documentMapper */
297
            $documentMapper = $this->objectManager->get(DocumentMapper::class);
298
299
            /** @var \EWW\Dpf\Domain\Model\Document $updateDocument */
300
            $updateDocument = $documentMapper->getDocument($documentForm);
301
302
            $saveWorkingCopy = false;
303
            $workflowTransition = null;
304
305
            // Convert the temporary copy into a local working copy if needed.
306
            if ( $updateDocument->isTemporaryCopy() && $saveMode == 'saveWorkingCopy') {
307
                $saveWorkingCopy = true;
308
                $updateDocument->setTemporary(false);
309
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
310
            } elseif ($updateDocument->isTemporaryCopy() && $saveMode == 'saveAndUpdate') {
311
                $workflowTransition = DocumentWorkflow::TRANSITION_REMOTE_UPDATE;
312
            } elseif (
313
                $this->security->getUser()->getUserRole() === Security::ROLE_LIBRARIAN &&
314
                $updateDocument->getState() === DocumentWorkflow::STATE_REGISTERED_NONE
315
            ) {
316
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
317
            }
318
319
            if (
320
                $this->documentManager->update(
321
                    $updateDocument, $workflowTransition,
322
                    $documentForm->getDeletedFiles(), $documentForm->getNewFiles()
323
                )
324
            ) {
325
326
                $message = LocalizationUtility::translate(
327
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.success',
328
                    'dpf',
329
                    array($updateDocument->getTitle())
330
                );
331
                $this->addFlashMessage($message, '', AbstractMessage::OK);
332
333
                if ($this->security->getUser()->getUserRole() === Security::ROLE_LIBRARIAN) {
334
                    if ($saveWorkingCopy) {
335
                        if(
336
                            $this->bookmarkRepository->addBookmark(
337
                                $this->security->getUser()->getUid(), $updateDocument
338
                            )
339
                        ) {
340
                            $this->addFlashMessage(
341
                                LocalizationUtility::translate("manager.workspace.bookmarkAdded","dpf"), '',
342
                                AbstractMessage::INFO
343
                            );
344
                        }
345
                    } else {
346
                        switch ($document->getState()) {
347
                            case DocumentWorkflow::STATE_POSTPONED_NONE:
348
                            case DocumentWorkflow::STATE_DISCARDED_NONE:
349
                            case DocumentWorkflow::STATE_NONE_INACTIVE:
350
                            case DocumentWorkflow::STATE_NONE_ACTIVE:
351
                            case DocumentWorkflow::STATE_NONE_DELETED:
352
353
                                if (
354
                                    $this->bookmarkRepository->removeBookmark(
355
                                        $updateDocument,
356
                                        $this->security->getUser()->getUid()
357
                                    )
358
                                ) {
359
                                    $this->addFlashMessage(
360
                                        LocalizationUtility::translate("manager.workspace.bookmarkRemoved.singular","dpf"), '',
361
                                        AbstractMessage::INFO
362
                                    );
363
                                }
364
365
                                $this->redirectToDocumentList();
366
367
                                break;
368
                        }
369
                    }
370
                }
371
372
            } else {
373
                $message = LocalizationUtility::translate(
374
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
375
                    'dpf',
376
                    array($updateDocument->getTitle())
377
                );
378
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
379
            }
380
381
            if ($workflowTransition && $workflowTransition === DocumentWorkflow::TRANSITION_REMOTE_UPDATE) {
382
                $this->redirectToDocumentList();
383
            } else {
384
                $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
385
            }
386
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
387
            // A redirect always throws this exception, but in this case, however,
388
            // redirection is desired and should not lead to an exception handling
389
        } catch (\Exception $exception) {
390
391
            $severity = AbstractMessage::ERROR;
392
393
            if ($exception instanceof DPFExceptionInterface) {
394
                $key = $exception->messageLanguageKey();
395
            } else {
396
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
397
            }
398
399
            $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...
400
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
401
                'dpf',
402
                array($updateDocument->getTitle())
403
            );
404
405
            $exceptionMsg[] = LocalizationUtility::translate($key, 'dpf');
406
407
            $this->addFlashMessage(implode(" ", $exceptionMsg), '', $severity,true);
408
            $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
409
        }
410
    }
411
412
    public function createAction(\EWW\Dpf\Domain\Model\DocumentForm $newDocumentForm)
413
    {
414
        /** @var \EWW\Dpf\Helper\DocumentMapper $documentMapper */
415
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
416
417
        /** @var \EWW\Dpf\Domain\Model\Document $document */
418
        $document = $documentMapper->getDocument($newDocumentForm);
419
420
        if (!$this->authorizationChecker->isGranted(DocumentVoter::CREATE, $document)) {
421
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.accessDenied';
422
            $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...
423
            $message = LocalizationUtility::translate($key, 'dpf', $args);
424
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
425
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
426
            return FALSE;
427
        }
428
429
        try {
430
            parent::createAction($newDocumentForm);
431
432
            $severity = AbstractMessage::OK;
433
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.ok';
434
            $message = LocalizationUtility::translate($key, 'dpf');
435
            $this->addFlashMessage(
436
                $message,
437
                '',
438
                $severity,
439
                true
440
            );
441
442
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
443
            // A redirect always throws this exception, but in this case, however,
444
            // redirection is desired and should not lead to an exception handling
445
        } catch (\Exception $exception) {
446
447
            $severity = AbstractMessage::ERROR;
448
449
            if ($exception instanceof DPFExceptionInterface) {
450
                $key = $exception->messageLanguageKey();
451
            } else {
452
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
453
            }
454
455
            $message[] = LocalizationUtility::translate($key, 'dpf');
456
457
            $this->addFlashMessage(
458
                implode(" ", $message),
459
                '',
460
                $severity,
461
                true
462
            );
463
        }
464
465
        $this->redirect('listWorkspace', 'Workspace');
466
    }
467
468
469
    /**
470
     * action cancel edit
471
     *
472
     * @param integer $documentUid
473
     * @param bool $documentList
474
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
475
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
476
     *
477
     * @return void
478
     */
479
    public function cancelEditAction($documentUid = 0, $documentList = false)
480
    {
481
        if ($documentList) {
482
            $this->redirectToDocumentList();
483
        }
484
485
        if ($documentUid) {
486
            /** @var $document \EWW\Dpf\Domain\Model\Document */
487
            $document = $this->documentRepository->findByUid($documentUid);
488
489
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
490
        }
491
    }
492
493
    public function initializeAction()
494
    {
495
        $this->authorizationChecker->denyAccessUnlessLoggedIn();
496
497
        parent::initializeAction();
498
499
    }
500
501
    /**
502
     * Redirect to the current document list.
503
     *
504
     * @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...
505
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
506
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
507
     */
508
    protected function redirectToDocumentList($message = null)
509
    {
510
        list($action, $controller, $redirectUri) = $this->session->getListAction();
511
512
        if ($redirectUri) {
513
            $this->redirectToUri($redirectUri);
514
        } else {
515
            $this->redirect($action, $controller, null, array('message' => $message));;
516
        }
517
    }
518
519
520
}
521