Skip to content

Commit ecc76fc

Browse files
committed
Add support for spotting static::$member_var outside class scope.
1 parent 9a0388c commit ecc76fc

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

README.mkdn

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ variable use.
88
* Warns on use of undefined variables.
99
* Warns if variables are set or declared but never used within that scope.
1010
* Warns if variables are redeclared within same scope.
11-
* Warns if self::$static_member is used outside class scope.
11+
* Warns if $this, self::$static_member, static::$static_member is used outside class scope.
1212

1313
INSTALLATION
1414
------------

Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -875,20 +875,29 @@ protected function checkForStaticMember(
875875
}
876876
$classNamePtr = $stackPtr - 2;
877877
if (($tokens[$classNamePtr]['code'] !== T_STRING) &&
878-
($tokens[$classNamePtr]['code'] !== T_SELF)) {
878+
($tokens[$classNamePtr]['code'] !== T_SELF) &&
879+
($tokens[$classNamePtr]['code'] !== T_STATIC)) {
879880
return false;
880881
}
881882

882883
// Are we refering to self:: outside a class?
883884
// TODO: not sure this is our business or should be some other sniff.
884-
if ($tokens[$classNamePtr]['code'] === T_SELF) {
885+
if (($tokens[$classNamePtr]['code'] === T_SELF) ||
886+
($tokens[$classNamePtr]['code'] === T_STATIC)) {
887+
if ($tokens[$classNamePtr]['code'] === T_SELF) {
888+
$err_class = 'SelfOutsideClass';
889+
$err_desc = 'self::';
890+
} else {
891+
$err_class = 'StaticOutsideClass';
892+
$err_desc = 'static::';
893+
}
885894
if (!empty($token['conditions'])) {
886895
foreach (array_reverse($token['conditions'], true) as $scopePtr => $scopeCode) {
887896
// self within a closure is invalid
888897
// Note: have to fetch code from $tokens, T_CLOSURE isn't set for conditions codes.
889898
if ($tokens[$scopePtr]['code'] === T_CLOSURE) {
890-
$phpcsFile->addError("Use of self::%s inside closure.", $stackPtr,
891-
'SelfOutsideClass',
899+
$phpcsFile->addError("Use of {$err_desc}%s inside closure.", $stackPtr,
900+
$err_class,
892901
array("\${$varName}"));
893902
return true;
894903
}
@@ -897,8 +906,8 @@ protected function checkForStaticMember(
897906
}
898907
}
899908
}
900-
$phpcsFile->addError("Use of self::%s outside class definition.", $stackPtr,
901-
'SelfOutsideClass',
909+
$phpcsFile->addError("Use of {$err_desc}%s outside class definition.", $stackPtr,
910+
$err_class,
902911
array("\${$varName}"));
903912
return true;
904913
}

0 commit comments

Comments
 (0)