Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions Standards/moodle/Sniffs/Strings/PreferCoreTextSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php

// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.

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 <cameron@cameron1729.xyz>
* @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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
<?php

// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.

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 <cameron@cameron1729.xyz>
* @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'],
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

strlen($text);
strtolower($text);
strtoupper($text);
strpos($text, $needle, 2);
strrpos($text, $needle, 2);
strrchr($text, $needle);
strrev($text);
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

substr('नमस्ते दुनिया', 0, 6);
\substr($shortname, 0, 253);
SUBSTR($text, 0, -1);
\SuBsTr($text, -2);
substr(string: $text, offset: 0, length: 255);
substr($text, 0, strlen($text) - 1);
$callback = substr(...);
substr('ascii', 0, 3);
$flags = $flags & strpos($text, $needle);
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace first {
use function Vendor\text\strlen;
use function Vendor\text\slice as substr;
use function Vendor\text\{lower as strtolower, strtoupper};
use Vendor\text\{function strrev, Thing, const MARKER};
use Vendor\text\Position as strpos;
use const Vendor\text\POSITION as strrpos;

strlen($text);
STRLEN($text);
substr($text, 0, 3);
strtolower($text);
strtoupper($text);
strrev($text);
strpos($text, $needle);
strrpos($text, $needle);
\strlen($text);

$callback = function () use ($text) {
return strlen($text);
};

trait helpers {}
class example {
use helpers;
public function length($text) {
return strlen($text);
}
}
}

namespace second {
strlen($text);
}

namespace first {
strlen($text);
}

namespace {
use function Vendor\text\strlen;
strlen($text);
\strlen($text);
}

namespace later {
strlen($text);
use function Vendor\text\strlen;
strlen($text);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace example;

use function substr;

substr($text, 0, 3);
\substr($text, 0, 3);
tools\substr($text, 0, 3);
\tools\substr($text, 0, 3);
namespace\substr($text, 0, 3);
Loading
Loading