Skip to content

Commit dcd4bae

Browse files
author
Alex Paliarush
committed
MAGETWO-83266: Prohibit global variables and output buffering with Code Sniffer
1 parent 4ee8196 commit dcd4bae

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
/**
3+
* Copyright © Magento, Inc. All rights reserved.
4+
* See COPYING.txt for license details.
5+
*/
6+
7+
namespace Magento\Sniffs\MagentoModule;
8+
9+
/**
10+
* Sniff prohibiting usage of certain functions in Magento modules.
11+
*/
12+
class ForbiddenFunctionsSniff extends \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\ForbiddenFunctionsSniff
13+
{
14+
public $forbiddenFunctions = ['ob_start' => null];
15+
16+
/**
17+
* @inheritdoc
18+
*/
19+
protected function addError($phpcsFile, $stackPtr, $function, $pattern = null)
20+
{
21+
$data = [$function];
22+
$error = 'The usage of %s() in Magento modules is forbidden';
23+
$type = 'Found';
24+
25+
if ($this->error === true) {
26+
$phpcsFile->addError($error, $stackPtr, $type, $data);
27+
} else {
28+
$phpcsFile->addWarning($error, $stackPtr, $type, $data);
29+
}
30+
}
31+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
/**
3+
* Copyright © Magento, Inc. All rights reserved.
4+
* See COPYING.txt for license details.
5+
*/
6+
7+
namespace Magento\Sniffs\MagentoModule;
8+
9+
use PHP_CodeSniffer\Sniffs\Sniff;
10+
use PHP_CodeSniffer\Files\File;
11+
12+
/**
13+
* Sniff prohibiting usage of global variables in Magento modules.
14+
*/
15+
class GlobalVariablesSniff implements Sniff
16+
{
17+
/**
18+
* @inheritdoc
19+
*/
20+
public function register()
21+
{
22+
return [T_VARIABLE];
23+
}
24+
25+
/**
26+
* @inheritdoc
27+
*/
28+
public function process(File $phpcsFile, $stackPtr)
29+
{
30+
$tokens = $phpcsFile->getTokens();
31+
if (preg_match('/^\$[_A-Z0-9]+$/', $tokens[$stackPtr]['content'])) {
32+
$phpcsFile->addError(
33+
'Usage of global variables in modules is not allowed: ' . $tokens[$stackPtr]['content'],
34+
$stackPtr,
35+
'ERROR'
36+
);
37+
return;
38+
}
39+
}
40+
}

dev/tests/static/framework/Magento/ruleset.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@
1919
<rule ref="Magento.LiteralNamespaces.LiteralNamespaces">
2020
<exclude-pattern>*/_files/*</exclude-pattern>
2121
</rule>
22+
<rule ref="Magento.MagentoModule.ForbiddenFunctions">
23+
<include-pattern>*/(app/code|vendor)/*</include-pattern>
24+
</rule>
25+
<rule ref="Magento.MagentoModule.GlobalVariables">
26+
<include-pattern>*/(app/code|vendor)/*</include-pattern>
27+
</rule>
2228

2329
<rule ref="Generic.Functions.CallTimePassByReference"/>
2430
<rule ref="Generic.PHP.DeprecatedFunctions"/>

0 commit comments

Comments
 (0)