Passed
Pull Request — master (#155)
by
unknown
09:37
created

DocumentFormBackofficeController::createAction()   A

Complexity

Conditions 5
Paths 11

Size

Total Lines 54
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 33
c 1
b 0
f 0
nc 11
nop 1
dl 0
loc 54
rs 9.0808

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
28
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
29
30
class DocumentFormBackofficeController extends AbstractDocumentFormController
31
{
32
    /**
33
     * documentTransferManager
34
     *
35
     * @var \EWW\Dpf\Services\Transfer\DocumentTransferManager $documentTransferManager
36
     */
37
    protected $documentTransferManager;
38
39
    /**
40
     * fedoraRepository
41
     *
42
     * @var \EWW\Dpf\Services\Transfer\FedoraRepository $fedoraRepository
43
     */
44
    protected $fedoraRepository;
45
46
    /**
47
     * DocumentController constructor.
48
     */
49
    public function __construct()
50
    {
51
        parent::__construct();
52
53
        $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
54
        $this->documentTransferManager = $objectManager->get(DocumentTransferManager::class);
55
        $this->fedoraRepository = $objectManager->get(FedoraRepository::class);
56
        $this->documentTransferManager->setRemoteRepository($this->fedoraRepository);
57
    }
58
59
    public function arrayRecursiveDiff($aArray1, $aArray2) {
60
        $aReturn = array();
61
62
        foreach ($aArray1 as $mKey => $mValue) {
63
            if (array_key_exists($mKey, $aArray2)) {
64
                if (is_array($mValue)) {
65
                    $aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
66
                    if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
67
                } else {
68
                    if ($mValue != $aArray2[$mKey]) {
69
                        $aReturn[$mKey] = $mValue;
70
                    }
71
                }
72
            } else {
73
                $aReturn[$mKey] = $mValue;
74
            }
75
        }
76
        return $aReturn;
77
    }
78
79
80
    /**
81
     * action edit
82
     *
83
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
84
     * @param bool $suggestMod
85
     * @ignorevalidation $documentForm
86
     * @return void
87
     */
88
    public function editAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, bool $suggestMod = false)
89
    {
90
        /** @var \EWW\Dpf\Domain\Model\Document $document */
91
        $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
92
93
        if ($suggestMod) {
94
            $documentVoterAttribute = DocumentVoter::SUGGEST_MODIFICATION;
95
        } else {
96
            $documentVoterAttribute = DocumentVoter::EDIT;
97
        }
98
99
        if (!$this->authorizationChecker->isGranted($documentVoterAttribute, $document)) {
100
101
            if ($document->getOwner() !== $this->security->getUser()->getUid()) {
102
                $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
103
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_edit.accessDenied',
104
                    'dpf',
105
                    array($document->getTitle())
106
                );
107
            } else {
108
                $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
109
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_edit.failureBlocked',
110
                    'dpf',
111
                    array($document->getTitle())
112
                );
113
            }
114
115
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
116
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
117
            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...
118
        }
119
120
        $this->view->assign('document', $document);
121
        $this->view->assign('suggestMod', $suggestMod);
122
        $document->setEditorUid($this->security->getUser()->getUid());
123
        $this->documentRepository->update($document);
124
        $this->persistenceManager->persistAll();
125
        parent::editAction($documentForm);
126
    }
127
128
    /**
129
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
130
     * @param bool $restore
131
     */
132
    public function createSuggestionDocumentAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, $restore = FALSE)
133
    {
134
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
135
136
        $hasFilesFlag = true;
137
138
        $workingCopy = $this->documentRepository->findByUid($documentForm->getDocumentUid());
139
140
        if ($workingCopy->getTemporary()) {
141
            $workingCopy->setTemporary(false);
142
            $workingCopy->setEditorUid(0);
143
        }
144
145
        if (empty($workingCopy->getFileData())) {
146
            // no files are linked to the document
147
            $hasFilesFlag = false;
148
        }
149
150
        $newDocument = $this->objectManager->get(Document::class);
151
152
        $this->documentRepository->add($newDocument);
153
        $this->persistenceManager->persistAll();
154
155
        /* @var $document \EWW\Dpf\Domain\Model\Document */
156
        $document = $documentMapper->getDocument($documentForm);
157
158
        /* @var $newDocument \EWW\Dpf\Domain\Model\Document */
159
        $newDocument = $newDocument->copy($document);
160
161
        if ($document->getObjectIdentifier()) {
162
            $newDocument->setLinkedUid($document->getObjectIdentifier());
163
        } else {
164
            $newDocument->setLinkedUid($document->getUid());
165
        }
166
167
        $newDocument->setSuggestion(true);
168
        $newDocument->setComment($document->getComment());
169
170
        if ($restore) {
171
            $newDocument->setTransferStatus("RESTORE");
172
        }
173
174
        if (!$hasFilesFlag) {
175
            // Add or update files
176
            foreach ($documentForm->getNewFiles() as $newFile) {
177
                if ($newFile->getUID()) {
178
                    $this->fileRepository->update($newFile);
179
                } else {
180
                    $newFile->setDocument($newDocument);
181
                    $this->fileRepository->add($newFile);
182
                }
183
184
            }
185
        } else {
186
            // remove files for suggest object
187
            $newDocument->setFile($this->objectManager->get(ObjectStorage::class));
188
        }
189
190
191
        try {
192
            $newDocument->setOwner($this->security->getUser()->getUid());
193
            $this->documentRepository->add($newDocument);
194
            $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...
195
            $this->addFlashMessage("Success", '', $severity,false);
196
        } catch (\Throwable $t) {
197
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
198
            $this->addFlashMessage("Failed", '', $severity,false);
199
        }
200
201
        $this->redirectToDocumentList();
202
    }
