Completed
Push — master ( cfb74b...9d6537 )
by Thomas
38s queued 10s
created

Autoloader::load()   B

Complexity

Conditions 9
Paths 14

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 14
nop 1
dl 0
loc 31
rs 8.0555
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Andreas Fischer <[email protected]>
4
 * @author Georg Ehrke <[email protected]>
5
 * @author Joas Schilling <[email protected]>
6
 * @author Lukas Reschke <[email protected]>
7
 * @author Markus Goetz <[email protected]>
8
 * @author Morris Jobke <[email protected]>
9
 * @author Robin Appelman <[email protected]>
10
 * @author Robin McCorkell <[email protected]>
11
 * @author Roeland Jago Douma <[email protected]>
12
 * @author Thomas Müller <[email protected]>
13
 * @author Vincent Petry <[email protected]>
14
 *
15
 * @copyright Copyright (c) 2018, ownCloud GmbH
16
 * @license AGPL-3.0
17
 *
18
 * This code is free software: you can redistribute it and/or modify
19
 * it under the terms of the GNU Affero General Public License, version 3,
20
 * as published by the Free Software Foundation.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25
 * GNU Affero General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU Affero General Public License, version 3,
28
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
29
 *
30
 */
31
32
namespace OC;
33
34
use \OCP\AutoloadNotAllowedException;
35
36
class Autoloader {
37
	/** @var array */
38
	private $validRoots = [];
39
40
	/**
41
	 * Optional low-latency memory cache for class to path mapping.
42
	 *
43
	 * @var \OC\Memcache\Cache
44
	 */
45
	protected $memoryCache;
46
47
	/**
48
	 * Autoloader constructor.
49
	 *
50
	 * @param string[] $validRoots
51
	 */
52
	public function __construct(array $validRoots = []) {
53
		foreach ($validRoots as $root) {
54
			$this->validRoots[$root] = true;
55
		}
56
	}
57
58
	/**
59
	 * Add a path to the list of valid php roots for auto loading
60
	 *
61
	 * @param string $root
62
	 */
63
	public function addValidRoot($root) {
64
		$root = \stream_resolve_include_path($root);
65
		$this->validRoots[$root] = true;
66
	}
67
68
	/**
69
	 * get the possible paths for a class
70
	 *
71
	 * @param string $class
72
	 * @return array|bool an array of possible paths or false if the class is not part of ownCloud
73
	 */
74
	public function findClass($class) {
75
		$class = \trim($class, '\\');
76
77
		$paths = [];
78
		if (\strpos($class, 'OCA\\') === 0) {
79
			list(, $app, $rest) = \explode('\\', $class, 3);
80
			$app = \strtolower($app);
81
			$appPath = \OC_App::getAppPath($app);
82
			if ($appPath && \stream_resolve_include_path($appPath)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $appPath of type string|false 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...
83
				$paths[] = $appPath . '/' . \strtolower(\str_replace('\\', '/', $rest) . '.php');
84
				// If not found in the root of the app directory, insert '/lib' after app id and try again.
85
				$paths[] = $appPath . '/lib/' . \strtolower(\str_replace('\\', '/', $rest) . '.php');
86
			}
87
		}
88
		return $paths;
89
	}
90
91
	/**
92
	 * @param string $fullPath
93
	 * @return bool
94
	 */
95
	protected function isValidPath($fullPath) {
96
		foreach ($this->validRoots as $root => $true) {
97
			if (\substr($fullPath, 0, \strlen($root) + 1) === $root . '/') {
98
				return true;
99
			}
100
		}
101
		throw new AutoloadNotAllowedException($fullPath);
102
	}
103
104
	/**
105
	 * Load the specified class
106
	 *
107
	 * @param string $class
108
	 * @return bool
109
	 */
110
	public function load($class) {
111
		$pathsToRequire = null;
112
		if ($this->memoryCache) {
113
			$pathsToRequire = $this->memoryCache->get($class);
114
		}
115
116
		if (\class_exists($class, false)) {
117
			return false;
118
		}
119
120
		if (!\is_array($pathsToRequire)) {
121
			// No cache or cache miss
122
			$pathsToRequire = [];
123
			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...
124
				$fullPath = \stream_resolve_include_path($path);
125
				if ($fullPath && $this->isValidPath($fullPath)) {
126
					$pathsToRequire[] = $fullPath;
127
				}
128
			}
129
130
			if ($this->memoryCache) {
131
				$this->memoryCache->set($class, $pathsToRequire, 60); // cache 60 sec
132
			}
133
		}
134
135
		foreach ($pathsToRequire as $fullPath) {
136
			require_once $fullPath;
137
		}
138
139
		return false;
140
	}
141
142
	/**
143
	 * Sets the optional low-latency cache for class to path mapping.
144
	 *
145
	 * @param \OC\Memcache\Cache $memoryCache Instance of memory cache.
146
	 */
147
	public function setMemoryCache(\OC\Memcache\Cache $memoryCache = null) {
148
		$this->memoryCache = $memoryCache;
149
	}
150
}
151