From 8cce6c7b96233729c5528bb5b1fec77bfc241470 Mon Sep 17 00:00:00 2001 From: Cameron Ball Date: Fri, 13 Nov 2026 02:20:23 +0800 Subject: [PATCH] Suggest core_text alternatives for PHP string functions --- .../Sniffs/Strings/PreferCoreTextSniff.php | 128 +++++++++++++++ .../PreferCoreText/PreferCoreTextTest.php | 155 ++++++++++++++++++ .../PreferCoreText/fixtures/alternatives.php | 9 + .../Strings/PreferCoreText/fixtures/calls.php | 11 ++ .../PreferCoreText/fixtures/imports.php | 52 ++++++ .../fixtures/namespaced_calls.php | 11 ++ .../PreferCoreText/fixtures/other_uses.php | 43 +++++ .../fixtures/semicolon_imports.php | 16 ++ .../PreferCoreText/fixtures/suppression.php | 16 ++ Standards/moodle/ruleset.xml | 3 + 10 files changed, 444 insertions(+) create mode 100644 Standards/moodle/Sniffs/Strings/PreferCoreTextSniff.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/PreferCoreTextTest.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/alternatives.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/calls.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/imports.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/namespaced_calls.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/other_uses.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/semicolon_imports.php create mode 100644 Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/suppression.php diff --git a/Standards/moodle/Sniffs/Strings/PreferCoreTextSniff.php b/Standards/moodle/Sniffs/Strings/PreferCoreTextSniff.php new file mode 100644 index 00000000..14b17a36 --- /dev/null +++ b/Standards/moodle/Sniffs/Strings/PreferCoreTextSniff.php @@ -0,0 +1,128 @@ +. + +namespace MoodleHQ\MoodleCS\moodle\Sniffs\Strings; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\ForbiddenFunctionsSniff; +use PHPCSUtils\Internal\Cache; +use PHPCSUtils\Utils\Namespaces; +use PHPCSUtils\Utils\Parentheses; +use PHPCSUtils\Utils\UseStatements; + +/** + * Suggest core_text alternatives for PHP string functions. + * + * @copyright 2026 Cameron Ball + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class PreferCoreTextSniff extends ForbiddenFunctionsSniff +{ + /** @var array PHP string functions and their core_text alternatives. */ + public $forbiddenFunctions = [ + 'substr' => 'core_text::substr', + 'strlen' => 'core_text::strlen', + 'strtolower' => 'core_text::strtolower', + 'strtoupper' => 'core_text::strtoupper', + 'strpos' => 'core_text::strpos', + 'strrpos' => 'core_text::strrpos', + 'strrchr' => 'core_text::strrchr', + 'strrev' => 'core_text::strrev', + ]; + + /** + * Suggest the core_text equivalent. + * + * @param File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the function call. + * @param string $function The function name. + * @param string|null $pattern The matched function pattern, if any. + */ + protected function addError($phpcsFile, $stackPtr, $function, $pattern = null): void { + $opener = $phpcsFile->findNext(T_OPEN_PARENTHESIS, $stackPtr + 1); + if (Parentheses::isOwnerIn($phpcsFile, $opener, T_FUNCTION)) { + return; + } + + // Skip calls such as namespace\substr() in PHPCS 3. + $tokens = $phpcsFile->getTokens(); + if ( + ($tokens[$stackPtr - 1]['code'] ?? null) === T_NS_SEPARATOR && + ($tokens[$stackPtr - 2]['code'] ?? null) === T_NAMESPACE + ) { + return; + } + + $function = $pattern ?? strtolower($function); + if ( + $tokens[$stackPtr]['code'] !== T_NAME_FULLY_QUALIFIED && + ($tokens[$stackPtr - 1]['code'] ?? null) !== T_NS_SEPARATOR + ) { + $function = $this->getImportedFunction($phpcsFile, $stackPtr, $function); + } + if (!isset($this->forbiddenFunctions[$function])) { + return; + } + + $phpcsFile->addWarning( + 'Consider %s().', + $stackPtr, + ucfirst($function), + [$this->forbiddenFunctions[$function]] + ); + } + + /** + * Resolve a function import. + * + * @param File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the function call. + * @param string $function The function name. + * @return string The imported or original function name. + */ + private function getImportedFunction(File $phpcsFile, int $stackPtr, string $function): string { + $namespace = Namespaces::findNamespacePtr($phpcsFile, $stackPtr); + $cacheKey = $namespace === false ? 'global' : $namespace; + if (!Cache::isCached($phpcsFile, __METHOD__, $cacheKey)) { + $imports = []; + $start = $namespace === false ? 0 : $namespace + 1; + for ( + $use = $phpcsFile->findNext(T_USE, $start); + $use !== false; + $use = $phpcsFile->findNext(T_USE, $use + 1) + ) { + if ( + !UseStatements::isImportUse($phpcsFile, $use) || + Namespaces::findNamespacePtr($phpcsFile, $use) !== $namespace + ) { + continue; + } + + foreach (UseStatements::splitImportUseStatement($phpcsFile, $use)['function'] as $alias => $name) { + $imports[strtolower($alias)] = ['name' => strtolower($name), 'position' => $use]; + } + } + Cache::set($phpcsFile, __METHOD__, $cacheKey, $imports); + } + + $imports = Cache::get($phpcsFile, __METHOD__, $cacheKey); + if (isset($imports[$function]) && $imports[$function]['position'] < $stackPtr) { + return $imports[$function]['name']; + } + return $function; + } +} diff --git a/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/PreferCoreTextTest.php b/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/PreferCoreTextTest.php new file mode 100644 index 00000000..fdc61512 --- /dev/null +++ b/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/PreferCoreTextTest.php @@ -0,0 +1,155 @@ +. + +namespace MoodleHQ\MoodleCS\moodle\Tests\Sniffs\Strings\PreferCoreText; + +use MoodleHQ\MoodleCS\moodle\Tests\MoodleCSBaseTestCase; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\LocalFile; +use PHP_CodeSniffer\Ruleset; + +/** + * Tests for PHP string function warnings. + * + * @copyright 2026 Cameron Ball + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * + * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Strings\PreferCoreTextSniff + */ +class PreferCoreTextTest extends MoodleCSBaseTestCase +{ + /** + * Test function warnings. + * + * @dataProvider functionCallsProvider + * @param string $fixture Fixture name. + * @param array $warnings Expected warnings. + */ + public function testFunctionWarnings(string $fixture, array $warnings): void { + $this->setStandard('moodle'); + $this->setSniff('moodle.Strings.PreferCoreText'); + $this->setFixture(__DIR__ . '/fixtures/' . $fixture . '.php'); + $this->setErrors([]); + $this->setWarnings($warnings); + $this->verifyCsResults(); + } + + /** + * Test core_text suggestions. + */ + public function testOtherCoreTextAlternatives(): void { + $this->setStandard('moodle'); + $this->setSniff('moodle.Strings.PreferCoreText'); + $this->setFixture(__DIR__ . '/fixtures/alternatives.php'); + $this->setErrors([]); + $source = '@Source: moodle.Strings.PreferCoreText.'; + $this->setWarnings([ + 3 => 'Consider core_text::strlen(). ' . $source . 'Strlen', + 4 => 'Consider core_text::strtolower(). ' . $source . 'Strtolower', + 5 => 'Consider core_text::strtoupper(). ' . $source . 'Strtoupper', + 6 => 'Consider core_text::strpos(). ' . $source . 'Strpos', + 7 => 'Consider core_text::strrpos(). ' . $source . 'Strrpos', + 8 => 'Consider core_text::strrchr(). ' . $source . 'Strrchr', + 9 => 'Consider core_text::strrev(). ' . $source . 'Strrev', + ]); + $this->verifyCsResults(); + } + + /** + * Function call test cases. + * + * @return array + */ + public static function functionCallsProvider(): array { + $prefix = '@Source: moodle.Strings.PreferCoreText.'; + $source = $prefix . 'Substr'; + return [ + 'direct calls, casing, named arguments and callable creation' => [ + 'calls', + [ + 3 => '@Message: Consider core_text::substr().', + 4 => $source, + 5 => $source, + 6 => $source, + 7 => $source, + 8 => [$source, '@Source: moodle.Strings.PreferCoreText.Strlen'], + 9 => $source, + 10 => $source, + 11 => $prefix . 'Strpos', + ], + ], + 'global calls within a namespace' => ['namespaced_calls', [7 => $source, 8 => $source]], + 'methods, declarations and other string functions' => ['other_uses', []], + 'function imports within namespace blocks' => [ + 'imports', + [ + 17 => $prefix . 'Strpos', + 18 => $prefix . 'Strrpos', + 19 => $prefix . 'Strlen', + 35 => $prefix . 'Strlen', + 39 => $prefix . 'Strlen', + 45 => $prefix . 'Strlen', + 49 => $prefix . 'Strlen', + ], + ], + 'function imports across namespace declarations' => [ + 'semicolon_imports', + [10 => $prefix . 'Strlen', 15 => $prefix . 'Strtoupper', 16 => $prefix . 'Strlen'], + ], + 'suppress warnings by function' => [ + 'suppression', + [10 => '@Source: moodle.Strings.PreferCoreText.Strlen', 13 => $source], + ], + ]; + } + + /** + * Test warnings across standards. + * + * @dataProvider standardsProvider + * @param string $standard Coding standard. + */ + public function testWarningsAreEnabledAndNotFixable(string $standard): void { + $config = new Config([], false); + $config->cache = false; + $config->standards = [$standard]; + $config->sniffs = ['moodle.Strings.PreferCoreText']; + $ruleset = new Ruleset($config); + $path = __DIR__ . '/fixtures/calls.php'; + $file = new LocalFile($path, $ruleset, $config); + $file->process(); + + $this->assertSame([], $file->getErrors()); + $this->assertSame(10, $file->getWarningCount()); + $this->assertSame(0, $file->getFixableCount()); + $file->fixer->fixFile(); + $this->assertSame(file_get_contents($path), $file->fixer->getContents()); + } + + /** + * Coding standards to test. + * + * @return array + */ + public static function standardsProvider(): array { + return [ + 'Moodle 5.x' => ['moodle'], + 'Moodle 6.0' => ['moodle600'], + 'extended standard' => ['moodle-extra'], + ]; + } +} diff --git a/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/alternatives.php b/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/alternatives.php new file mode 100644 index 00000000..2cbbd862 --- /dev/null +++ b/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/alternatives.php @@ -0,0 +1,9 @@ +substr($text, 0, 6); +$object?->substr($text, 0, 6); +example::substr($text, 0, 6); +mb_substr($text, 0, 6, 'UTF-8'); +core_text::strlen($text); +core_text::strtolower($text); +core_text::strtoupper($text); +core_text::strpos($text, $needle); +core_text::strrpos($text, $needle); +core_text::strrchr($text, $needle); +core_text::strrev($text); +str_replace('_', '-', $text); +trim($text); +ucwords($text); +new substr($text); +$literal = 'substr($text, 0, 6)'; +// substr($text, 0, 6); diff --git a/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/semicolon_imports.php b/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/semicolon_imports.php new file mode 100644 index 00000000..a35076d7 --- /dev/null +++ b/Standards/moodle/Tests/Sniffs/Strings/PreferCoreText/fixtures/semicolon_imports.php @@ -0,0 +1,16 @@ + + + +