203
204
    public function updateAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm)
205
    {
206
        if ($this->request->getArgument('documentData')['suggestMod']) {
207
            $restore = $this->request->getArgument('documentData')['suggestRestore'];
208
            $this->forward('createSuggestionDocument', null, null, ['documentForm' => $documentForm, 'restore' => $restore]);
209
        }
210
        if ($this->request->hasArgument('saveAndUpdate')) {
211
            $this->forward('updateRemote',NULL, NULL, ['documentForm' => $documentForm]);
212
        } else {
213
            $this->forward(
214
                'updateLocally',
215
                NULL,
216
                NULL,
217
                [
218
                    'documentForm' => $documentForm,
219
                    'workingCopy' => $this->request->hasArgument('saveWorkingCopy')
220
                ]
221
            );
222
223
        }
224
225
    }
226
227
    /**
228
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
229
     * @param bool $workingCopy
230
     * @return bool
231
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
232
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
233
     */
234
    public function updateLocallyAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, $workingCopy)
235
    {
236
        /** @var \EWW\Dpf\Domain\Model\Document $document */
237
        $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
238
239
        if (!$this->authorizationChecker->isGranted(DocumentVoter::UPDATE, $document)) {
240
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
241
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_updateLocally.accessDenied',
242
                'dpf',
243
                array($document->getTitle())
244
            );
245
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
246
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
247
            return FALSE;
248
        }
249
250
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
251
252
        /** @var \EWW\Dpf\Domain\Model\Document $updateDocument */
253
        $updateDocument = $documentMapper->getDocument($documentForm);
254
255
        try {
256
            parent::updateAction($documentForm);
257
258
            if ($updateDocument->getTemporary()) {
259
                if ($workingCopy) {
260
                    $documents = $this->documentRepository->findByObjectIdentifier($updateDocument->getObjectIdentifier());
0 ignored issues
show
Bug introduced by
The method findByObjectIdentifier() does not exist on EWW\Dpf\Domain\Repository\DocumentRepository. 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

260
                    /** @scrutinizer ignore-call */ 
261
                    $documents = $this->documentRepository->findByObjectIdentifier($updateDocument->getObjectIdentifier());
Loading history...
261
                    foreach ($documents as $document) {
262
                        if (!$document->getTemporary() && !$document->isSuggestion()) {
263
                            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
264
                                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_updateLocally.failureCreateWorkingCopy',
265
                                'dpf',
266
                                array($document->getTitle())
267
                            );
268
                            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
269
                            $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
270
                        }
271
                    }
272
                    $updateDocument->setTemporary(false);
273
                }
274
            }
275
276
            if ($this->security->getUserRole() === Security::ROLE_LIBRARIAN &&
277
                $updateDocument->getState() === DocumentWorkflow::STATE_REGISTERED_NONE) {
278
279
                $state = explode(":", $updateDocument->getState());
280
281
                $state[0] = DocumentWorkflow::LOCAL_STATE_IN_PROGRESS;
282
                $updateDocument->setState(implode(":", $state));
283
            }
284
285
            if (!$updateDocument->getTemporary()) {
286
                $updateDocument->setEditorUid(0);
287
            }
288
289
            $this->documentRepository->update($updateDocument);
290
291
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
292
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_updateLocally.success',
293
                'dpf',
294
                array($updateDocument->getTitle())
295
            );
296
            $this->addFlashMessage($message, '', AbstractMessage::OK);
297
            $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
298
299
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
300
            // A redirect always throws this exception, but in this case, however,
301
            // redirection is desired and should not lead to an exception handling
302
        } catch (\Exception $exception) {
303
            $severity = AbstractMessage::ERROR;
304
305
            if ($exception instanceof DPFExceptionInterface) {
306
                $key = $exception->messageLanguageKey();
307
            } else {
308
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
309
            }
310
311
            $message[] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
312
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
313
                'dpf',
314
                array($updateDocument->getTitle())
315
            );
316
317
            $message[] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
318
319
            $this->addFlashMessage(implode(" ", $message), '', $severity,true);
320
            $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
321
        }
322
    }
323
324
325
    public function updateRemoteAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm)
