Completed
Push — master ( 450a89...be9ae4 )
by Robin
299:22 queued 287:36
created

Autoloader::setMemoryCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Andreas Fischer <[email protected]>
6
 * @author Georg Ehrke <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 * @author Markus Goetz <[email protected]>
10
 * @author Morris Jobke <[email protected]>
11
 * @author Robin Appelman <[email protected]>
12
 * @author Robin McCorkell <[email protected]>
13
 * @author Roeland Jago Douma <[email protected]>
14
 * @author Thomas Müller <[email protected]>
15
 * @author Vincent Petry <[email protected]>
16
 *
17
 * @license AGPL-3.0
18
 *
19
 * This code is free software: you can redistribute it and/or modify
20
 * it under the terms of the GNU Affero General Public License, version 3,
21
 * as published by the Free Software Foundation.
22
 *
23
 * This program is distributed in the hope that it will be useful,
24
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26
 * GNU Affero General Public License for more details.
27
 *
28
 * You should have received a copy of the GNU Affero General Public License, version 3,
29
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
30
 *
31
 */
32
33
namespace OC;
34
35
use \OCP\AutoloadNotAllowedException;
36
37
class Autoloader {
38
	/** @var bool */
39
	private $useGlobalClassPath = true;
40
	/** @var array */
41
	private $validRoots = [];
42
43
	/**
44
	 * Optional low-latency memory cache for class to path mapping.
45
	 *
46
	 * @var \OC\Memcache\Cache
47
	 */
48
	protected $memoryCache;
49
50
	/**
51
	 * Autoloader constructor.
52
	 *
53
	 * @param string[] $validRoots
54
	 */
55
	public function __construct(array $validRoots) {
56
		foreach ($validRoots as $root) {
57
			$this->validRoots[$root] = true;
58
		}
59
	}
60
61
	/**
62
	 * Add a path to the list of valid php roots for auto loading
63
	 *
64
	 * @param string $root
65
	 */
66
	public function addValidRoot($root) {
67
		$root = stream_resolve_include_path($root);
68
		$this->validRoots[$root] = true;
69
	}
70
71
	/**
72
	 * disable the usage of the global classpath \OC::$CLASSPATH
73
	 */
74
	public function disableGlobalClassPath() {
75
		$this->useGlobalClassPath = false;
76
	}
77
78
	/**
79
	 * enable the usage of the global classpath \OC::$CLASSPATH
80
	 */
81
	public function enableGlobalClassPath() {
82
		$this->useGlobalClassPath = true;
83
	}
84
85
	/**
86
	 * get the possible paths for a class
87
	 *
88
	 * @param string $class
89
	 * @return array|bool an array of possible paths or false if the class is not part of ownCloud
90
	 */
91
	public function findClass($class) {
92
		$class = trim($class, '\\');
93
94
		$paths = array();
95
		if ($this->useGlobalClassPath && array_key_exists($class, \OC::$CLASSPATH)) {
96
			$paths[] = \OC::$CLASSPATH[$class];
97
			/**
98
			 * @TODO: Remove this when necessary
99
			 * Remove "apps/" from inclusion path for smooth migration to multi app dir
100
			 */
101
			if (strpos(\OC::$CLASSPATH[$class], 'apps/') === 0) {
102
				\OCP\Util::writeLog('core', 'include path for class "' . $class . '" starts with "apps/"', \OCP\Util::DEBUG);
103
				$paths[] = str_replace('apps/', '', \OC::$CLASSPATH[$class]);
104
			}
105
		} elseif (strpos($class, 'OC_') === 0) {
106
			$paths[] = \OC::$SERVERROOT . '/lib/private/legacy/' . strtolower(str_replace('_', '/', substr($class, 3)) . '.php');
107
		} elseif (strpos($class, 'OCA\\') === 0) {
108
			list(, $app, $rest) = explode('\\', $class, 3);
109
			$app = strtolower($app);
110
			$appPath = \OC_App::getAppPath($app);
111
			if ($appPath && stream_resolve_include_path($appPath)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $appPath of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
112
				$paths[] = $appPath . '/' . strtolower(str_replace('\\', '/', $rest) . '.php');
113
				// If not found in the root of the app directory, insert '/lib' after app id and try again.
114
				$paths[] = $appPath . '/lib/' . strtolower(str_replace('\\', '/', $rest) . '.php');
115
			}
116
		} elseif ($class === 'Test\\TestCase') {
117
			// This File is considered public API, so we make sure that the class
118
			// can still be loaded, although the PSR-4 paths have not been loaded.
119
			$paths[] = \OC::$SERVERROOT . '/tests/lib/TestCase.php';
120
		}
121
		return $paths;
122
	}
123
124
	/**
125
	 * @param string $fullPath
126
	 * @return bool
127
	 */
128
	protected function isValidPath($fullPath) {
129
		foreach ($this->validRoots as $root => $true) {
130
			if (substr($fullPath, 0, strlen($root) + 1) === $root . '/') {
131
				return true;
132
			}
133
		}
134
		throw new AutoloadNotAllowedException($fullPath);
135
	}
136
137
	/**
138
	 * Load the specified class
139
	 *
140
	 * @param string $class
141
	 * @return bool
142
	 */
143
	public function load($class) {
144
		$pathsToRequire = null;
145
		if ($this->memoryCache) {
146
			$pathsToRequire = $this->memoryCache->get($class);
147
		}
148
149
		if(class_exists($class, false)) {
150
			return false;
151
		}
152
153
		if (!is_array($pathsToRequire)) {
154
			// No cache or cache miss
155
			$pathsToRequire = array();
156
			foreach ($this->findClass($class) as $path) {
0 ignored issues
show
Bug introduced by
The expression $this->findClass($class) of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
157
				$fullPath = stream_resolve_include_path($path);
158
				if ($fullPath && $this->isValidPath($fullPath)) {
159
					$pathsToRequire[] = $fullPath;
160
				}
161
			}
162
163
			if ($this->memoryCache) {
164
				$this->memoryCache->set($class, $pathsToRequire, 60); // cache 60 sec
165
			}
166
		}
167
168
		foreach ($pathsToRequire as $fullPath) {
169
			require_once $fullPath;
170
		}
171
172
		return false;
173
	}
174
175
	/**
176
	 * Sets the optional low-latency cache for class to path mapping.
177
	 *
178
	 * @param \OC\Memcache\Cache $memoryCache Instance of memory cache.
179
	 */
180
	public function setMemoryCache(\OC\Memcache\Cache $memoryCache = null) {
181
		$this->memoryCache = $memoryCache;
182
	}
183
}
184