Skip to content

Commit cd49860

Browse files
committed
Add sniff that disallows utf8_encode and utf8_decode
These functions can be considered misleading because they only convert to/from ISO-8859-1, and do not 'magically' detect the source/target encoding. Using iconv() or mb_convert_encoding() instead makes both character encodings that play a role in the conversion explicit.
1 parent b68f71a commit cd49860

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
namespace Moxio\CodeSniffer\MoxioSniffs\Sniffs\PHP;
3+
4+
use Moxio\CodeSniffer\MoxioSniffs\Sniffs\AbstractFunctionCallSniff;
5+
use PHP_CodeSniffer\Files\File;
6+
7+
class DisallowUtf8EncodeDecodeSniff extends AbstractFunctionCallSniff
8+
{
9+
protected function registerFunctions()
10+
{
11+
return ['utf8_encode', 'utf8_decode'];
12+
}
13+
14+
protected function processFunctionCall(File $phpcsFile, $functionName, $functionNamePtr, $argumentPtrs)
15+
{
16+
$error = sprintf('Using %s() is not allowed; use iconv() or mb_convert_encoding() instead', $functionName);
17+
$sniffCode = $this->translateFunctionNameToSniffCode($functionName);
18+
$phpcsFile->addError($error, $functionNamePtr, $sniffCode);
19+
}
20+
21+
private function translateFunctionNameToSniffCode($functionName)
22+
{
23+
return implode('', array_map('ucfirst', explode('_', $functionName)));
24+
}
25+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
utf8_encode('foo');
3+
iconv('ISO-8859-1', 'UTF-8', 'foo');
4+
mb_convert_encoding('foo', 'UTF-8', 'ISO-8859-1');
5+
6+
utf8_decode('foo');
7+
iconv('UTF-8', 'ISO-8859-1', 'foo');
8+
mb_convert_encoding('foo', 'ISO-8859-1', 'UTF-8');
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
namespace Moxio\CodeSniffer\MoxioSniffs\Sniffs\Tests\PHP;
3+
4+
use Moxio\CodeSniffer\MoxioSniffs\Sniffs\PHP\DisallowUtf8EncodeDecodeSniff;
5+
use Moxio\CodeSniffer\MoxioSniffs\Sniffs\Tests\AbstractSniffTest;
6+
7+
class DisallowUtf8EncodeDecodeSniffTest extends AbstractSniffTest
8+
{
9+
protected function getSniffClass()
10+
{
11+
return DisallowUtf8EncodeDecodeSniff::class;
12+
}
13+
14+
public function testSniff()
15+
{
16+
$file = __DIR__ . '/DisallowUtf8EncodeDecodeSniffTest.inc';
17+
$this->assertFileHasErrorsOnLines($file, [
18+
2,
19+
6,
20+
]);
21+
}
22+
}

0 commit comments

Comments
 (0)