326
    {
327
        /** @var \EWW\Dpf\Domain\Model\Document $document */
328
        $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
329
330
        if (!$this->authorizationChecker->isGranted(DocumentVoter::UPDATE, $document)) {
331
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
332
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.accessDenied',
333
                'dpf',
334
                array($document->getTitle())
335
            );
336
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
337
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
338
            return FALSE;
339
        }
340
341
        try {
342
            $documentMapper = $this->objectManager->get(DocumentMapper::class);
343
344
            /** @var \EWW\Dpf\Domain\Model\Document $updateDocument */
345
            $updateDocument = $documentMapper->getDocument($documentForm);
346
347
            if ($this->documentTransferManager->getLastModDate($updateDocument->getObjectIdentifier()) === $updateDocument->getRemoteLastModDate()) {
348
                parent::updateAction($documentForm);
349
                $this->documentTransferManager->update($updateDocument);
350
351
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.success';
352
                $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf', [$updateDocument->getTitle()]);
353
                $this->addFlashMessage($message, '', AbstractMessage::OK);
354
                $this->redirectToDocumentList();
355
            } else {
356
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failureNewVersion';
357
                $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf', [$updateDocument->getTitle()]);
358
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
359
                $this->redirectToDocumentList();
360
            }
361
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
362
            // A redirect always throws this exception, but in this case, however,
363
            // redirection is desired and should not lead to an exception handling
364
        } catch (\Exception $exception) {
365
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
366
367
            if ($exception instanceof DPFExceptionInterface) {
368
                $key = $exception->messageLanguageKey();
369
            } else {
370
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
371
            }
372
373
            $documentMapper = $this->objectManager->get(\EWW\Dpf\Helper\DocumentMapper::class);
374
            $updateDocument = $documentMapper->getDocument($documentForm);
375
376
            $message[] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
377
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
378
                'dpf',
379
                array($updateDocument->getTitle())
380
            );
381
382
            $message[] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
383
384
            $this->addFlashMessage(implode(" ", $message), '', $severity,true);
385
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
386
        }
387
    }
388
389
390
391
    public function createAction(\EWW\Dpf\Domain\Model\DocumentForm $newDocumentForm)
392
    {
393
        /** @var \EWW\Dpf\Helper\DocumentMapper $documentMapper */
394
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
395
396
        /** @var \EWW\Dpf\Domain\Model\Document $document */
397
        $document = $documentMapper->getDocument($newDocumentForm);
398
399
        if (!$this->authorizationChecker->isGranted(DocumentVoter::CREATE, $document)) {
400
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.accessDenied';
401
            $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...
402
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf', $args);
403
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
404
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
405
            return FALSE;
406
        }
407
408
        try {
409
            parent::createAction($newDocumentForm);
410
411
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::OK;
412
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.ok';
413
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
414
            $this->addFlashMessage(
415
                $message,
416
                '',
417
                $severity,
418
                true
419
            );
420
421
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
422
            // A redirect always throws this exception, but in this case, however,
423
            // redirection is desired and should not lead to an exception handling
424
        } catch (\Exception $exception) {
425
426
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
427
428
            if ($exception instanceof DPFExceptionInterface) {
429
                $key = $exception->messageLanguageKey();
430
            } else {
431
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
432
            }
433
434
            $message[] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
435
436
            $this->addFlashMessage(
437
                implode(" ", $message),
438
                '',
439
                $severity,
440
                true
441
            );
442
        }
443
444
        $this->redirect('list', 'Document');
445
    }
446
447
448
    /**
449
     * action cancel edit
450
     *
451
     * @param integer $documentUid
452
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
453
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
454
     *
455
     * @return void
456
     */
457
    public function cancelEditAction($documentUid = 0)
458
    {
459
        if ($documentUid) {
460
            /* @var $document \EWW\Dpf\Domain\Model\Document */
461
            $document = $this->documentRepository->findByUid($documentUid);
462
463
            if ($document) {
0 ignored issues
show
introduced by
$document is of type EWW\Dpf\Domain\Model\Document, thus it always evaluated to true.
Loading history...
464
                if (!$document->getTemporary() && $document->getEditorUid() === $this->security->getUser()->getUid()) {
465
                    $document->setEditorUid(0);
466
                }
467
                $this->documentRepository->update($document);
468
            }
469
470
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
471
        }
472
473
    }
474
475
    public function initializeAction()
476
    {
477
        $this->authorizationChecker->denyAccessUnlessLoggedIn();
478
479
        parent::initializeAction();
480
481
    }
482
483
    /**
484
     * Redirect to the current document list.
485
     *
486
     * @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...
487
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
488
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
489
     */
490
    protected function redirectToDocumentList($message = null)
491
    {
492
        $redirectAction = $this->getSessionData('redirectToDocumentListAction');
493
        $redirectController = $this->getSessionData('redirectToDocumentListController');
494
        $this->redirect($redirectAction, $redirectController, null, array('message' => $message));
495
    }
496
497
498
}
499