Completed
Push — master ( a6ded9...3aafe2 )
by Morris
14s
created

PublicFileHandlingController::load()   C

Complexity

Conditions 13
Paths 17

Size

Total Lines 62
Code Lines 39

Duplication

Lines 3
Ratio 4.84 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 3
loc 62
rs 6.1884
cc 13
eloc 39
nc 17
nop 1

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
 * @copyright 2017, Roeland Jago Douma <[email protected]>
4
 *
5
 * @author Roeland Jago Douma <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License as
11
 * published by the Free Software Foundation, either version 3 of the
12
 * License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
namespace OCA\FilesTextEditor\Controller;
24
25
use OCP\AppFramework\Controller;
26
use OCP\AppFramework\Http;
27
use OCP\AppFramework\Http\DataResponse;
28
use OCP\Files\Folder;
29
use OCP\Files\NotFoundException;
30
use OCP\IL10N;
31
use OCP\IRequest;
32
use OCP\ISession;
33
use OCP\Share\Exceptions\ShareNotFound;
34
use OCP\Share\IManager as ShareManager;
35
36
class PublicFileHandlingController extends Controller{
37
38
	/** @var IL10N */
39
	private $l;
40
41
	/** @var ShareManager */
42
	private $shareManager;
43
44
	/** @var ISession */
45
	private $session;
46
47
	/**
48
	 *
49
	 * @param string $AppName
50
	 * @param IRequest $request
51
	 * @param IL10N $l10n
52
	 * @param ShareManager $shareManager
53
	 * @param ISession $session
54
	 */
55
	public function __construct($AppName,
56
								IRequest $request,
57
								IL10N $l10n,
58
								ShareManager $shareManager,
59
								ISession $session) {
60
		parent::__construct($AppName, $request);
61
		$this->l = $l10n;
62
		$this->shareManager = $shareManager;
63
		$this->session = $session;
64
	}
65
66
	/**
67
	 * load text file
68
	 *
69
	 * @NoAdminRequired
70
	 * @PublicPage
71
	 * @NoCSRFRequired
72
	 *
73
	 * @param string $token
74
	 * @return DataResponse
75
	 */
76
	public function load($token) {
77
		try {
78
			$share = $this->shareManager->getShareByToken($token);
79
		} catch (ShareNotFound $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Share\Exceptions\ShareNotFound 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...
80
			return new DataResponse(['message' => $this->l->t('Share not found'), Http::STATUS_NOT_FOUND]);
81
		}
82
83
		if ($share->getPassword() !== null &&
84
			(!$this->session->exists('public_link_authenticated')
85
			|| $this->session->get('public_link_authenticated') !== (string)$share->getId())) {
86
			return new DataResponse(['message' => $this->l->t('You are not authorized to open this share'), Http::STATUS_BAD_REQUEST]);
87
		}
88
89
		try {
90
			$node = $share->getNode();
91
		} catch (NotFoundException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\NotFoundException 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...
92
			return new DataResponse(['message' => $this->l->t('Share not found'), Http::STATUS_NOT_FOUND]);
93
		}
94
95
		if ($node 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...
96
			return new DataResponse(['message' => $this->l->t('You can not open a folder')], Http::STATUS_BAD_REQUEST);
97
		}
98
99
		$range = $this->request->getHeader('Range');
100
		if ($range !== '') {
101
			$matches = [];
102 View Code Duplication
			if (preg_match('/bytes=0-(\d+)$/', $range, $matches) === 0) {
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...
103
				return new DataResponse(['message' => $this->l->t('Invalid range request')], Http::STATUS_REQUEST_RANGE_NOT_SATISFIABLE);
104
			}
105
			$range = (int)$matches[1];
106
		} else {
107
			$range = -1;
108
		}
109
110
		// default of 4MB
111
		$maxSize = 4194304;
112
		if ($node->getSize() > $maxSize) {
113
			return new DataResponse(['message' => $this->l->t('This file is too big to be opened. Please download the file instead.')], Http::STATUS_BAD_REQUEST);
114
		}
115
116
		$fileContents = $node->getContent();
117
		if ($fileContents !== false) {
118
			$encoding = mb_detect_encoding($fileContents . 'a', 'UTF-8, WINDOWS-1252, ISO-8859-15, ISO-8859-1, ASCII', true);
119
			if ($encoding === '') {
120
				// set default encoding if it couldn't be detected
121
				$encoding = 'ISO-8859-15';
122
			}
123
			$fileContents = iconv($encoding, 'UTF-8', $fileContents);
124
125
			if ($range !== -1) {
126
				$fileContents = mb_substr($fileContents, 0, $range);
127
			}
128
129
			return new Http\DataDisplayResponse(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \OCP\AppFrame...in; charset="utf-8"')); (OCP\AppFramework\Http\DataDisplayResponse) is incompatible with the return type documented by OCA\FilesTextEditor\Cont...andlingController::load of type OCP\AppFramework\Http\DataResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
130
				$fileContents,
131
				Http::STATUS_OK,
132
				['Content-Type' => 'text/plain; charset="utf-8"']
133
			);
134
		}
135
136
		return new DataResponse(['message' => $this->l->t('Cannot read the file.')], Http::STATUS_BAD_REQUEST);
137
	}
138
}
139