Completed
Push — master ( 3c32f9...42fff5 )
by Paweł
03:24
created

Analyzer::outputReportHeader()   C

Complexity

Conditions 8
Paths 96

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 19
c 1
b 0
f 0
nc 96
nop 0
dl 0
loc 29
ccs 0
cts 21
cp 0
crap 72
rs 5.3846
1
<?php
2
namespace CodeReview;
3
4
class Analyzer {
5
6
	/**
7
	 * @var \CodeReview\Config
8
	 */
9
	protected $options;
10
11
	/**
12
	 * Function names seen as called
13
	 *
14
	 * @var array
15
	 */
16
	protected $calledFunctions = array();
17
18
	/**
19
	 * @var array
20
	 */
21
	protected $stats;
22
23
	/**
24
	 * @var integer
25
	 */
26
	protected $filesAnalyzed;
27
28
	/**
29
	 * @var string
30
	 */
31
	protected $maxVersion;
32
33
	/**
34
	 * Array of basic function names replacements
35
	 *
36
	 * @var array
37
	 */
38
	protected $instantReplacements;
39
40
	/**
41
	 * @var bool
42
	 */
43
	protected $fixProblems;
44
45
	/**
46
	 * @param \CodeReview\Config $options
47
	 */
48
	public function __construct(\CodeReview\Config $options = null) {
49
50
		if ($options === null) {
51
			$options = new \CodeReview\Config();
52
		}
53
		$this->options = $options;
54
55
		$this->maxVersion = $options->getMaxVersion();
56
		$this->fixProblems = $options->isFixProblemsEnabled();
57
	}
58
59
	/**
60
	 * @param string $subPath
61
	 * @throws \CodeReview\IOException
62
	 * @return CodeReviewFileFilterIterator
63
	 */
64
	public function getPhpFilesIterator($subPath = 'engine/') {
65
		$config = \code_review::getConfig();
66
		$path = $config['path'] . $subPath;
67
		if (!file_exists($path)) {
68
			throw new \CodeReview\IOException("Invalid subPath specified. $path does not exists!");
69
		}
70
		$i = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS);
71
		$i = new \RecursiveIteratorIterator($i, \RecursiveIteratorIterator::LEAVES_ONLY);
72
		$i = new \RegexIterator($i, "/.*\.php/");
73
		$i = new \CodeReview\FileFilterIterator($i, $config['path'], $this->options);
0 ignored issues
show
Documentation introduced by
$i is of type object<RegexIterator>, but the function expects a object<CodeReview\Iterator>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
74
		return $i;
75
	}
76
77
	/**
78
	 * @return array
79
	 */
80
	public function analyze() {
81
82
		$options = $this->options;
83
84
		$i = $this->getPhpFilesIterator($options->getSubPath());
85
86
		$fixer = new CodeFixer();
87
		$this->instantReplacements = $fixer->getBasicFunctionRenames($this->maxVersion);
88
89
		$this->stats = array();
90
		$this->filesAnalyzed = 0;
91
92
		$functions = array();
93
		if ($options->isDeprecatedFunctionsTestEnabled()) {
94
			$functions = array_merge($functions, \code_review::getDeprecatedFunctionsList($options->getMaxVersion()));
95
		}
96
		if ($options->isPrivateFunctionsTestEnabled()) {
97
			$functions = array_merge($functions, \code_review::getPrivateFunctionsList());
98
		}
99
100
		foreach ($i as $filePath => $file) {
101
			if ($file instanceof \SplFileInfo) {
102
				$result = $this->processFile($filePath, $functions);
103
				$this->filesAnalyzed++;
104
				if (!empty($result['problems'])) {
105
					$this->stats[$filePath] = $result;
106
				}
107
			}
108
		}
109
		return $this->stats;
110
	}
111
112
	/**
113
	 * @return string
114
	 */
115
	private function outputReportHeader() {
116
117
		$options = $this->options;
118
119
		$result = '';
120
121
		$result .= "Subpath selected <strong>" . $options->getSubPath() . "</strong>\n";
122
		$result .= "Max version: " . $options->getMaxVersion() . "\n";
123
		$result .= "Skipped inactive plugins: " . ($options->isSkipInactivePluginsEnabled() ? 'yes' : 'no') . "\n";
124
		$result .= "Search for deprecated functions usage: " . ($options->isDeprecatedFunctionsTestEnabled() ? 'yes' : 'no') . "\n";
125
		$result .= "Search for private functions usage: " . ($options->isPrivateFunctionsTestEnabled() ? 'yes' : 'no') . "\n";
126
		$result .= "Attempt to fix problems: " . ($options->isFixProblemsEnabled() ? 'yes' : 'no') . "\n";
127
128
		foreach (array('problems', 'fixes') as $type) {
129
			$total = 0;
130
			foreach ($this->stats as $items) {
131
				$total += count($items[$type]);
132
			}
133
			$result .= "Found $total $type in " . count($this->stats) . " files\n";
134
		}
135
136
		if ($this->filesAnalyzed === 0) {
137
			$result .= "*** No files were processed! *** Analysis input parameters did not resolve to any files.\n";
138
		} else {
139
			$result .= "Processed " . $this->filesAnalyzed . " files total\n";
140
		}
141
142
		return $result;
143
	}
