1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Php;
use Magento\Framework\App\Utility\Files;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\TestFramework\CodingStandard\Tool\CodeMessDetector;
use Magento\TestFramework\CodingStandard\Tool\CodeSniffer;
use Magento\TestFramework\CodingStandard\Tool\CodeSniffer\Wrapper;
use Magento\TestFramework\CodingStandard\Tool\CopyPasteDetector;
use PHPMD\TextUI\Command;
/**
* Set of tests for static code analysis, e.g. code style, code complexity, copy paste detecting, etc.
*/
class LiveCodeTest extends \PHPUnit\Framework\TestCase
{
/**
* @var string
*/
protected static $reportDir = '';
/**
* @var string
*/
protected static $pathToSource = '';
/**
* Setup basics for all tests
*
* @return void
*/
public static function setUpBeforeClass()
{
self::$pathToSource = BP;
self::$reportDir = self::$pathToSource . '/dev/tests/static/report';
if (!is_dir(self::$reportDir)) {
mkdir(self::$reportDir);
}
}
/**
* Returns base folder for suite scope
*
* @return string
*/
private static function getBaseFilesFolder()
{
return __DIR__;
}
/**
* Returns base directory for whitelisted files
*
* @return string
*/
private static function getChangedFilesBaseDir()
{
return __DIR__ . '/..';
}
/**
* Returns whitelist based on blacklist and git changed files
*
* @param array $fileTypes
* @param string $changedFilesBaseDir
* @param string $baseFilesFolder
* @param string $whitelistFile
* @return array
*/
public static function getWhitelist(
$fileTypes = ['php'],
$changedFilesBaseDir = '',
$baseFilesFolder = '',
$whitelistFile = '/_files/whitelist/common.txt'
) {
$changedFiles = self::getChangedFilesList($changedFilesBaseDir);
if (empty($changedFiles)) {
return [];
}
$globPatternsFolder = ('' !== $baseFilesFolder) ? $baseFilesFolder : self::getBaseFilesFolder();
try {
$directoriesToCheck = Files::init()->readLists($globPatternsFolder . $whitelistFile);
} catch (\Exception $e) {
// no directories matched white list
return [];
}
$targetFiles = self::filterFiles($changedFiles, $fileTypes, $directoriesToCheck);
return $targetFiles;
}
/**
* This method loads list of changed files.
*
* List may be generated by:
* - dev/tests/static/get_github_changes.php utility (allow to generate diffs between branches),
* - CLI command "git diff --name-only > dev/tests/static/testsuite/Magento/Test/_files/changed_files_local.txt",
*
* If no generated changed files list found "git diff" will be used to find not committed changed
* (tests should be invoked from target gir repo).
*
* Note: "static" modifier used for compatibility with legacy implementation of self::getWhitelist method
*
* @param string $changedFilesBaseDir Base dir with previously generated list files
* @return string[] List of changed files
*/
private static function getChangedFilesList($changedFilesBaseDir)
{
return self::getFilesFromListFile(
$changedFilesBaseDir,
'changed_files*',
function () {
// if no list files, probably, this is the dev environment
@exec('git diff --name-only', $changedFiles);
@exec('git diff --cached --name-only', $addedFiles);
$changedFiles = array_unique(array_merge($changedFiles, $addedFiles));
return $changedFiles;
}
);
}
/**
* This method loads list of added files.
*
* @param string $changedFilesBaseDir
* @return string[]
*/
private static function getAddedFilesList($changedFilesBaseDir)
{
return self::getFilesFromListFile(
$changedFilesBaseDir,
'changed_files*.added.*',
function () {
// if no list files, probably, this is the dev environment
@exec('git diff --cached --name-only', $addedFiles);
return $addedFiles;
}
);
}
/**
* Read files from generated lists.
*
* @param string $listsBaseDir
* @param string $listFilePattern
* @param callable $noListCallback
* @return string[]
*/
private static function getFilesFromListFile($listsBaseDir, $listFilePattern, $noListCallback)
{
$filesDefinedInList = [];
$globFilesListPattern = ($listsBaseDir ?: self::getChangedFilesBaseDir())
. '/_files/' . $listFilePattern;
$listFiles = glob($globFilesListPattern);
if (count($listFiles)) {
foreach ($listFiles as $listFile) {
$filesDefinedInList = array_merge(
$filesDefinedInList,
file($listFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
);
}
} else {
$filesDefinedInList = call_user_func($noListCallback);
}
array_walk(
$filesDefinedInList,
function (&$file) {
$file = BP . '/' . $file;
}
);
$filesDefinedInList = array_values(array_unique($filesDefinedInList));
return $filesDefinedInList;
}
/**
* Filter list of files.
*
* File removed from list:
* - if it not exists,
* - if allowed types are specified and file has another type (extension),
* - if allowed directories specified and file not located in one of them.
*
* Note: "static" modifier used for compatibility with legacy implementation of self::getWhitelist method
*
* @param string[] $files List of file paths to filter
* @param string[] $allowedFileTypes List of allowed file extensions (pass empty array to allow all)
* @param string[] $allowedDirectories List of allowed directories (pass empty array to allow all)
* @return string[] Filtered file paths
*/
private static function filterFiles(array $files, array $allowedFileTypes, array $allowedDirectories)
{
if (empty($allowedFileTypes)) {
$fileHasAllowedType = function () {
return true;
};
} else {
$fileHasAllowedType = function ($file) use ($allowedFileTypes) {
return in_array(pathinfo($file, PATHINFO_EXTENSION), $allowedFileTypes);
};
}
if (empty($allowedDirectories)) {
$fileIsInAllowedDirectory = function () {
return true;
};
} else {
$allowedDirectories = array_map('realpath', $allowedDirectories);
usort($allowedDirectories, function ($dir1, $dir2) {
return strlen($dir1) - strlen($dir2);
});
$fileIsInAllowedDirectory = function ($file) use ($allowedDirectories) {
foreach ($allowedDirectories as $directory) {
if (strpos($file, $directory) === 0) {
return true;
}
}
return false;
};
}
$filtered = array_filter(
$files,
function ($file) use ($fileHasAllowedType, $fileIsInAllowedDirectory) {
$file = realpath($file);
if (false === $file) {
return false;
}
return $fileHasAllowedType($file) && $fileIsInAllowedDirectory($file);
}
);
return $filtered;
}
/**
* Retrieves full list of codebase paths without any files/folders filtered out
*
* @return array
*/
private function getFullWhitelist()
{
try {
return Files::init()->readLists(__DIR__ . '/_files/whitelist/common.txt');
} catch (\Exception $e) {
// nothing is whitelisted
return [];
}
}
/**
* Test code quality using phpcs
*/
public function testCodeStyle()
{
$isFullScan = defined('TESTCODESTYLE_IS_FULL_SCAN') && TESTCODESTYLE_IS_FULL_SCAN === '1';
$reportFile = self::$reportDir . '/phpcs_report.txt';
if (!file_exists($reportFile)) {
touch($reportFile);
}
$codeSniffer = new CodeSniffer('Magento', $reportFile, new Wrapper());
$result = $codeSniffer->run($isFullScan ? $this->getFullWhitelist() : self::getWhitelist(['php', 'phtml']));
$report = file_get_contents($reportFile);
$this->assertEquals(
0,
$result,
"PHP Code Sniffer detected {$result} violation(s): " . PHP_EOL . $report
);
}
/**
* Test code quality using phpmd
*/
public function testCodeMess()
{
$reportFile = self::$reportDir . '/phpmd_report.txt';
$codeMessDetector = new CodeMessDetector(realpath(__DIR__ . '/_files/phpmd/ruleset.xml'), $reportFile);
if (!$codeMessDetector->canRun()) {
$this->markTestSkipped('PHP Mess Detector is not available.');
}
$result = $codeMessDetector->run(self::getWhitelist(['php']));
$output = "";
if (file_exists($reportFile)) {
$output = file_get_contents($reportFile);
}
$this->assertEquals(
Command::EXIT_SUCCESS,
$result,
"PHP Code Mess has found error(s):" . PHP_EOL . $output
);
// delete empty reports
if (file_exists($reportFile)) {
unlink($reportFile);
}
}
/**
* Test code quality using phpcpd
*/
public function testCopyPaste()
{
$reportFile = self::$reportDir . '/phpcpd_report.xml';
$copyPasteDetector = new CopyPasteDetector($reportFile);
if (!$copyPasteDetector->canRun()) {
$this->markTestSkipped('PHP Copy/Paste Detector is not available.');
}
$blackList = [];
foreach (glob(__DIR__ . '/_files/phpcpd/blacklist/*.txt') as $list) {
$blackList = array_merge($blackList, file($list, FILE_IGNORE_NEW_LINES));
}
$copyPasteDetector->setBlackList($blackList);
$result = $copyPasteDetector->run([BP]);
$output = "";
if (file_exists($reportFile)) {
$output = file_get_contents($reportFile);
}
$this->assertTrue(
$result,
"PHP Copy/Paste Detector has found error(s):" . PHP_EOL . $output
);
}
/**
* Tests whitelisted files for strict type declarations.
*/
public function testStrictTypes()
{
$changedFiles = self::getAddedFilesList('');
try {
$blackList = Files::init()->readLists(
self::getBaseFilesFolder() . '/_files/blacklist/strict_type.txt'
);
} catch (\Exception $e) {
// nothing matched black list
$blackList = [];
}
$toBeTestedFiles = array_diff(
self::filterFiles($changedFiles, ['php'], []),
$blackList
);
$filesMissingStrictTyping = [];
foreach ($toBeTestedFiles as $fileName) {
$file = file_get_contents($fileName);
if (strstr($file, 'strict_types=1') === false) {
$filesMissingStrictTyping[] = $fileName;
}
}
$this->assertEquals(
0,
count($filesMissingStrictTyping),
"Following files are missing strict type declaration:"
. PHP_EOL
. implode(PHP_EOL, $filesMissingStrictTyping)
);
}
}