Passed
Push — master ( d5a28b...d12ca0 )
by
unknown
17:01
created

RenameFileController::renderContent()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 67
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 67
rs 9.1563
c 0
b 0
f 0
cc 3
nc 4
nop 0

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
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
namespace TYPO3\CMS\Filelist\Controller\File;
19
20
use Psr\Http\Message\ResponseInterface;
21
use Psr\Http\Message\ServerRequestInterface;
22
use TYPO3\CMS\Backend\Routing\UriBuilder;
23
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
24
use TYPO3\CMS\Backend\Template\ModuleTemplate;
25
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
26
use TYPO3\CMS\Core\Http\HtmlResponse;
27
use TYPO3\CMS\Core\Imaging\Icon;
28
use TYPO3\CMS\Core\Imaging\IconFactory;
29
use TYPO3\CMS\Core\Localization\LanguageService;
30
use TYPO3\CMS\Core\Page\PageRenderer;
31
use TYPO3\CMS\Core\Resource\DuplicationBehavior;
32
use TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException;
33
use TYPO3\CMS\Core\Resource\File;
34
use TYPO3\CMS\Core\Resource\Folder;
35
use TYPO3\CMS\Core\Resource\ResourceFactory;
36
use TYPO3\CMS\Core\Utility\GeneralUtility;
37
use TYPO3\CMS\Fluid\View\StandaloneView;
38
39
/**
40
 * Script Class for the rename-file form.
41
 * @internal This class is a specific Backend controller implementation and is not considered part of the Public TYPO3 API.
42
 */
