BUGFIX: Leading namespace separator in replaced classnames

* First remove possible namespace seperators from class name to allow
  lookup.
* Check whether we have to prefix the new classname with namespace
  seperator.

Resolves: #14
This commit is contained in:
Daniel Siepmann 2017-03-16 15:02:25 +01:00
parent 1b2e72ec96
commit 0012c229ed
Signed by: Daniel Siepmann
GPG key ID: 33D6629915560EF4

View file

@ -114,6 +114,7 @@ trait ClassnameCheckerTrait
*/ */
public function addFixableError(PhpcsFile $phpcsFile, $classnamePosition, $classname) public function addFixableError(PhpcsFile $phpcsFile, $classnamePosition, $classname)
{ {
$classname = trim($classname, '\\');
$this->addMaybeWarning($phpcsFile, $classnamePosition, $classname); $this->addMaybeWarning($phpcsFile, $classnamePosition, $classname);
if ($this->isLegacyClassname($classname) === false) { if ($this->isLegacyClassname($classname) === false) {
@ -128,10 +129,7 @@ trait ClassnameCheckerTrait
); );
if ($fix === true) { if ($fix === true) {
$phpcsFile->fixer->replaceToken( $this->replaceLegacyClassname($phpcsFile, $classnamePosition, $classname);
$classnamePosition,
$this->getTokenForReplacement('\\' . $this->getNewClassname($classname))
);
} }
} }
@ -156,6 +154,26 @@ trait ClassnameCheckerTrait
); );
} }
/**
* Replaces the classname at $classnamePosition with $classname in $phpcsFile.
*
* @param PhpcsFile $phpcsFile
* @param int $classnamePosition
* @param string $classname
*/
private function replaceLegacyClassname(PhpcsFile $phpcsFile, $classnamePosition, $classname)
{
$prefix = '\\';
if ($phpcsFile->getTokens()[$classnamePosition -1]['code'] === T_NS_SEPARATOR) {
$prefix = '';
}
$phpcsFile->fixer->replaceToken(
$classnamePosition,
$this->getTokenForReplacement($prefix . $this->getNewClassname($classname))
);
}
/** /**
* String to use for replacing / fixing the token. * String to use for replacing / fixing the token.
* Default is class name itself, can be overwritten in sniff for special behaviour. * Default is class name itself, can be overwritten in sniff for special behaviour.