144
145
	/**
146
	 * @return string
147
	 */
148
	private function ouptutUnusedFunctionsReport() {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
149
		//prepare unused functions report
150
		$functions = get_defined_functions();
151
		$functions = array_filter($functions['user'], 'strtolower');
152
		$calledFunctions = array_filter($this->calledFunctions, 'strtolower');
153
		$deprecatedFunctions = array_filter(array_keys(\code_review::getDeprecatedFunctionsList($this->maxVersion)), 'strtolower');
154
		$functions = array_diff($functions, $calledFunctions, $deprecatedFunctions);
155
156
		foreach ($functions as $key => $function) {
157
			if (function_exists($function)) {
158
				$reflectionFunction = new ReflectionFunction($function);
159
				if (!$reflectionFunction->isInternal()) {
160
					continue;
161
				}
162
				unset($reflectionFunction);
163
			}
164
			unset($functions[$key]);
165
		}
166
		sort($functions);
167
168
		//unused functions report
169
		$result = "Not called but defined funcions:\n";
170
		$baseLenght = strlen(elgg_get_root_path());
171
		foreach (array_values($functions) as $functionName) {
172
			$reflectionFunction = new \ReflectionFunction($functionName);
173
			$path = substr($reflectionFunction->getFileName(), $baseLenght);
174
			if (strpos($path, 'engine') !== 0) {
175
				continue;
176
			}
177
			$result .= "$functionName \t{$path}:{$reflectionFunction->getStartLine()}\n";
178
		}
179
		return $result;
180
	}
181
182
	/**
183
	 * @return string
184
	 */
185
	public function outputReport() {
186
187
		$result = $this->outputReportHeader();
188
189
		/*
190
		 * Full report
191
		 */
192
		foreach ($this->stats as $filePath => $items) {
193
			$result .= "\nIn file: " . $filePath . "\n";
194
195
			//problems
196
			foreach ($items['problems'] as $row) {
197
				list($data, , $line) = $row;
198
				$result .= "    " . (string)$data . "\n";
199
			}
200
201
			//fixes
202
			foreach ($items['fixes'] as $row) {
203
				list($before, $after, $line) = $row;
204
				$result .= "    Line $line:\tReplacing: '$before' with '$after'\n";
205
			}
206
		}
207
		
208
		$result .= "\n";
209
210
//		$result .= $this->ouptutUnusedFunctionsReport();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
211
212
		$result .= "\n";
213
214
		return $result;
215
	}
216
217
	/**
218
	 * Find function calls and extract
219
	 *
220
	 * @param string $filePath
221
	 * @param array $functions
222
	 * @return array
223
	 */
224
	public function processFile($filePath, $functions) {
225
		$result = array(
226
			'problems' => array(),
227
			'fixes' => array(),
228
		);
229
		$phpTokens = new PhpFileParser($filePath);
230
		$changes = 0;
231
		foreach ($phpTokens as $key => $row) {
232
			// get non trivial tokens
233
			if (is_array($row)) {
234
				list($token, $functionName, $lineNumber) = $row;
235
				$originalFunctionName = $functionName;
236
237
				// prepare normalized version of function name for matching
238
				$functionName = strtolower($functionName);
239
240
				// check for function call
241
				if ($token == T_STRING
242
					&& !$phpTokens->isEqualToToken(T_OBJECT_OPERATOR, $key-1) //not method
243
					&& !$phpTokens->isEqualToToken(T_DOUBLE_COLON, $key-1) //not static method
244
					&& !$phpTokens->isEqualToToken(T_FUNCTION, $key-2) //not definition
245
				) {
246
					// mark function as called
247
					if (function_exists($functionName) && !in_array($functionName, $this->calledFunctions)) {
248
						$this->calledFunctions[] = $functionName;
249
					}
250
					// is it function we're looking for
251
					if (isset($functions[$functionName])) {
252
						$definingFunctionName = $phpTokens->getDefiningFunctionName($key);
253
254
						//we're skipping deprecated calls that are in deprecated function itself
255
						if (!$definingFunctionName || !isset($functions[strtolower($definingFunctionName)])) {
256
							$result['problems'][] = array($functions[$functionName], $originalFunctionName, $lineNumber);
257
						}
258
259
						//do instant replacement
260
						if ($this->fixProblems && isset($this->instantReplacements[$functionName])) {
261
							$phpTokens[$key] = array(T_STRING, $this->instantReplacements[$functionName]);
262
							$result['fixes'][] = array($originalFunctionName, $this->instantReplacements[$functionName], $lineNumber);
263
							$changes++;
264
						}
265
					}
266
				}
267
			}
268
		}
269
		if ($changes) {
270
			try {
271
				$phpTokens->exportPhp($filePath);
272
			} catch (\CodeReview\IOException $e) {
273
				echo '*** Error: ' . $e->getMessage() . " ***\n";
274
			}
275
		}
276
		unset($phpTokens);
277
		return $result;
278
	}
279
}