Completed
Pull Request — master (#118)
by Victor
02:55
created

BackgroundScanner::run()   B

Complexity

Conditions 7
Paths 19

Size

Total Lines 66
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 11
Bugs 4 Features 0
Metric Value
c 11
b 4
f 0
dl 0
loc 66
ccs 0
cts 57
cp 0
rs 7.0832
cc 7
eloc 48
nc 19
nop 0
crap 56

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
 * Copyright (c) 2012 Bart Visscher <[email protected]>
4
 * This file is licensed under the Affero General Public License version 3 or
5
 * later.
6
 * See the COPYING-README file.
7
 */
8
9
namespace OCA\Files_Antivirus;
10
11
use OC\Files\Filesystem;
12
use OCP\Files\IRootFolder;
13
use OCP\IUser;
14
use OCP\IL10N;
15
16
use OCA\Files_Antivirus\Item;
17
18
class BackgroundScanner {
19
20
	const BATCH_SIZE = 10;
21
22
	/** @var IRootFolder */
23
	protected $rootFolder;
24
25
	/** @var \OCP\Files\Folder[] */
26
	protected $userFolders;
27
28
	/**
29
	 * @var ScannerFactory
30
	 */
31
	private $scannerFactory;
32
33
	
34
	/**
35
	 * @var IL10N
36
	 */
37
	private $l10n;
38
39
	/** @var string */
40
	protected $currentFilesystemUser;
41
42
	/**
43
	 * A constructor
44
	 *
45
	 * @param IRootFolder $rootFolder
46
	 * @param \OCA\Files_Antivirus\ScannerFactory $scannerFactory
47
	 * @param IL10N $l10n
48
	 */
49
	public function __construct(IRootFolder $rootFolder = null, ScannerFactory $scannerFactory, IL10N $l10n){
50
		$this->rootFolder = $rootFolder;
51
		$this->scannerFactory = $scannerFactory;
52
		$this->l10n = $l10n;
53
	}
54
	
55
	/**
56
	 * Background scanner main job
57
	 * @return null
58
	 */
59
	public function run(){
60
		if (!$this->initFS()) {
0 ignored issues
show
Bug introduced by
The method initFS() does not seem to exist on object<OCA\Files_Antivirus\BackgroundScanner>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
61
			return;
62
		}
63
		// locate files that are not checked yet
64
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory');
65
		try {
66
			$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
67
			$qb->select(['fc.fileid'])
68
				->from('filecache', 'fc')
69
				->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
70
				->innerJoin(
71
					'fc',
72
					'storages',
73
					'ss',
74
					$qb->expr()->andX(
75
						$qb->expr()->eq('fc.storage', 'ss.numeric_id'),
76
						$qb->expr()->orX(
77
							$qb->expr()->like('ss.id', $qb->expr()->literal('local::%')),
78
							$qb->expr()->like('ss.id', $qb->expr()->literal('home::%'))
79
						)
80
					)
81
				)
82
				->where(
83
					$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
84
				)
85
				->andWhere(
86
					$qb->expr()->orX(
87
						$qb->expr()->isNull('fa.fileid'),
88
						$qb->expr()->gt('fc.mtime', 'fa.check_time')
89
					)
90
				)
91
				->andWhere(
92
					$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
93
				)
94
				->andWhere(
95
					$qb->expr()->neq('fc.size', '0')
96
				)
97
				->setMaxResults(self::BATCH_SIZE)
98
			;
99
			$result = $qb->execute();
100
		} catch(\Exception $e) {
101
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
102
			return;
103
		}
104
105
		try {
106
			while ($row = $result->fetch()) {
107
				$owner = $this->getOwner($row['fileid']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $owner is correct as $this->getOwner($row['fileid']) (which targets OCA\Files_Antivirus\BackgroundScanner::getOwner()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
108
				if (!$owner){
109
					continue;
110
				}
111
				$userFolder = $this->getUserFolder($owner);
112
				$nodes = $userFolder->getById($row['fileid']);
0 ignored issues
show
Unused Code introduced by
$nodes is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
113
				if (!is_null($path)) {
114
					$item = new Item($this->l10n, $view, $path, $row['fileid']);
0 ignored issues
show
Bug introduced by
The variable $view does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $path does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
115
					$scanner = $this->scannerFactory->getScanner();
116
					$status = $scanner->scan($item);
117
					$status->dispatch($item, true);
118
				}
119
			}
120
		} catch (\Exception $e){
121
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
122
		}
123
		\OC_Util::tearDownFS();
124
	}
125
126
	protected function getOwner($fileId){
127
		$mountProviderCollection = \OC::$server->getMountProviderCollection();
128
		$mountCache = $mountProviderCollection->getMountCache();
129
		$mounts = $mountCache->getMountsForFileId($fileId);
130
		if (!empty($mounts)) {
131
			$user = $mounts[0]->getUser();
132
			if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser 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...
133
				$this->initFilesystemForUser($user);
134
				$userFolder = $this->getUserFolder($user);
135
				$nodes = $userFolder->getById($fileId);
136
				if (!empty($nodes)) {
137
					$nodesToCheck[] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$nodesToCheck was never initialized. Although not strictly required by PHP, it is generally a good practice to add $nodesToCheck = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
138
						'node' => array_shift($nodes),
139
						'owner' => $user
140
					];
141
				}
142
			}
143
		}
144
	}
145
146
	/**
147
	 * @param \OCP\IUser $user
148
	 * @return \OCP\Files\Folder
149
	 */
150
	protected function getUserFolder(IUser $user) {
151
		if (!isset($this->userFolders[$user->getUID()])) {
152
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
153
			$this->userFolders[$user->getUID()] = $userFolder;
154
		}
155
		return $this->userFolders[$user->getUID()];
156
	}
157
158
	/**
159
	 * @param IUser $user
160
	 */
161
	protected function initFilesystemForUser(IUser $user) {
162
		if ($this->currentFilesystemUser !== $user->getUID()) {
163
			if ($this->currentFilesystemUser !== '') {
164
				Filesystem::tearDown();
165
			}
166
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
167
			$this->userSession->setUser($user);
0 ignored issues
show
Bug introduced by
The property userSession does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
168
			$this->currentFilesystemUser = $user->getUID();
169
		}
170
	}
171
172
	/**
173
	 * @deprecated since  v8.0.0
174
	 */
175
	public static function check(){
176
	}
177
}
178