43
class RenameFileController
44
{
45
    /**
46
     * Target path
47
     *
48
     * @var string
49
     * @internal
50
     */
51
    protected $target;
52
53
    /**
54
     * The file or folder object that should be renamed
55
     *
56
     * @var File|Folder $fileOrFolderObject
57
     */
58
    protected $fileOrFolderObject;
59
60
    /**
61
     * Return URL of list module.
62
     *
63
     * @var string
64
     */
65
    protected $returnUrl;
66
67
    /**
68
     * ModuleTemplate object
69
     *
70
     * @var ModuleTemplate
71
     */
72
    protected $moduleTemplate;
73
74
    protected IconFactory $iconFactory;
75
    protected PageRenderer $pageRenderer;
76
    protected UriBuilder $uriBuilder;
77
    protected ResourceFactory $resourceFactory;
78
    protected ModuleTemplateFactory $moduleTemplateFactory;
79
80
    public function __construct(
81
        IconFactory $iconFactory,
82
        PageRenderer $pageRenderer,
83
        UriBuilder $uriBuilder,
84
        ResourceFactory $resourceFactory,
85
        ModuleTemplateFactory $moduleTemplateFactory
86
    ) {
87
        $this->iconFactory = $iconFactory;
88
        $this->pageRenderer = $pageRenderer;
89
        $this->uriBuilder = $uriBuilder;
90
        $this->resourceFactory = $resourceFactory;
91
        $this->moduleTemplateFactory = $moduleTemplateFactory;
92
    }
93
94
    /**
95
     * Processes the request, currently everything is handled and put together via "renderContent()"
96
     *
97
     * @param ServerRequestInterface $request
98
     * @return ResponseInterface the response with the content
99
     */
100
    public function mainAction(ServerRequestInterface $request): ResponseInterface
101
    {
102
        $this->moduleTemplate = $this->moduleTemplateFactory->create($request);
103
        $this->init($request);
104
        $this->renderContent();
105
        return new HtmlResponse($this->moduleTemplate->renderContent());
106
    }
107
108
    /**
109
     * Initialize
110
     *
111
     * @param ServerRequestInterface $request
112
     * @throws InsufficientFileAccessPermissionsException
113
     */
114
    protected function init(ServerRequestInterface $request): void
115
    {
116
        $parsedBody = $request->getParsedBody();
117
        $queryParams = $request->getQueryParams();
118
119
        // Initialize GPvars:
120
        $this->target = $parsedBody['target'] ?? $queryParams['target'] ?? null;
121
        $this->returnUrl = GeneralUtility::sanitizeLocalUrl($parsedBody['returnUrl'] ?? $queryParams['returnUrl'] ?? '');
122
        // Cleaning and checking target
123
        if ($this->target) {
124
            $this->fileOrFolderObject = $this->resourceFactory->retrieveFileOrFolderObject($this->target);
125
        }
126
        if (!$this->fileOrFolderObject) {
127
            $title = $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang_mod_file_list.xlf:paramError');
128
            $message = $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang_mod_file_list.xlf:targetNoDir');
129
            throw new \RuntimeException($title . ': ' . $message, 1294586844);
130
        }
131
        if ($this->fileOrFolderObject->getStorage()->getUid() === 0) {
132
            throw new InsufficientFileAccessPermissionsException('You are not allowed to access files outside your storages', 1375889840);
133
        }
134
135
        // If a folder should be renamed, AND the returnURL should go to the old directory name, the redirect is forced
136
        // so the redirect will NOT end in an error message
137
        // this case only happens if you select the folder itself in the foldertree and then use the clickmenu to
138
        // rename the folder
139
        if ($this->fileOrFolderObject instanceof Folder) {
140
            $parsedUrl = parse_url($this->returnUrl);
141
            $queryParts = GeneralUtility::explodeUrl2Array(urldecode($parsedUrl['query']));
142
            if ($queryParts['id'] === $this->fileOrFolderObject->getCombinedIdentifier()) {
143
                $this->returnUrl = str_replace(
144
                    urlencode($queryParts['id']),
145
                    urlencode($this->fileOrFolderObject->getStorage()->getRootLevelFolder()->getCombinedIdentifier()),
146
                    $this->returnUrl
147
                );
148
            }
149
        }
150
151
        // building pathInfo for metaInformation
152
        $pathInfo = [
153
            'combined_identifier' => $this->fileOrFolderObject->getCombinedIdentifier(),
154
        ];
155
        $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($pathInfo);
156
157
        // Setting up the context sensitive menu
158
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
159
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Filelist/RenameFile');
160
    }
161
162
    /**
163
     * Render module content
164
     */
165
    protected function renderContent(): void
166
    {
167
        $assigns = [];
168
        $assigns['moduleUrlTceFile'] = (string)$this->uriBuilder->buildUriFromRoute('tce_file');
169
        $assigns['returnUrl'] = $this->returnUrl;
170
171
        if ($this->fileOrFolderObject instanceof Folder) {
172
            $fileIdentifier = $this->fileOrFolderObject->getCombinedIdentifier();
173
            $targetLabel = 'file_rename.php.label.target.folder';
174
        } else {
175
            $fileIdentifier = $this->fileOrFolderObject->getUid();
176
            $targetLabel = 'file_rename.php.label.target.file';
177
            $assigns['conflictMode'] = DuplicationBehavior::cast(DuplicationBehavior::RENAME);
178
            $assigns['destination'] = $this->fileOrFolderObject->getParentFolder()->getCombinedIdentifier();
179
        }
180
181
        $assigns['fileName'] = $this->fileOrFolderObject->getName();
182
        $assigns['fileIdentifier'] = $fileIdentifier;
183
        $assigns['fieldLabel'] = $targetLabel;
184
185
        // Create buttons
186
        $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
187
188
        // csh button
189
        $cshButton = $buttonBar->makeHelpButton()
190
            ->setModuleName('xMOD_csh_corebe')
191
            ->setFieldName('file_rename');
192
        $buttonBar->addButton($cshButton);
193
194
        // back button
195
        if ($this->returnUrl) {
196
            $backButton = $buttonBar->makeLinkButton()
197
                ->setHref($this->returnUrl)
198
                ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.goBack'))
199
                ->setIcon($this->iconFactory->getIcon('actions-close', Icon::SIZE_SMALL));
200
            $buttonBar->addButton($backButton);
201
        }
202
203
        // Save and Close button
204
        $saveAndCloseButton = $buttonBar->makeInputButton()
205
            ->setName('_saveandclose')
206
            ->setValue('1')
207
            ->setShowLabelText(true)
208
            ->setClasses('t3js-submit-file-rename')
209
            ->setForm('RenameFileController')
210
            ->setTitle($this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang.xlf:file_edit.php.saveAndClose'))
211
            ->setIcon($this->iconFactory->getIcon('actions-document-save-close', Icon::SIZE_SMALL));
212
213
        $buttonBar->addButton($saveAndCloseButton, ButtonBar::BUTTON_POSITION_LEFT, 20);
214
215
        $this->pageRenderer->addInlineLanguageLabelArray([
216
            'file_rename.actions.cancel' => $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang.xlf:file_rename.actions.cancel'),
217
            'file_rename.actions.rename' => $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang.xlf:file_rename.actions.rename'),
218
            'file_rename.actions.override' => $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang.xlf:file_rename.actions.override'),
219
            'file_rename.exists.title' => $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang.xlf:file_rename.exists.title'),
220
            'file_rename.exists.description' => $this->getLanguageService()->sL('LLL:EXT:filelist/Resources/Private/Language/locallang.xlf:file_rename.exists.description'),
221
        ]);
222
223
        // Rendering of the output via fluid
224
        $view = GeneralUtility::makeInstance(StandaloneView::class);
225
        $view->setTemplateRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates')]);
226
        $view->setPartialRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials')]);
227
        $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName(
228
            'EXT:filelist/Resources/Private/Templates/File/RenameFile.html'
229
        ));
230
        $view->assignMultiple($assigns);
231
        $this->moduleTemplate->setContent($view->render());
232
    }
233
234
    /**
235
     * @return LanguageService
236
     */
237
    protected function getLanguageService(): LanguageService
238
    {
239
        return $GLOBALS['LANG'];
240
    }
241
}
242