Completed
Push — master ( f94cea...cfc523 )
by Morris
12s
created

FileHandlingController::load()   C

Complexity

Conditions 10
Paths 66

Size

Total Lines 57
Code Lines 40

Duplication

Lines 6
Ratio 10.53 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
dl 6
loc 57
ccs 0
cts 50
cp 0
rs 6.7123
c 0
b 0
f 0
cc 10
eloc 40
nc 66
nop 2
crap 110

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
/**
3
 * @author Björn Schießle <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2015, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
23
namespace OCA\FilesTextEditor\Controller;
24
25
26
use OC\HintException;
27
use OCP\AppFramework\Controller;
28
use OCP\AppFramework\Http;
29
use OCP\AppFramework\Http\DataResponse;
30
use OCP\Files\File;
31
use OCP\Files\Folder;
32
use OCP\Files\ForbiddenException;
33
use OCP\IL10N;
34
use OCP\ILogger;
35
use OCP\IRequest;
36
use OCP\Lock\LockedException;
37
38
class FileHandlingController extends Controller{
39
40
	/** @var IL10N */
41
	private $l;
42
43
	/** @var ILogger */
44
	private $logger;
45
46
	/** @var Folder */
47
	private $userFolder;
48
49
	/**
50
	 * @NoAdminRequired
51
	 *
52
	 * @param string $AppName
53
	 * @param IRequest $request
54
	 * @param IL10N $l10n
55
	 * @param ILogger $logger
56
	 * @param Folder $userFolder
57
	 */
58
	public function __construct($AppName,
59
								IRequest $request,
60
								IL10N $l10n,
61
								ILogger $logger,
62
								Folder $userFolder) {
63
		parent::__construct($AppName, $request);
64
		$this->l = $l10n;
65
		$this->logger = $logger;
66
		$this->userFolder = $userFolder;
67
	}
68
69
	/**
70
	 * load text file
71
	 *
72
	 * @NoAdminRequired
73
	 *
74
	 * @param string $dir
75
	 * @param string $filename
76
	 * @return DataResponse
77
	 */
78
	public function load($dir, $filename) {
79
		try {
80
			if (!empty($filename)) {
81
				$path = $dir . '/' . $filename;
82
83
				/** @var File $file */
84
				$file = $this->userFolder->get($path);
85
86 View Code Duplication
				if ($file instanceof Folder) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Folder does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
87
					return new DataResponse(['message' => $this->l->t('You can not open a folder')], Http::STATUS_BAD_REQUEST);
88
				}
89
90
				// default of 4MB
91
				$maxSize = 4194304;
92 View Code Duplication
				if ($file->getSize() > $maxSize) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
93
					return new DataResponse(['message' => (string)$this->l->t('This file is too big to be opened. Please download the file instead.')], Http::STATUS_BAD_REQUEST);
94
				}
95
				$fileContents = $file->getContent();
96
				if ($fileContents !== false) {
97
					$writable = $file->isUpdateable();
98
					$mime = $file->getMimeType();
99
					$mTime = $file->getMTime();
100
					$encoding = mb_detect_encoding($fileContents . 'a', 'UTF-8, WINDOWS-1252, ISO-8859-15, ISO-8859-1, ASCII', true);
101
					if ($encoding === '') {
102
						// set default encoding if it couldn't be detected
103
						$encoding = 'ISO-8859-15';
104
					}
105
					$fileContents = iconv($encoding, 'UTF-8', $fileContents);
106
					return new DataResponse(
107
						[
108
							'filecontents' => $fileContents,
109
							'writeable' => $writable,
110
							'mime' => $mime,
111
							'mtime' => $mTime
112
						],
113
						Http::STATUS_OK
114
					);
115
				} else {
116
					return new DataResponse(['message' => (string)$this->l->t('Cannot read the file.')], Http::STATUS_BAD_REQUEST);
117
				}
118
			} else {
119
				return new DataResponse(['message' => (string)$this->l->t('Invalid file path supplied.')], Http::STATUS_BAD_REQUEST);
120
			}
121
122
		} catch (LockedException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Lock\LockedException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
123
			$message = (string) $this->l->t('The file is locked.');
124
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
125
		} catch (ForbiddenException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\ForbiddenException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
126
			return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
127
		} catch (HintException $e) {
0 ignored issues
show
Bug introduced by
The class OC\HintException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
128
			$message = (string)$e->getHint();
129
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
130
		} catch (\Exception $e) {
131
			$message = (string)$this->l->t('An internal server error occurred.');
132
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
133
		}
134
	}
135
136
	/**
137
	 * save text file
138
	 *
139
	 * @NoAdminRequired
140
	 *
141
	 * @param string $path
142
	 * @param string $filecontents
143
	 * @param integer $mtime
144
	 * @return DataResponse
145
	 */
146
	public function save($path, $filecontents, $mtime) {
147
		try {
148
			if($path !== '' && (is_int($mtime) && $mtime > 0)) {
149
150
				/** @var File $file */
151
				$file = $this->userFolder->get($path);
152
153 View Code Duplication
				if ($file instanceof Folder) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Folder does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
					return new DataResponse(['message' => $this->l->t('You can not write to a folder')], Http::STATUS_BAD_REQUEST);
155
				}
156
157
				// Get file mtime
158
				$filemtime = $file->getMTime();
159
				if($mtime !== $filemtime) {
160
					// Then the file has changed since opening
161
					$this->logger->error('File: ' . $path . ' modified since opening.',
162
						['app' => 'files_texteditor']);
163
					return new DataResponse(
164
						['message' => $this->l->t('Cannot save file as it has been modified since opening')],
165
						Http::STATUS_BAD_REQUEST);
166
				} else {
167
					// File same as when opened, save file
168
					if($file->isUpdateable()) {
169
						$filecontents = iconv(mb_detect_encoding($filecontents), 'UTF-8', $filecontents);
170
						try {
171
							$file->putContent($filecontents);
172
						} catch (LockedException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Lock\LockedException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
173
							$message = (string) $this->l->t('The file is locked.');
174
							return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
175
						} catch (ForbiddenException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\ForbiddenException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
176
							return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
177
						}
178
						// Clear statcache
179
						clearstatcache();
180
						// Get new mtime
181
						$newmtime = $file->getMTime();
182
						$newsize = $file->getSize();
183
						return new DataResponse(['mtime' => $newmtime, 'size' => $newsize], Http::STATUS_OK);
184 View Code Duplication
					} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185
						// Not writeable!
186
						$this->logger->error('User does not have permission to write to file: ' . $path,
187
							['app' => 'files_texteditor']);
188
						return new DataResponse([ 'message' => $this->l->t('Insufficient permissions')],
189
							Http::STATUS_BAD_REQUEST);
190
					}
191
				}
192
			} else if ($path === '') {
193
				$this->logger->error('No file path supplied');
194
				return new DataResponse(['message' => $this->l->t('File path not supplied')], Http::STATUS_BAD_REQUEST);
195 View Code Duplication
			} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
				$this->logger->error('No file mtime supplied', ['app' => 'files_texteditor']);
197
				return new DataResponse(['message' => $this->l->t('File mtime not supplied')], Http::STATUS_BAD_REQUEST);
198
			}
199
200
		} catch (HintException $e) {
0 ignored issues
show
Bug introduced by
The class OC\HintException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
201
			$message = (string)$e->getHint();
202
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
203
		} catch (\Exception $e) {
204
			$message = (string)$this->l->t('An internal server error occurred.');
205
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
206
		}
207
	}
208
209
}
210