Skip to content
Snippets Groups Projects
Unverified Commit a7c6a386 authored by Mitch Portier's avatar Mitch Portier Committed by GitHub
Browse files

feat(ExceptionT): Add sniff to ensure that exceptions are not translated (#3123061 by Arkener)

parent e3c6e118
No related branches found
No related tags found
No related merge requests found
<?php
/**
* \DrupalPractice\Sniffs\General\ExceptionTSniff.
*
* @category PHP
* @package PHP_CodeSniffer
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace DrupalPractice\Sniffs\General;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
/**
* Checks that exceptions aren't translated.
*
* @category PHP
* @package PHP_CodeSniffer
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class ExceptionTSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array<int|string>
*/
public function register()
{
return [T_THROW];
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the function
* name in the stack.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$endPtr = $phpcsFile->findEndOfStatement($stackPtr);
for ($i = ($stackPtr + 1); $i < $endPtr; $i++) {
if ($tokens[$i]['code'] === T_STRING && $tokens[$i]['content'] === 't') {
$warning = 'Exceptions should not be translated';
$phpcsFile->addWarning($warning, $stackPtr, 'ExceptionT');
return;
}
}
}//end process()
}//end class
<?php
class ExceptionExample {
public function foo() {
throw new Exception(t('Error'));
}
public function bar() {
throw new Exception($this->t('Error'));
}
public function lorem() {
return t('Error');
}
public function ipsum() {
return $this->t('Error');
}
}
<?php
namespace DrupalPractice\Test\General;
use Drupal\Test\CoderSniffUnitTest;
class ExceptionTUnitTest extends CoderSniffUnitTest
{
/**
* Returns the lines where errors should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of errors that should occur on that line.
*
* @param string $testFile The name of the file being tested.
*
* @return array<int, int>
*/
protected function getErrorList(string $testFile): array
{
return [];
}//end getErrorList()
/**
* Returns the lines where warnings should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of warnings that should occur on that line.
*
* @param string $testFile The name of the file being tested.
*
* @return array<int, int>
*/
protected function getWarningList(string $testFile): array
{
return [
6 => 1,
10 => 1,
];
}//end getWarningList()
}//end class
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment