Skip to content

Commit 13e5071

Browse files
committed
Added new sniffs
1 parent fae898c commit 13e5071

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

Sniffs/PHP/NamespaceSniff.php

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
/**
3+
* When catching an exception inside a namespace it is important that you escape to the global space.
4+
*
5+
*/
6+
7+
class Ecg_Sniffs_PHP_NamespaceSniff implements PHP_CodeSniffer_Sniff
8+
{
9+
public function register()
10+
{
11+
return array(
12+
T_CATCH
13+
);
14+
}
15+
16+
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
17+
{
18+
if ($phpcsFile->findNext(T_NAMESPACE, 0) === false) {
19+
return;
20+
}
21+
22+
$tokens = $phpcsFile->getTokens();
23+
24+
$endOfTryStatement = $phpcsFile->findEndOfStatement($stackPtr);
25+
26+
$posOfCatchVariable = $phpcsFile->findNext(T_VARIABLE, $stackPtr, $endOfTryStatement);
27+
28+
$posOfExceptionClassName = $phpcsFile->findNext(T_STRING, $stackPtr, $posOfCatchVariable);
29+
30+
$posOfNsSeparator = $phpcsFile->findNext(T_NS_SEPARATOR, $stackPtr, $posOfExceptionClassName);
31+
32+
if ($posOfNsSeparator === false) {
33+
$exceptionClassName = trim($tokens[$posOfExceptionClassName]['content']);
34+
$posOfClassInUse = $phpcsFile->findNext(T_STRING, 0, $stackPtr, false, $exceptionClassName);
35+
if ($posOfClassInUse === false || $tokens[$posOfClassInUse]['level'] != 0) {
36+
$phpcsFile->addError('Namespace for "'.$exceptionClassName.'" class is not specified.', $posOfExceptionClassName);
37+
}
38+
}
39+
}
40+
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
/**
3+
*
4+
*/
5+
6+
class Ecg_Sniffs_PHP_PrivateClassMemberSniff implements PHP_CodeSniffer_Sniff
7+
{
8+
public function register()
9+
{
10+
return array(
11+
T_PRIVATE
12+
);
13+
}
14+
15+
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
16+
{
17+
$phpcsFile->addWarning('Private class member detected.', $stackPtr);
18+
}
19+
}

Tests/PHP/NamespaceUnitTest.inc

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
namespace foo\bar;
3+
4+
//use \Exception;
5+
6+
class TestNamespace
7+
{
8+
public function go()
9+
{
10+
try {
11+
throw new \Exception('test');
12+
} catch (Exception $e) {
13+
return 'cache block';
14+
}
15+
}
16+
}
17+
18+
$class = new TestNamespace();
19+
echo $class->go();

0 commit comments

Comments
 (0)