Skip to content

Commit 6ad1fc9

Browse files
authored
Merge pull request #236 from humanmade/isset-sniff
#142 - Add new Isset sniff
2 parents 6efe4b8 + b9f3cb3 commit 6ad1fc9

File tree

5 files changed

+57
-0
lines changed

5 files changed

+57
-0
lines changed

HM/Sniffs/PHP/IssetSniff.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
namespace HM\Sniffs\PHP;
3+
4+
use PHP_CodeSniffer\Exceptions\RuntimeException;
5+
use PHP_CodeSniffer\Files\File;
6+
use PHP_CodeSniffer\Sniffs\Sniff;
7+
8+
/**
9+
* Sniff to check for isset() usage.
10+
*/
11+
class IssetSniff implements Sniff {
12+
public function register() {
13+
return array( T_ISSET );
14+
}
15+
16+
public function process( File $phpcsFile, $stackPtr ) {
17+
$tokens = $phpcsFile->getTokens();
18+
19+
$open_parenthesis_token = $phpcsFile->findNext( T_OPEN_PARENTHESIS, $stackPtr + 1 );
20+
if ( $open_parenthesis_token === false ) {
21+
throw new RuntimeException( '$stackPtr was not a valid T_ISSET' );
22+
}
23+
24+
$comma_token = $phpcsFile->findNext( T_COMMA, $open_parenthesis_token + 1 );
25+
if ( $comma_token !== false && $comma_token < $tokens[ $open_parenthesis_token ]['parenthesis_closer'] ) {
26+
$phpcsFile->addWarning( 'Only one argument should be used per ISSET call', $stackPtr, 'MultipleArguments' );
27+
}
28+
}
29+
}

tests/FixtureTests.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ public function setUp() {
106106
'HM.Namespaces.NoLeadingSlashOnUse',
107107
'HM.Performance.SlowMetaQuery',
108108
'HM.Performance.SlowOrderBy',
109+
'HM.PHP.Isset',
109110
'HM.Security.EscapeOutput',
110111
'HM.Security.NonceVerification',
111112
'HM.Security.ValidatedSanitizedInput',

tests/fixtures/fail/isset.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
isset( $a, $b );
4+
isset(
5+
$a,
6+
$b
7+
);

tests/fixtures/fail/isset.php.json

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"3": [
3+
{
4+
"source": "HM.PHP.Isset.MultipleArguments",
5+
"type": "warning"
6+
}
7+
],
8+
"4": [
9+
{
10+
"source": "HM.PHP.Isset.MultipleArguments",
11+
"type": "warning"
12+
}
13+
]
14+
}

tests/fixtures/pass/isset.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php
2+
3+
isset( $a );
4+
isset(
5+
$a
6+
);

0 commit comments

Comments
 (0)