-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathRestrictedCodeSniff.php
109 lines (94 loc) · 2.59 KB
/
RestrictedCodeSniff.php
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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento2\Sniffs\Legacy;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Common;
/**
* Tests to find usage of restricted code
*/
class RestrictedCodeSniff implements Sniff
{
private const ERROR_MESSAGE = "Class '%s' is restricted in %s. Suggested replacement: %s";
/**
* List of fixtures that contain restricted classes and should not be tested
*
* @var array
*/
private $fixtureFiles = [];
/**
* Restricted classes
*
* @var array
*/
private $classes = [];
/**
* RestrictedCodeSniff constructor.
*/
public function __construct()
{
// phpcs:ignore Magento2.Security.IncludeFile.FoundIncludeFile
$this->classes = include __DIR__ . '/_files/restricted_classes.php';
}
/**
* @inheritdoc
*/
public function register()
{
return [
T_STRING,
T_CONSTANT_ENCAPSED_STRING
];
}
/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
// phpcs:ignore Magento2.Functions.DiscouragedFunction
if (array_key_exists(basename($phpcsFile->getFilename()), $this->fixtureFiles)) {
return;
}
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr]['content'];
if (array_key_exists($token, $this->classes)) {
if ($this->isExcluded($token, $phpcsFile)) {
return;
}
$phpcsFile->addError(
self::ERROR_MESSAGE,
$stackPtr,
$this->classes[$token]['warning_code'],
[
$token,
Common::stripBasepath($phpcsFile->getFilename(), $phpcsFile->config->basepath),
$this->classes[$token]['replacement'],
]
);
}
}
/**
* Checks if currently parsed file should be excluded from analysis
*
* @param string $token
* @param File $phpcsFile
*
* @return bool
*/
private function isExcluded(string $token, File $phpcsFile): bool
{
if (in_array($phpcsFile->getFilename(), $this->fixtureFiles)) {
return true;
}
foreach ($this->classes[$token]['exclude'] as $exclude) {
if (strpos($phpcsFile->getFilename(), $exclude) !== false) {
return true;
}
}
return false;
}
}