From 1c12b3321a0733e90535425c36ff1a03c33eb1ca Mon Sep 17 00:00:00 2001 From: "Eloy Lafuente (stronk7)" Date: Sat, 24 Feb 2024 15:14:13 +0100 Subject: [PATCH] Make the whole codebase compliant with our configuration Apart from fixing all the errors and warnings, this commit also: - Changes all http occurrences in comments to https. - Removes all the @package and @category tags, not much useful. - Removes all the phpcs:disable moodle.NamingConventions, not needed. TODO: On purpose, to be able to go testing everything while advancing with this commit, I've not changed our testing API methods on purpose (MoodleCSBaseTestCase). That comes in the next commit. --- LICENSE | 8 +- moodle/Sniffs/Commenting/CategorySniff.php | 13 +- .../Sniffs/Commenting/InlineCommentSniff.php | 103 ++++--- moodle/Sniffs/Commenting/PackageSniff.php | 14 +- moodle/Sniffs/Commenting/TodoCommentSniff.php | 2 - .../ControlSignatureSniff.php | 18 +- .../Sniffs/Files/BoilerplateCommentSniff.php | 41 ++- moodle/Sniffs/Files/LineLengthSniff.php | 15 +- moodle/Sniffs/Files/MoodleInternalSniff.php | 113 ++++--- moodle/Sniffs/Files/RequireLoginSniff.php | 42 +-- .../Namespaces/NamespaceStatementSniff.php | 13 +- .../ValidFunctionNameSniff.php | 42 ++- .../ValidVariableNameSniff.php | 45 +-- .../Sniffs/PHP/DeprecatedFunctionsSniff.php | 22 +- moodle/Sniffs/PHP/ForbiddenFunctionsSniff.php | 14 +- moodle/Sniffs/PHP/ForbiddenGlobalUseSniff.php | 39 ++- moodle/Sniffs/PHP/ForbiddenTokensSniff.php | 26 +- moodle/Sniffs/PHP/IncludingFileSniff.php | 22 +- moodle/Sniffs/PHP/MemberVarScopeSniff.php | 17 +- moodle/Sniffs/PHPUnit/TestCaseCoversSniff.php | 146 ++++++--- moodle/Sniffs/PHPUnit/TestCaseNamesSniff.php | 99 ++++-- .../Sniffs/PHPUnit/TestCaseProviderSniff.php | 19 +- .../Sniffs/PHPUnit/TestCasesAbstractSniff.php | 12 +- .../Sniffs/PHPUnit/TestClassesFinalSniff.php | 14 +- moodle/Sniffs/PHPUnit/TestReturnTypeSniff.php | 14 +- .../Sniffs/Strings/ForbiddenStringsSniff.php | 41 +-- .../WhiteSpace/SpaceAfterCommaSniff.php | 13 +- .../WhiteSpace/WhiteSpaceInStringsSniff.php | 24 +- moodle/Tests/FilesBoilerPlateCommentTest.php | 33 +- moodle/Tests/MoodleCSBaseTestCase.php | 96 +++--- moodle/Tests/MoodleStandardTest.php | 290 +++++++++--------- ...NamingConventionsValidFunctionNameTest.php | 25 +- ...rmalizedArraysArraysCommaAfterLastTest.php | 13 +- moodle/Tests/PHPIncludingFileTest.php | 19 +- moodle/Tests/PHPMemberVarScopeTest.php | 19 +- moodle/Tests/PHPUnitTestCaseCoversTest.php | 25 +- moodle/Tests/PHPUnitTestCaseNamesTest.php | 33 +- moodle/Tests/PHPUnitTestCaseProviderTest.php | 27 +- moodle/Tests/PHPUnitTestReturnTypeTest.php | 27 +- .../Sniffs/Commenting/CategorySniffTest.php | 6 +- .../Commenting/InlineCommentSniffTest.php | 4 +- .../Sniffs/Commenting/PackageSniffTest.php | 23 +- .../Commenting/TodoCommentSniffTest.php | 4 +- .../Tests/Sniffs/Files/MoodleInternalTest.php | 16 +- .../MethodDeclarationSpacingSniffTest.php | 3 +- .../NamespaceStatementSniffTest.php | 20 +- .../PHPUnit/TestCasesAbstractSniffTest.php | 21 +- .../PHPUnit/TestClassesFinalSniffTest.php | 27 +- .../SquizArraysArrayBrackerSpacingTest.php | 19 +- ...quizOperatorsValidLogicalOperatorsTest.php | 21 +- moodle/Tests/Util/DocblocksTest.php | 16 +- moodle/Tests/Util/MoodleUtilTest.php | 87 +++--- .../Tests/WhiteSpaceSpaceAfterCommaTest.php | 19 +- .../WhiteSpaceWhiteSpaceInStringsTest.php | 19 +- moodle/Tests/bootstrap.php | 6 +- moodle/Util/Docblocks.php | 17 +- moodle/Util/MoodleUtil.php | 46 +-- 57 files changed, 1008 insertions(+), 964 deletions(-) diff --git a/LICENSE b/LICENSE index 94a9ed0..e600086 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,7 @@ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @@ -645,7 +645,7 @@ the "copyright" line and a pointer to where the full notice is found. GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program. If not, see . + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. @@ -664,11 +664,11 @@ might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see -. +. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read -. +. diff --git a/moodle/Sniffs/Commenting/CategorySniff.php b/moodle/Sniffs/Commenting/CategorySniff.php index 6f9537a..675078e 100644 --- a/moodle/Sniffs/Commenting/CategorySniff.php +++ b/moodle/Sniffs/Commenting/CategorySniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\Commenting; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use MoodleHQ\MoodleCS\moodle\Util\Docblocks; use PHP_CodeSniffer\Sniffs\Sniff; @@ -27,10 +26,10 @@ * Checks that all test classes and global functions have appropriate @package tags. * * @copyright 2024 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class CategorySniff implements Sniff { - +class CategorySniff implements Sniff +{ /** * Register for open tag (only process once per file). */ diff --git a/moodle/Sniffs/Commenting/InlineCommentSniff.php b/moodle/Sniffs/Commenting/InlineCommentSniff.php index 39c00e4..84115c1 100644 --- a/moodle/Sniffs/Commenting/InlineCommentSniff.php +++ b/moodle/Sniffs/Commenting/InlineCommentSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Verifies that inline comments conform to their coding standards. @@ -20,9 +21,8 @@ * Based on {@see PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\InlineCommentSniff} * with some customizations to suit our very personal rules. * - * @package local_codechecker - * @copyright 2012 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2012 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** @@ -35,14 +35,12 @@ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Commenting; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Util\Tokens; -class InlineCommentSniff implements Sniff { - +class InlineCommentSniff implements Sniff +{ /** * A list of tokenizers this sniff supports. * @@ -64,9 +62,7 @@ public function register() { T_COMMENT, T_DOC_COMMENT_OPEN_TAG, ]; - - }//end register() - + } /** * Processes this test, when one of its tokens is encountered. @@ -131,12 +127,12 @@ public function process(File $phpcsFile, $stackPtr) { // Allow phpdoc block before "return new class extends" expressions, // we use those anon classes in places like coverage.php files. - if ($this->is_return_new_class_extends($phpcsFile, $stackPtr)) { + if ($this->isReturnNewClassExtends($phpcsFile, $stackPtr)) { return; } // Allow phpdoc before define() token (see CONTRIB-4150). - if ($tokens[$nextToken]['code'] == T_STRING and $tokens[$nextToken]['content'] == 'define') { + if ($tokens[$nextToken]['code'] == T_STRING && $tokens[$nextToken]['content'] == 'define') { return; } @@ -148,10 +144,11 @@ public function process(File $phpcsFile, $stackPtr) { $ignore[] = T_STRING; $ignore[] = T_OBJECT_OPERATOR; $nextToken = $phpcsFile->findNext($ignore, ($nextToken + 1), null, true); - if ($tokens[$nextToken]['code'] === T_FUNCTION - || $tokens[$nextToken]['code'] === T_CLOSURE - || $tokens[$nextToken]['code'] === T_OBJECT - || $tokens[$nextToken]['code'] === T_PROTOTYPE + if ( + $tokens[$nextToken]['code'] === T_FUNCTION || + $tokens[$nextToken]['code'] === T_CLOSURE || + $tokens[$nextToken]['code'] === T_OBJECT || + $tokens[$nextToken]['code'] === T_PROTOTYPE ) { return; } @@ -176,8 +173,10 @@ public function process(File $phpcsFile, $stackPtr) { true ); // Is it a @var tag in the comment? - if ($tokens[$nextToken]['code'] === T_DOC_COMMENT_TAG && - $tokens[$nextToken]['content'] == '@var') { + if ( + $tokens[$nextToken]['code'] === T_DOC_COMMENT_TAG && + $tokens[$nextToken]['content'] == '@var' + ) { $nextToken = $phpcsFile->findNext( T_DOC_COMMENT_WHITESPACE, ($nextToken + 1), @@ -221,10 +220,10 @@ public function process(File $phpcsFile, $stackPtr) { if (!$nextToken) { // Not valid type-hinting, specialised error. $error = 'Inline doc block type-hinting for \'%s\' does not match next list() variables'; - $data = array($foundvar); + $data = [$foundvar]; $phpcsFile->addError($error, $stackPtr, 'TypeHintingList', $data); } - } else if ($tokens[$nextToken]['code'] === T_FOREACH) { + } elseif ($tokens[$nextToken]['code'] === T_FOREACH) { // Let's look within the foreach if the variable appear after the 'as' token. $astoken = $phpcsFile->findNext( T_AS, @@ -237,13 +236,13 @@ public function process(File $phpcsFile, $stackPtr) { if ($tokens[$variabletoken]['content'] !== $foundvar) { // Not valid type-hinting, specialised error. $error = 'Inline doc block type-hinting for \'%s\' does not match next foreach() as variable'; - $data = array($foundvar, $tokens[$nextToken]['content']); + $data = [$foundvar, $tokens[$nextToken]['content']]; $phpcsFile->addError($error, $stackPtr, 'TypeHintingForeach', $data); } - } else if ($tokens[$nextToken]['content'] !== $foundvar) { + } elseif ($tokens[$nextToken]['content'] !== $foundvar) { // Not valid type-hinting, specialised error. $error = 'Inline doc block type-hinting for \'%s\' does not match next code line \'%s...\''; - $data = array($foundvar, $tokens[$nextToken]['content']); + $data = [$foundvar, $tokens[$nextToken]['content']]; $phpcsFile->addError($error, $stackPtr, 'TypeHintingMatch', $data); } return; // Have finished. @@ -255,7 +254,7 @@ public function process(File $phpcsFile, $stackPtr) { $error = 'Inline doc block comments are not allowed; use "// Comment." instead'; $phpcsFile->addError($error, $stackPtr, 'DocBlock'); } - }//end if + } if ($tokens[$stackPtr]['content'][0] === '#') { $error = 'Perl-style comments are not allowed; use "// Comment." instead'; @@ -275,8 +274,9 @@ public function process(File $phpcsFile, $stackPtr) { } // Special case for JS files. - if ($tokens[$previousContent]['code'] === T_COMMA - || $tokens[$previousContent]['code'] === T_SEMICOLON + if ( + $tokens[$previousContent]['code'] === T_COMMA || + $tokens[$previousContent]['code'] === T_SEMICOLON ) { $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($previousContent - 1), null, true); if ($tokens[$lastContent]['code'] === T_CLOSE_CURLY_BRACKET) { @@ -301,14 +301,14 @@ public function process(File $phpcsFile, $stackPtr) { $error = 'Comment separators are not allowed to contain other chars buy hyphens (-). Found: (%s)'; // Basic clean dupes for notification. $wrongcharsfound = implode(array_keys(array_flip(preg_split('//', $wrongcharsfound, -1, PREG_SPLIT_NO_EMPTY)))); - $data = array($wrongcharsfound); + $data = [$wrongcharsfound]; $phpcsFile->addWarning($error, $stackPtr, 'IncorrectCommentSeparator', $data); } // Verify length between 20 and 120. $hyphencount = strlen($matches[1] . $matches[2] . $matches[3]); - if ($hyphencount < 20 or $hyphencount > 120) { + if ($hyphencount < 20 || $hyphencount > 120) { $error = 'Comment separators length must contain 20-120 chars, %s found'; - $phpcsFile->addWarning($error, $stackPtr, 'WrongCommentSeparatorLength', array($hyphencount)); + $phpcsFile->addWarning($error, $stackPtr, 'WrongCommentSeparatorLength', [$hyphencount]); } // Verify it's the first token in the line. $prevToken = $phpcsFile->findPrevious( @@ -317,9 +317,9 @@ public function process(File $phpcsFile, $stackPtr) { null, true ); - if (!empty($prevToken) and $tokens[$prevToken]['line'] == $tokens[$stackPtr]['line']) { + if (!empty($prevToken) && $tokens[$prevToken]['line'] == $tokens[$stackPtr]['line']) { $error = 'Comment separators must be the unique text in the line, code found before'; - $phpcsFile->addWarning($error, $stackPtr, 'WrongCommentCodeFoundBefore', array()); + $phpcsFile->addWarning($error, $stackPtr, 'WrongCommentCodeFoundBefore', []); } // Don't want to continue processing the comment separator. return; @@ -349,7 +349,7 @@ public function process(File $phpcsFile, $stackPtr) { $commentTokens[] = $nextComment; $lastComment = $nextComment; - }//end while + } $commentText = ''; foreach ($commentTokens as $lastCommentToken) { @@ -360,7 +360,7 @@ public function process(File $phpcsFile, $stackPtr) { if ($slashCount > 2) { $error = '%s slashes comments are not allowed; use "// Comment." instead'; - $data = array($slashCount); + $data = [$slashCount]; $phpcsFile->addError($error, $lastCommentToken, 'WrongStyle', $data); } @@ -393,14 +393,14 @@ public function process(File $phpcsFile, $stackPtr) { $comment, ]; $fix = $phpcsFile->addFixableError($error, $lastCommentToken, 'TabBefore', $data); - } else if ($spaceCount === 0) { + } elseif ($spaceCount === 0) { $error = 'No space found before comment text; expected "// %s" but found "%s"'; $data = [ substr($comment, $slashCount), $comment, ]; $fix = $phpcsFile->addFixableError($error, $lastCommentToken, 'NoSpaceBefore', $data); - } else if ($spaceCount > 1) { + } elseif ($spaceCount > 1) { $error = 'Expected 1 space before comment text but found %s; use block comment if you need indentation'; $data = [ $spaceCount, @@ -408,15 +408,15 @@ public function process(File $phpcsFile, $stackPtr) { $comment, ]; $fix = $phpcsFile->addFixableError($error, $lastCommentToken, 'SpacingBefore', $data); - }//end if + } if ($fix === true) { - $newComment = '// '.ltrim($tokens[$lastCommentToken]['content'], "/\t "); + $newComment = '// ' . ltrim($tokens[$lastCommentToken]['content'], "/\t "); $phpcsFile->fixer->replaceToken($lastCommentToken, $newComment); } $commentText .= trim(substr($tokens[$lastCommentToken]['content'], $slashCount)); - }//end foreach + } if ($commentText === '') { $error = 'Blank comments are not allowed'; @@ -454,7 +454,7 @@ public function process(File $phpcsFile, $stackPtr) { $error = 'Inline comments must end in %s'; $ender = ''; foreach ($acceptedClosers as $closerName => $symbol) { - $ender .= ' '.$closerName.','; + $ender .= ' ' . $closerName . ','; } $ender = trim($ender, ' ,'); @@ -500,8 +500,11 @@ public function process(File $phpcsFile, $stackPtr) { $type = end($conditions); $conditionPtr = key($conditions); - if (($type === T_FUNCTION || $type === T_CLOSURE) - && $tokens[$conditionPtr]['scope_closer'] === $next + if ( + ( + $type === T_FUNCTION || + $type === T_CLOSURE + ) && $tokens[$conditionPtr]['scope_closer'] === $next ) { $errorCode = 'SpacingAfterAtFunctionEnd'; } @@ -512,7 +515,7 @@ public function process(File $phpcsFile, $stackPtr) { if ($tokens[$i]['code'] !== T_WHITESPACE) { return ($lastCommentToken + 1); } - } else if ($tokens[$i]['line'] > ($tokens[$lastCommentToken]['line'] + 1)) { + } elseif ($tokens[$i]['line'] > ($tokens[$lastCommentToken]['line'] + 1)) { break; } } @@ -531,11 +534,10 @@ public function process(File $phpcsFile, $stackPtr) { $phpcsFile->fixer->endChangeset(); } - }//end if + } return ($lastCommentToken + 1); - - }//end process() + } /** * This looks if there is a valid "return new class extends" expression allowed to have phpdoc block. @@ -544,7 +546,7 @@ public function process(File $phpcsFile, $stackPtr) { * @param int $pointer The position in the stack. * @return bool true if is an allowed to have phpdoc block return new class code. */ - protected function is_return_new_class_extends(File $file, $pointer) { + protected function isReturnNewClassExtends(File $file, $pointer) { $ignoredtokens = Tokens::$emptyTokens; @@ -576,6 +578,5 @@ protected function is_return_new_class_extends(File $file, $pointer) { // Found a valid "return new class extends" expression, phpdoc block allowed. return true; - }// end is_return_new_class_extends() - -}//end class + } +} diff --git a/moodle/Sniffs/Commenting/PackageSniff.php b/moodle/Sniffs/Commenting/PackageSniff.php index 85e0a96..41867cf 100644 --- a/moodle/Sniffs/Commenting/PackageSniff.php +++ b/moodle/Sniffs/Commenting/PackageSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\Commenting; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use MoodleHQ\MoodleCS\moodle\Util\Docblocks; use PHP_CodeSniffer\Sniffs\Sniff; @@ -28,10 +27,10 @@ * Checks that all test classes and global functions have appropriate @package tags. * * @copyright 2024 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class PackageSniff implements Sniff { - +class PackageSniff implements Sniff +{ /** * Register for open tag (only process once per file). */ @@ -88,7 +87,6 @@ public function process(File $phpcsFile, $stackPtr) { $this->checkDocblock($phpcsFile, $typePtr, $docblock); } - } /** diff --git a/moodle/Sniffs/Commenting/TodoCommentSniff.php b/moodle/Sniffs/Commenting/TodoCommentSniff.php index c756d3b..badec28 100644 --- a/moodle/Sniffs/Commenting/TodoCommentSniff.php +++ b/moodle/Sniffs/Commenting/TodoCommentSniff.php @@ -27,8 +27,6 @@ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Commenting; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Config; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; diff --git a/moodle/Sniffs/ControlStructures/ControlSignatureSniff.php b/moodle/Sniffs/ControlStructures/ControlSignatureSniff.php index e0f84d5..1d8031f 100644 --- a/moodle/Sniffs/ControlStructures/ControlSignatureSniff.php +++ b/moodle/Sniffs/ControlStructures/ControlSignatureSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Verifies that control statements conform to their coding standards. * * Based on {@link Squiz_Sniffs_ControlStructures_ControlSignatureSniff}. * - * @package local_codechecker * @copyright 2011 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\ControlStructures; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\AbstractPatternSniff; use PHP_CodeSniffer\Files\File; -class ControlSignatureSniff extends AbstractPatternSniff { - +class ControlSignatureSniff extends AbstractPatternSniff +{ public function __construct() { parent::__construct(true); } @@ -40,7 +38,7 @@ public function __construct() { /** @var array A list of tokenizers this sniff supports. */ protected function getPatterns() { - return array( + return [ 'try {EOL...} catch (...) {EOL', 'do {EOL...} while (...);EOL', 'while (...) {EOL', @@ -49,6 +47,6 @@ protected function getPatterns() { 'foreach (...) {EOL', '} else if (...) {EOL', '} else {EOL', - ); + ]; } } diff --git a/moodle/Sniffs/Files/BoilerplateCommentSniff.php b/moodle/Sniffs/Files/BoilerplateCommentSniff.php index 8883171..57efe20 100644 --- a/moodle/Sniffs/Files/BoilerplateCommentSniff.php +++ b/moodle/Sniffs/Files/BoilerplateCommentSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that each file contains the standard GPL comment. * - * @package local_codechecker * @copyright 2011 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Files; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Util\Tokens; -class BoilerplateCommentSniff implements Sniff { - protected static $comment = array( +class BoilerplateCommentSniff implements Sniff +{ + protected static $comment = [ "// This file is part of", "//", "// Moodle is free software: you can redistribute it and/or modify", @@ -46,9 +45,9 @@ class BoilerplateCommentSniff implements Sniff { "//", "// You should have received a copy of the GNU General Public License", "// along with Moodle. If not, see .", - ); + ]; public function register() { - return array(T_OPEN_TAG); + return [T_OPEN_TAG]; } public function process(File $file, $stackptr) { @@ -83,8 +82,11 @@ public function process(File $file, $stackptr) { } if ($numnewlines > 0) { - $file->addError('The opening addError( + 'The opening addError('Line %s of the opening comment must start "%s".', - $tokenptr, 'WrongLine', array($lineindex + 1, $line)); + if ( + $tokens[$tokenptr]['code'] != T_COMMENT || + !preg_match($regex, $tokens[$tokenptr]['content']) + ) { + $file->addError( + 'Line %s of the opening comment must start "%s".', + $tokenptr, + 'WrongLine', + [$lineindex + 1, $line] + ); } } } diff --git a/moodle/Sniffs/Files/LineLengthSniff.php b/moodle/Sniffs/Files/LineLengthSniff.php index 1c4cb4c..f12e8c9 100644 --- a/moodle/Sniffs/Files/LineLengthSniff.php +++ b/moodle/Sniffs/Files/LineLengthSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that lines are no more than 180 chars, ideally 132. * - * @package local_codechecker * @copyright 2011 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Files; @@ -28,8 +28,8 @@ use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; -class LineLengthSniff extends GenericLineLengthSniff { - +class LineLengthSniff extends GenericLineLengthSniff +{ public function __construct() { $this->lineLimit = 132; $this->absoluteLineLimit = 180; @@ -37,8 +37,7 @@ public function __construct() { public function process(File $file, $stackptr) { // Lang files are allowed to have long lines. - if (strpos($file->getFilename(), - DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR) !== false) { + if (strpos($file->getFilename(), DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR) !== false) { return; } parent::process($file, $stackptr); diff --git a/moodle/Sniffs/Files/MoodleInternalSniff.php b/moodle/Sniffs/Files/MoodleInternalSniff.php index e43f34b..7dbbe24 100644 --- a/moodle/Sniffs/Files/MoodleInternalSniff.php +++ b/moodle/Sniffs/Files/MoodleInternalSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that each file contains the standard MOODLE_INTERNAL check or * a config.php inclusion. * - * @package local_codechecker * @copyright 2016 Dan Poltawski - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Files; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Util\Tokens; -class MoodleInternalSniff implements Sniff { +class MoodleInternalSniff implements Sniff +{ /** * Register for open tag (only process once per file). */ public function register() { - return array(T_OPEN_TAG); + return [T_OPEN_TAG]; } /** @@ -79,13 +78,13 @@ public function process(File $file, $pointer) { } // Find where real code is and check from there. - $pointer = $this->get_position_of_relevant_code($file, $pointer); + $pointer = $this->getPositionOfRelevantCode($file, $pointer); if (!$pointer) { // The file only contains non-relevant (and non side-effects) code. We are done. return; } - if ($this->is_config_php_incluson($file, $pointer)) { + if ($this->isConfigPhpInclusion($file, $pointer)) { // We are requiring config.php. This file is good, hurrah! return; } @@ -95,46 +94,60 @@ public function process(File $file, $pointer) { $sideEffectsPointer = $pointer; // OK, we've got to the first bit of relevant code. It must be the MOODLE_INTERNAL check. - if ($this->is_moodle_internal_or_die_check($file, $pointer)) { + if ($this->isMoodleInternalOrDieCheck($file, $pointer)) { $hasMoodleInternal = true; // Let's look for side effects after the check. $sideEffectsPointer = $file->findNext(T_SEMICOLON, $pointer) + 1; - - } else if ($this->is_if_not_moodle_internal_die_check($file, $pointer)) { + } elseif ($this->isIfNotMoodleInternalDieCheck($file, $pointer)) { $hasMoodleInternal = true; $isOldMoodleInternal = true; // Let's look for side effects after the check. $sideEffectsPointer = $file->getTokens()[$pointer]['scope_closer'] + 1; } - $hasSideEffects = $this->code_changes_global_state($file, $sideEffectsPointer, ($file->numTokens - 1)); - $hasMultipleArtifacts = ($this->count_artifacts($file) > 1); + $hasSideEffects = $this->codeChangesGlobalState($file, $sideEffectsPointer, ($file->numTokens - 1)); + $hasMultipleArtifacts = ($this->countArtifacts($file) > 1); // Missing MOODLE_INTERNAL and having side effects, error. if (!$hasMoodleInternal && $hasSideEffects) { - $file->addError('Expected MOODLE_INTERNAL check or config.php inclusion. Change in global state detected.', - $pointer, 'MoodleInternalGlobalState'); + $file->addError( + 'Expected MOODLE_INTERNAL check or config.php inclusion. Change in global state detected.', + $pointer, + 'MoodleInternalGlobalState' + ); return; } // Missing MOODLE_INTERNAL, not having side effects, but having multiple artifacts, warning. if (!$hasMoodleInternal && !$hasSideEffects && $hasMultipleArtifacts) { - $file->addWarning('Expected MOODLE_INTERNAL check or config.php inclusion. Multiple artifacts detected.', - $pointer, 'MoodleInternalMultipleArtifacts'); + $file->addWarning( + 'Expected MOODLE_INTERNAL check or config.php inclusion. Multiple artifacts detected.', + $pointer, + 'MoodleInternalMultipleArtifacts' + ); return; } // Having MOODLE_INTERNAL, not having side effects and not having multiple artifacts, error. - if ($hasMoodleInternal && !$hasSideEffects && !$hasMultipleArtifacts) { - $file->addWarning('Unexpected MOODLE_INTERNAL check. No side effects or multiple artifacts detected.', - $pointer, 'MoodleInternalNotNeeded'); + if ( + $hasMoodleInternal && + !$hasSideEffects && !$hasMultipleArtifacts + ) { + $file->addWarning( + 'Unexpected MOODLE_INTERNAL check. No side effects or multiple artifacts detected.', + $pointer, + 'MoodleInternalNotNeeded' + ); return; } // Having old MOODLE_INTERNAL check, warn. if ($hasMoodleInternal && $isOldMoodleInternal) { - $file->addWarning('Old MOODLE_INTERNAL check detected. Replace it by "defined(\'MOODLE_INTERNAL\') || die();"', - $pointer, 'MoodleInternalOld'); + $file->addWarning( + 'Old MOODLE_INTERNAL check detected. Replace it by "defined(\'MOODLE_INTERNAL\') || die();"', + $pointer, + 'MoodleInternalOld' + ); return; } } @@ -147,7 +160,7 @@ public function process(File $file, $pointer) { * @param int $pointer The position in the stack. * @return int position in stack of relevant code. */ - protected function get_position_of_relevant_code(File $file, $pointer) { + protected function getPositionOfRelevantCode(File $file, $pointer) { // Advance through tokens until we find some real code. $tokens = $file->getTokens(); $relevantcodefound = false; @@ -159,14 +172,14 @@ protected function get_position_of_relevant_code(File $file, $pointer) { if ($tokens[$pointer]['code'] === T_NAMESPACE || $tokens[$pointer]['code'] === T_USE) { // Namespace definitions are allowed before anything else, jump to end of namspace statement. $pointer = $file->findEndOfStatement($pointer + 1, T_COMMA); - } else if ($tokens[$pointer]['code'] === T_STRING && $tokens[$pointer]['content'] == 'define') { + } elseif ($tokens[$pointer]['code'] === T_STRING && $tokens[$pointer]['content'] == 'define') { // Some things like AJAX_SCRIPT NO_MOODLE_COOKIES need to be defined before config inclusion. // Jump to end of define(). $pointer = $file->findEndOfStatement($pointer + 1); - } else if ($tokens[$pointer]['code'] === T_DECLARE && $tokens[$pointer]['content'] == 'declare') { + } elseif ($tokens[$pointer]['code'] === T_DECLARE && $tokens[$pointer]['content'] == 'declare') { // Declare statements must be at start of file. $pointer = $file->findEndOfStatement($pointer + 1); - } else if ($tokens[$pointer]['code'] === T_ATTRIBUTE) { + } elseif ($tokens[$pointer]['code'] === T_ATTRIBUTE) { // Attribute statements may exist before code. Skip them. $pointer = $tokens[$pointer]['attribute_closer'] + 1; } else { @@ -186,23 +199,25 @@ protected function get_position_of_relevant_code(File $file, $pointer) { * @param int $pointer The position in the stack. * @return bool true if is a moodle internal statement */ - protected function is_moodle_internal_or_die_check(File $file, $pointer) { + protected function isMoodleInternalOrDieCheck(File $file, $pointer) { $tokens = $file->getTokens(); - if ($tokens[$pointer]['code'] !== T_STRING or $tokens[$pointer]['content'] !== 'defined') { + if ($tokens[$pointer]['code'] !== T_STRING || $tokens[$pointer]['content'] !== 'defined') { return false; } $ignoredtokens = array_merge(Tokens::$emptyTokens, Tokens::$bracketTokens); $pointer = $file->findNext($ignoredtokens, $pointer + 1, null, true); - if ($tokens[$pointer]['code'] !== T_CONSTANT_ENCAPSED_STRING or - $tokens[$pointer]['content'] !== "'MOODLE_INTERNAL'") { + if ( + $tokens[$pointer]['code'] !== T_CONSTANT_ENCAPSED_STRING || + $tokens[$pointer]['content'] !== "'MOODLE_INTERNAL'" + ) { return false; } $pointer = $file->findNext($ignoredtokens, $pointer + 1, null, true); - if ($tokens[$pointer]['code'] !== T_BOOLEAN_OR and $tokens[$pointer]['code'] !== T_LOGICAL_OR) { + if ($tokens[$pointer]['code'] !== T_BOOLEAN_OR && $tokens[$pointer]['code'] !== T_LOGICAL_OR) { return false; } @@ -221,10 +236,13 @@ protected function is_moodle_internal_or_die_check(File $file, $pointer) { * @param int $pointer The position in the stack. * @return bool true if is a config.php inclusion. */ - protected function is_config_php_incluson(File $file, $pointer) { + protected function isConfigPhpInclusion(File $file, $pointer) { $tokens = $file->getTokens(); - if ($tokens[$pointer]['code'] !== T_REQUIRE and $tokens[$pointer]['code'] !== T_REQUIRE_ONCE) { + if ( + $tokens[$pointer]['code'] !== T_REQUIRE && + $tokens[$pointer]['code'] !== T_REQUIRE_ONCE + ) { return false; } @@ -248,11 +266,11 @@ protected function is_config_php_incluson(File $file, $pointer) { * @param int $pointer The position in the stack. * @return bool true if is a moodle internal statement */ - protected function is_if_not_moodle_internal_die_check(File $file, $pointer) { + protected function isIfNotMoodleInternalDieCheck(File $file, $pointer) { $tokens = $file->getTokens(); // Detect 'if'. - if ($tokens[$pointer]['code'] !== T_IF ) { + if ($tokens[$pointer]['code'] !== T_IF) { return false; } @@ -266,14 +284,16 @@ protected function is_if_not_moodle_internal_die_check(File $file, $pointer) { // Detect 'defined'. $pointer = $file->findNext($ignoredtokens, $pointer + 1, null, true); - if ($tokens[$pointer]['code'] !== T_STRING or $tokens[$pointer]['content'] !== 'defined') { + if ($tokens[$pointer]['code'] !== T_STRING || $tokens[$pointer]['content'] !== 'defined') { return false; } // Detect 'MOODLE_INTERNAL'. $pointer = $file->findNext($ignoredtokens, $pointer + 1, null, true); - if ($tokens[$pointer]['code'] !== T_CONSTANT_ENCAPSED_STRING or - $tokens[$pointer]['content'] !== "'MOODLE_INTERNAL'") { + if ( + $tokens[$pointer]['code'] !== T_CONSTANT_ENCAPSED_STRING || + $tokens[$pointer]['content'] !== "'MOODLE_INTERNAL'" + ) { return false; } @@ -293,14 +313,13 @@ protected function is_if_not_moodle_internal_die_check(File $file, $pointer) { * * @return int the number of classes, interfaces and traits in the file. */ - private function count_artifacts(File $file) { + private function countArtifacts(File $file) { $position = 0; $counter = 0; while ($position !== false) { if ($position = $file->findNext([T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], ($position + 1))) { $counter++; } - } return $counter; } @@ -314,10 +333,9 @@ private function count_artifacts(File $file) { * @param File $file The file being scanned. * @param int $start The token to start searching from. * @param int $end The token to search to. - * @param array $tokens The stack of tokens that make up the file. - * @return true if side effect is detected in the code. + * @return bool true if side effect is detected in the code. */ - private function code_changes_global_state(File $file, $start, $end) { + private function codeChangesGlobalState(File $file, $start, $end) { $tokens = $file->getTokens(); $symbols = [ T_CLASS => T_CLASS, @@ -382,10 +400,9 @@ private function code_changes_global_state(File $file, $start, $end) { if (isset($symbols[$tokens[$i]['code']]) === true && isset($tokens[$i]['scope_closer']) === true) { $i = $tokens[$i]['scope_closer']; continue; - } else if ($tokens[$i]['code'] === T_STRING && strtolower($tokens[$i]['content']) === 'define') { + } elseif ($tokens[$i]['code'] === T_STRING && strtolower($tokens[$i]['content']) === 'define') { $prev = $file->findPrevious(T_WHITESPACE, ($i - 1), null, true); if ($tokens[$prev]['code'] !== T_OBJECT_OPERATOR) { - $semicolon = $file->findNext(T_SEMICOLON, ($i + 1)); if ($semicolon !== false) { $i = $semicolon; @@ -404,7 +421,7 @@ private function code_changes_global_state(File $file, $start, $end) { continue; } - if ($this->code_changes_global_state($file, ($tokens[$i]['scope_opener'] + 1), ($tokens[$i]['scope_closer'] - 1))) { + if ($this->codeChangesGlobalState($file, ($tokens[$i]['scope_opener'] + 1), ($tokens[$i]['scope_closer'] - 1))) { return true; } diff --git a/moodle/Sniffs/Files/RequireLoginSniff.php b/moodle/Sniffs/Files/RequireLoginSniff.php index 3fa6beb..b03d4db 100644 --- a/moodle/Sniffs/Files/RequireLoginSniff.php +++ b/moodle/Sniffs/Files/RequireLoginSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that each file contains necessary login checks. * - * @package local_codechecker * @copyright 2016 Dan Poltawski - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Files; @@ -27,14 +27,15 @@ use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; -class RequireLoginSniff implements Sniff { +class RequireLoginSniff implements Sniff +{ public $loginfunctions = ['require_login', 'require_course_login', 'require_admin', 'admin_externalpage_setup']; public $ignorewhendefined = ['NO_MOODLE_COOKIES', 'CLI_SCRIPT', 'ABORT_AFTER_CONFIG']; /** * Register for open tag (only process once per file). */ public function register() { - return array(T_OPEN_TAG); + return [T_OPEN_TAG]; } /** @@ -50,22 +51,25 @@ public function process(File $file, $pointer) { return; // @codeCoverageIgnore } - $pointer = $this->get_config_inclusion_position($file, $pointer); + $pointer = $this->getConfigInclusionPosition($file, $pointer); if ($pointer === false) { // Config.php not included form file. return; } // OK, we've got a config.php. - if ($this->should_skip_login_checks($file, $pointer)) { + if ($this->shouldSkipLoginChecks($file, $pointer)) { // Login function check not necessary. return; } - if (!$this->is_login_function_present($file, $pointer)) { + if (!$this->isLoginFunctionPresent($file, $pointer)) { $loginfunctionsstr = implode(', ', $this->loginfunctions); - $file->addWarning("Expected login check ($loginfunctionsstr) following config inclusion. None found.", - $pointer, 'Missing'); + $file->addWarning( + "Expected login check ($loginfunctionsstr) following config inclusion. None found.", + $pointer, + 'Missing' + ); } } @@ -76,7 +80,7 @@ public function process(File $file, $pointer) { * @param int $pointer The position in the stack. * @return int|false the position in the file or false if no require statement found. */ - protected function get_config_inclusion_position(File $file, $pointer) { + protected function getConfigInclusionPosition(File $file, $pointer) { for ($i = $pointer; $i < $file->numTokens; $i++) { $i = $file->findNext([T_REQUIRE, T_REQUIRE_ONCE], $i); if ($i === false) { @@ -84,7 +88,7 @@ protected function get_config_inclusion_position(File $file, $pointer) { return false; } - if ($this->is_a_config_php_incluson($file, $i)) { + if ($this->isConfigPhpInclusion($file, $i)) { // Found config.php. return $i; } @@ -99,7 +103,7 @@ protected function get_config_inclusion_position(File $file, $pointer) { * @param int $pointer The position in the stack. * @return bool true if it is a config inclusion */ - protected function is_a_config_php_incluson(File $file, $pointer) { + protected function isConfigPhpInclusion(File $file, $pointer) { $tokens = $file->getTokens(); // It's a require() or require_once() statement. Is it require(config.php)? @@ -119,11 +123,10 @@ protected function is_a_config_php_incluson(File $file, $pointer) { * @param int $pointer The position in the stack. * @return bool true if the checks should be skipped */ - protected function should_skip_login_checks(File $file, $pointer) { + protected function shouldSkipLoginChecks(File $file, $pointer) { $tokens = $file->getTokens(); for ($i = $pointer; $i > 0; $i--) { - $i = $file->findPrevious(T_STRING, $i); if ($i === false) { // We've got to the start. A login function must be necessary. @@ -154,7 +157,7 @@ protected function should_skip_login_checks(File $file, $pointer) { * @param int $pointer The position in the stack. * @return bool true if the current point in stack is a login function. */ - protected function is_a_login_function(File $file, $pointer) { + protected function isLginFunction(File $file, $pointer) { $tokens = $file->getTokens(); if (in_array($tokens[$pointer]['content'], $this->loginfunctions)) { @@ -171,14 +174,14 @@ protected function is_a_login_function(File $file, $pointer) { * @param int $pointer The position in the stack. * @return true if login function is present. */ - protected function is_login_function_present(File $file, $pointer) { + protected function isLoginFunctionPresent(File $file, $pointer) { for ($i = $pointer; $i < $file->numTokens; $i++) { $i = $file->findNext(T_STRING, $i); if ($i === false) { return false; } - if ($this->is_a_login_function($file, $i)) { + if ($this->isLginFunction($file, $i)) { return true; } @@ -188,6 +191,5 @@ protected function is_login_function_present(File $file, $pointer) { return false; } } - } } diff --git a/moodle/Sniffs/Namespaces/NamespaceStatementSniff.php b/moodle/Sniffs/Namespaces/NamespaceStatementSniff.php index 19923b3..04e940b 100644 --- a/moodle/Sniffs/Namespaces/NamespaceStatementSniff.php +++ b/moodle/Sniffs/Namespaces/NamespaceStatementSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that each file contains the standard GPL comment. * - * @package moodle-cs * @copyright 2023 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Namespaces; @@ -28,9 +28,8 @@ use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Util\Tokens; -// phpcs:disable moodle.NamingConventions - -class NamespaceStatementSniff implements Sniff { +class NamespaceStatementSniff implements Sniff +{ public function register() { return [ diff --git a/moodle/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/moodle/Sniffs/NamingConventions/ValidFunctionNameSniff.php index ebb8b25..a0b58f7 100644 --- a/moodle/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/moodle/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * moodle_sniffs_namingconventions_validfunctionnamesniff. @@ -20,23 +21,20 @@ * Ensures method names are correct depending on whether they are public * or private, and that functions are named correctly. * - * @package local_codechecker * @copyright 2009 Nicolas Connault - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\NamingConventions; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; use PHP_CodeSniffer\Util\Tokens; -class ValidFunctionNameSniff extends AbstractScopeSniff { - +class ValidFunctionNameSniff extends AbstractScopeSniff +{ /** @var array A list of all PHP magic methods. */ - private $magicmethods = array( + private $magicmethods = [ 'construct', 'destruct', 'call', @@ -54,14 +52,14 @@ class ValidFunctionNameSniff extends AbstractScopeSniff { 'set_state', 'clone', 'debuginfo', - ); + ]; /** @var array A list of all PHP magic functions. */ - private $magicfunctions = array( - 'autoload' - ); + private $magicfunctions = [ + 'autoload', + ]; - private $permittedmethods = array( + private $permittedmethods = [ 'setUp', 'tearDown', // Used by simpletest. 'setUpBeforeClass', @@ -71,13 +69,13 @@ class ValidFunctionNameSniff extends AbstractScopeSniff { 'offsetUnset', // Defined by the PHP ArrayAccess interface. 'tearDownAfterClass', 'jsonSerialize', - ); + ]; /** * Constructs a moodle_sniffs_namingconventions_validfunctionnamesniff. */ public function __construct() { - parent::__construct(Tokens::$ooScopeTokens, array(T_FUNCTION), true); + parent::__construct(Tokens::$ooScopeTokens, [T_FUNCTION], true); } /** @@ -89,8 +87,7 @@ public function __construct() { * * @return void */ - protected function processTokenWithinScope(File $phpcsfile, - $stackptr, $currscope) { + protected function processTokenWithinScope(File $phpcsfile, $stackptr, $currscope) { $classname = $phpcsfile->getDeclarationName($currscope); $methodname = $phpcsfile->getDeclarationName($stackptr); @@ -112,12 +109,13 @@ protected function processTokenWithinScope(File $phpcsfile, $scopespecified = $methodprops['scope_specified']; // Only lower-case accepted. - if (preg_match('/[A-Z]+/', $methodname) && - !in_array($methodname, $this->permittedmethods)) { - + if ( + preg_match('/[A-Z]+/', $methodname) && + !in_array($methodname, $this->permittedmethods) + ) { if ($scopespecified === true) { $error = ucfirst($scope) . ' method name "' . $classname . '::' . - $methodname .'" must be in lower-case letters only'; + $methodname . '" must be in lower-case letters only'; } else { $error = 'method name "' . $classname . '::' . $methodname . '" must be in lower-case letters only'; diff --git a/moodle/Sniffs/NamingConventions/ValidVariableNameSniff.php b/moodle/Sniffs/NamingConventions/ValidVariableNameSniff.php index 0fb54ed..5655766 100644 --- a/moodle/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/moodle/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks variable names are all lower-case, no underscores. * - * @package local_codechecker * @copyright 2009 Nicolas Connault - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\NamingConventions; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; use PHP_CodeSniffer\Files\File; -class ValidVariableNameSniff extends AbstractVariableSniff { - - static public $allowedglobals = array('ADMIN', 'CFG', 'COURSE', 'DB', 'FULLME', - 'OUTPUT', 'PAGE', 'PERF', 'SESSION', 'SITE', 'THEME', 'USER', - '_SERVER', '_GET', '_POST', '_FILES', '_REQUEST', '_SESSION', '_ENV', - '_COOKIE', '_HTTP_RAW_POST_DATA', 'ACCESSLIB_PRIVATE', 'ME', - 'CONDITIONLIB_PRIVATE', 'FILTERLIB_PRIVATE', 'SCRIPT', 'MNET_REMOTE_CLIENT', - 'http_response_header'); +class ValidVariableNameSniff extends AbstractVariableSniff +{ + public static $allowedglobals = ['ADMIN', 'CFG', 'COURSE', 'DB', 'FULLME', + 'OUTPUT', 'PAGE', 'PERF', 'SESSION', 'SITE', 'THEME', 'USER', + '_SERVER', '_GET', '_POST', '_FILES', '_REQUEST', '_SESSION', '_ENV', + '_COOKIE', '_HTTP_RAW_POST_DATA', 'ACCESSLIB_PRIVATE', 'ME', + 'CONDITIONLIB_PRIVATE', 'FILTERLIB_PRIVATE', 'SCRIPT', 'MNET_REMOTE_CLIENT', + 'http_response_header']; /** * Processes class member variables. @@ -93,7 +91,7 @@ protected function processMemberVar(File $phpcsfile, $stackptr) { protected function processVariable(File $phpcsfile, $stackptr) { $tokens = $phpcsfile->getTokens(); $membername = ltrim($tokens[$stackptr]['content'], '$'); - $this->validate_moodle_variable_name($membername, $phpcsfile, $stackptr); + $this->validateMoodleVariableName($membername, $phpcsfile, $stackptr); } /** @@ -107,12 +105,17 @@ protected function processVariable(File $phpcsfile, $stackptr) { protected function processVariableInString(File $phpcsfile, $stackptr) { $tokens = $phpcsfile->getTokens(); - if (preg_match_all('/[^\\\\]\$([A-Za-z0-9_]+)(\-\>([A-Za-z0-9_]+))?/i', - $tokens[$stackptr]['content'], $matches)) { + if ( + preg_match_all( + '/[^\\\\]\$([A-Za-z0-9_]+)(\-\>([A-Za-z0-9_]+))?/i', + $tokens[$stackptr]['content'], + $matches + ) + ) { $captured = $matches[1]; foreach ($captured as $varname) { - $this->validate_moodle_variable_name($varname, $phpcsfile, $stackptr); + $this->validateMoodleVariableName($varname, $phpcsfile, $stackptr); } } } @@ -127,7 +130,7 @@ protected function processVariableInString(File $phpcsfile, $stackptr) { * * @return void */ - private function validate_moodle_variable_name($varname, File $phpcsfile, $stackptr) { + private function validateMoodleVariableName($varname, File $phpcsfile, $stackptr) { if (preg_match('/[A-Z]+/', $varname) && !in_array($varname, self::$allowedglobals)) { $error = "Variable \"$varname\" must be all lower-case"; $fix = $phpcsfile->addFixableError($error, $stackptr, 'VariableNameLowerCase'); @@ -135,7 +138,9 @@ private function validate_moodle_variable_name($varname, File $phpcsfile, $stack $phpcsfile->fixer->beginChangeset(); $tokens = $phpcsfile->getTokens(); $phpcsfile->fixer->replaceToken( - $stackptr, str_replace('$' . $varname, '$' . strtolower($varname), $tokens[$stackptr]['content'])); + $stackptr, + str_replace('$' . $varname, '$' . strtolower($varname), $tokens[$stackptr]['content']) + ); $phpcsfile->fixer->endChangeset(); } } diff --git a/moodle/Sniffs/PHP/DeprecatedFunctionsSniff.php b/moodle/Sniffs/PHP/DeprecatedFunctionsSniff.php index 80051c8..8d8e88d 100644 --- a/moodle/Sniffs/PHP/DeprecatedFunctionsSniff.php +++ b/moodle/Sniffs/PHP/DeprecatedFunctionsSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHP; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\DeprecatedFunctionsSniff as GenericDeprecatedFunctionsSniff; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; @@ -42,12 +41,11 @@ * (because unit tests DO NOT parse the ruleset.xml details, like * properties, excludes... and other info). * - * @package local_codechecker * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class DeprecatedFunctionsSniff extends GenericDeprecatedFunctionsSniff { - +class DeprecatedFunctionsSniff extends GenericDeprecatedFunctionsSniff +{ /** * If true, an error will be thrown; otherwise a warning. * @@ -84,7 +82,7 @@ class DeprecatedFunctionsSniff extends GenericDeprecatedFunctionsSniff { * @todo: This method can be removed once/if this PR accepted: * https://github.com/squizlabs/PHP_CodeSniffer/pull/3295 */ - protected function addError($phpcsFile, $stackPtr, $function, $pattern=null) { + protected function addError($phpcsFile, $stackPtr, $function, $pattern = null) { $data = [$function]; $error = 'Function %s() has been deprecated'; $type = 'Deprecated'; @@ -93,8 +91,9 @@ protected function addError($phpcsFile, $stackPtr, $function, $pattern=null) { $pattern = strtolower($function); } - if ($this->forbiddenFunctions[$pattern] !== null - && $this->forbiddenFunctions[$pattern] !== 'null' + if ( + $this->forbiddenFunctions[$pattern] !== null && + $this->forbiddenFunctions[$pattern] !== 'null' ) { $type .= 'WithAlternative'; $data[] = $this->forbiddenFunctions[$pattern]; @@ -106,6 +105,5 @@ protected function addError($phpcsFile, $stackPtr, $function, $pattern=null) { } else { $phpcsFile->addWarning($error, $stackPtr, $type, $data); } - - }//end addError() + } } diff --git a/moodle/Sniffs/PHP/ForbiddenFunctionsSniff.php b/moodle/Sniffs/PHP/ForbiddenFunctionsSniff.php index 84e03a3..4530eb6 100644 --- a/moodle/Sniffs/PHP/ForbiddenFunctionsSniff.php +++ b/moodle/Sniffs/PHP/ForbiddenFunctionsSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHP; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\ForbiddenFunctionsSniff as GenericForbiddenFunctionsSniff; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; @@ -42,12 +41,11 @@ * (because unit tests DO NOT parse the ruleset.xml details, like * properties, excludes... and other info). * - * @package local_codechecker * @copyright 2011 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class ForbiddenFunctionsSniff extends GenericForbiddenFunctionsSniff { - +class ForbiddenFunctionsSniff extends GenericForbiddenFunctionsSniff +{ /** * A list of forbidden functions with their alternatives. * diff --git a/moodle/Sniffs/PHP/ForbiddenGlobalUseSniff.php b/moodle/Sniffs/PHP/ForbiddenGlobalUseSniff.php index 95e5eb8..cc73100 100644 --- a/moodle/Sniffs/PHP/ForbiddenGlobalUseSniff.php +++ b/moodle/Sniffs/PHP/ForbiddenGlobalUseSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Sniff to detect people using global $PAGE and $OUTPUT in renderers, or global $PAGE in blocks. * - * @package local_codechecker * @copyright 2020 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHP; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; use PHP_CodeSniffer\Files\File; -class ForbiddenGlobalUseSniff extends AbstractVariableSniff { - +class ForbiddenGlobalUseSniff extends AbstractVariableSniff +{ /** * @var array list of problems to detect. Each element is an array with three keys: * classtype - this is a human-readable description of this type of class, used in error messages. @@ -67,7 +65,7 @@ protected function processVariable(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $varName = ltrim($tokens[$stackPtr]['content'], '$'); - $this->check_variable_usage($varName, $phpcsFile, $stackPtr); + $this->checkVariableUsage($varName, $phpcsFile, $stackPtr); } /** @@ -78,7 +76,7 @@ protected function processVariableInString(File $phpcsFile, $stackPtr) { if (preg_match_all('|[^\\\]\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[$stackPtr]['content'], $matches) !== 0) { foreach ($matches[1] as $varName) { - $this->check_variable_usage($varName, $phpcsFile, $stackPtr); + $this->checkVariableUsage($varName, $phpcsFile, $stackPtr); } } } @@ -90,9 +88,9 @@ protected function processVariableInString(File $phpcsFile, $stackPtr) { * @param File $phpcsFile The PHP_CodeSniffer file where this token was found. * @param int $stackPtr The position where the token was found. */ - protected function check_variable_usage($varname, File $phpcsFile, $stackPtr) { + protected function checkVariableUsage($varname, File $phpcsFile, $stackPtr) { foreach ($this->forbiddencombinations as $forbiddencombination) { - $this->check_one_combination($varname, $forbiddencombination, $phpcsFile, $stackPtr); + $this->checkOneCombination($varname, $forbiddencombination, $phpcsFile, $stackPtr); } } @@ -106,8 +104,12 @@ protected function check_variable_usage($varname, File $phpcsFile, $stackPtr) { * @param File $phpcsFile The PHP_CodeSniffer file where this token was found. * @param int $stackPtr The position where the token was found. */ - protected function check_one_combination($varname, $forbiddencombination, - File $phpcsFile, $stackPtr) { + protected function checkOneCombination( + $varname, + $forbiddencombination, + File $phpcsFile, + $stackPtr + ) { $tokens = $phpcsFile->getTokens(); if (!in_array($varname, $forbiddencombination['variables'])) { @@ -127,9 +129,12 @@ protected function check_one_combination($varname, $forbiddencombination, // If the classname matches, report the error. if (preg_match($forbiddencombination['classnamepattern'], $classname)) { - $phpcsFile->addError('global $' . $varname . ' cannot be used in ' . - $forbiddencombination['classtype'] . '. Use $this->' . strtolower($varname) . '.', - $stackPtr, 'BadGlobal'); + $phpcsFile->addError( + 'global $' . $varname . ' cannot be used in ' . + $forbiddencombination['classtype'] . '. Use $this->' . strtolower($varname) . '.', + $stackPtr, + 'BadGlobal' + ); return; } } diff --git a/moodle/Sniffs/PHP/ForbiddenTokensSniff.php b/moodle/Sniffs/PHP/ForbiddenTokensSniff.php index a429698..ce241d4 100644 --- a/moodle/Sniffs/PHP/ForbiddenTokensSniff.php +++ b/moodle/Sniffs/PHP/ForbiddenTokensSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * The use of some tokens is forbidden. @@ -20,32 +21,29 @@ * This Sniff looks for some functions and operators that are handled * as specific tokens by the CS tokenizer. Complements {@link moodle_Sniffs_PHP_ForbiddenFunctionsSniff}. * - * @package local_codechecker - * @copyright 2014 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2014 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHP; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; -class ForbiddenTokensSniff implements Sniff { - +class ForbiddenTokensSniff implements Sniff +{ /** * Returns an array of Tokenizer tokens and errors this Sniff will listen and process. * * @return array with tokens as keys and error messages as description. */ - protected function get_forbidden_tokens() { - return array( + protected function getForbiddenTokens() { + return [ T_EVAL => 'The use of function eval() is forbidden', T_GOTO => 'The use of operator goto is forbidden', T_GOTO_LABEL => 'The use of goto labels is forbidden', T_BACKTICK => 'The use of backticks for shell execution is forbidden', - ); + ]; } /** @@ -54,7 +52,7 @@ protected function get_forbidden_tokens() { * @return array tokens this sniff will handle. */ public function register() { - return array_keys($this->get_forbidden_tokens()); + return array_keys($this->getForbiddenTokens()); } /** @@ -68,7 +66,7 @@ public function register() { public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); - $forbidden = $this->get_forbidden_tokens(); + $forbidden = $this->getForbiddenTokens(); $token = $tokens[$stackPtr]; $phpcsFile->addError($forbidden[$token['code']], $stackPtr, 'Found'); } diff --git a/moodle/Sniffs/PHP/IncludingFileSniff.php b/moodle/Sniffs/PHP/IncludingFileSniff.php index 4f7698e..e2f20b2 100644 --- a/moodle/Sniffs/PHP/IncludingFileSniff.php +++ b/moodle/Sniffs/PHP/IncludingFileSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that the include_once is used in conditional situations, and @@ -22,22 +23,20 @@ * * Based on {@link PEAR_Sniffs_Files_IncludingFileSniff}. * - * @package local_codechecker * @copyright 2011 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHP; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Util\Tokens; -class IncludingFileSniff implements Sniff { +class IncludingFileSniff implements Sniff +{ public function register() { - return array(T_INCLUDE_ONCE, T_REQUIRE_ONCE, T_REQUIRE, T_INCLUDE); + return [T_INCLUDE_ONCE, T_REQUIRE_ONCE, T_REQUIRE, T_INCLUDE]; } public function process(File $file, $stackptr) { @@ -45,7 +44,7 @@ public function process(File $file, $stackptr) { if ($tokens[$stackptr + 1]['code'] !== T_OPEN_PARENTHESIS) { $error = '"%s" must be immediately followed by an open parenthesis'; - $data = array($tokens[$stackptr]['content']); + $data = [$tokens[$stackptr]['content']]; $file->addError($error, $stackptr, 'BracketsRequired', $data); } @@ -65,8 +64,7 @@ public function process(File $file, $stackptr) { // Check to see if they are assigning the return value of this // including call. If they are then they are probably checking it, so // it's conditional. - $previous = $file->findPrevious(Tokens::$emptyTokens, - ($stackptr - 1), null, true); + $previous = $file->findPrevious(Tokens::$emptyTokens, ($stackptr - 1), null, true); if (in_array($tokens[$previous]['code'], Tokens::$assignmentTokens)) { // The have assigned the return value to it, so its conditional. $incondition = true; @@ -79,7 +77,7 @@ public function process(File $file, $stackptr) { $error = 'File is being unconditionally included; '; $error .= 'use "require_once" instead'; $file->addError($error, $stackptr, 'UseRequireOnce'); - } else if ($tokentype === T_INCLUDE) { + } elseif ($tokentype === T_INCLUDE) { $error = 'File is being unconditionally included; '; $error .= 'use "require" instead'; $file->addError($error, $stackptr, 'UseRequire'); diff --git a/moodle/Sniffs/PHP/MemberVarScopeSniff.php b/moodle/Sniffs/PHP/MemberVarScopeSniff.php index 923721d..bd23dc5 100644 --- a/moodle/Sniffs/PHP/MemberVarScopeSniff.php +++ b/moodle/Sniffs/PHP/MemberVarScopeSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Verifies that class members have scope modifiers. Created by sam marshall, * based on a sniff by Greg Sherwood and Marc McIntyre. * - * @package local_codechecker * @author Greg Sherwood * @author Marc McIntyre * @author sam marshall * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) * @copyright 2011 The Open University - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence + * @license https://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHP; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Util\Tokens; -class MemberVarScopeSniff - extends AbstractVariableSniff { - +class MemberVarScopeSniff extends AbstractVariableSniff +{ /** * Processes the function tokens within the class. * @@ -54,7 +51,7 @@ protected function processMemberVar(File $file, $stackptr) { if ($modifier === false || $modifier < $semicolon) { $error = 'Scope modifier not specified for member variable "%s"'; - $data = array($tokens[$stackptr]['content']); + $data = [$tokens[$stackptr]['content']]; $file->addError($error, $stackptr, 'Missing', $data); } } diff --git a/moodle/Sniffs/PHPUnit/TestCaseCoversSniff.php b/moodle/Sniffs/PHPUnit/TestCaseCoversSniff.php index 04a5787..de5dece 100644 --- a/moodle/Sniffs/PHPUnit/TestCaseCoversSniff.php +++ b/moodle/Sniffs/PHPUnit/TestCaseCoversSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; @@ -27,17 +26,16 @@ /** * Checks that a test file has the @coversxxx annotations properly defined. * - * @package local_codechecker * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class TestCaseCoversSniff implements Sniff { - +class TestCaseCoversSniff implements Sniff +{ /** * Register for open tag (only process once per file). */ public function register() { - return array(T_OPEN_TAG); + return [T_OPEN_TAG]; } /** @@ -131,10 +129,18 @@ public function process(File $file, $pointer) { // Both @covers and @coversNothing, that's a mistake. 2 errors. if ($classCovers && $classCoversNothing) { - $file->addError('Class %s has both @covers and @coversNothing tags, good contradiction', - $classCovers, 'ContradictoryClass', [$class]); - $file->addError('Class %s has both @covers and @coversNothing tags, good contradiction', - $classCoversNothing, 'ContradictoryClass', [$class]); + $file->addError( + 'Class %s has both @covers and @coversNothing tags, good contradiction', + $classCovers, + 'ContradictoryClass', + [$class] + ); + $file->addError( + 'Class %s has both @covers and @coversNothing tags, good contradiction', + $classCoversNothing, + 'ContradictoryClass', + [$class] + ); } // Iterate over all the methods in the class. @@ -172,8 +178,12 @@ public function process(File $file, $pointer) { break; case '@coversDefaultClass': // Not allowed in methods. - $file->addError('Method %s() has @coversDefaultClass tag, only allowed in classes', - $docPointer, 'DefaultClassNotAllowed', [$method]); + $file->addError( + 'Method %s() has @coversDefaultClass tag, only allowed in classes', + $docPointer, + 'DefaultClassNotAllowed', + [$method] + ); break; } } @@ -182,30 +192,54 @@ public function process(File $file, $pointer) { // No @covers or @coversNothing at any level, that's a missing one. if (!$classCovers && !$classCoversNothing && !$methodCovers && !$methodCoversNothing) { - $file->addWarning('Test method %s() is missing any coverage information, own or at class level', - $mStart, 'Missing', [$method]); + $file->addWarning( + 'Test method %s() is missing any coverage information, own or at class level', + $mStart, + 'Missing', + [$method] + ); } // Both @covers and @coversNothing, that's a mistake. 2 errors. if ($methodCovers && $methodCoversNothing) { - $file->addError('Method %s() has both @covers and @coversNothing tags, good contradiction', - $methodCovers, 'ContradictoryMethod', [$method]); - $file->addError('Method %s() has both @covers and @coversNothing tags, good contradiction', - $methodCoversNothing, 'ContradictoryMethod', [$method]); + $file->addError( + 'Method %s() has both @covers and @coversNothing tags, good contradiction', + $methodCovers, + 'ContradictoryMethod', + [$method] + ); + $file->addError( + 'Method %s() has both @covers and @coversNothing tags, good contradiction', + $methodCoversNothing, + 'ContradictoryMethod', + [$method] + ); } // Found @coversNothing at class, and @covers at method, strange. Warning. if ($classCoversNothing && $methodCovers) { - $file->addWarning('Class %s has @coversNothing, but there are methods covering stuff', - $classCoversNothing, 'ContradictoryMixed', [$class]); - $file->addWarning('Test method %s() is covering stuff, but class has @coversNothing', - $methodCovers, 'ContradictoryMixed', [$method]); + $file->addWarning( + 'Class %s has @coversNothing, but there are methods covering stuff', + $classCoversNothing, + 'ContradictoryMixed', + [$class] + ); + $file->addWarning( + 'Test method %s() is covering stuff, but class has @coversNothing', + $methodCovers, + 'ContradictoryMixed', + [$method] + ); } // Found @coversNothing at class and method, redundant. Warning. if ($classCoversNothing && $methodCoversNothing) { - $file->addWarning('Test method %s() has @coversNothing, but class also has it, redundant', - $methodCoversNothing, 'Redundant', [$method]); + $file->addWarning( + 'Test method %s() has @coversNothing, but class also has it, redundant', + $methodCoversNothing, + 'Redundant', + [$method] + ); } // Advance until the end of the method, if possible, to find the next one quicker. @@ -228,19 +262,31 @@ protected function checkCoversTagsSyntax(File $file, int $pointer, string $tag) if ($tag === '@coversNothing') { // Check that there isn't whitespace and string. - if ($tokens[$pointer + 1]['code'] === T_DOC_COMMENT_WHITESPACE && - $tokens[$pointer + 2]['code'] === T_DOC_COMMENT_STRING) { - $file->addError('Wrong %s annotation, it must be empty', - $pointer, 'NotEmpty', [$tag]); + if ( + $tokens[$pointer + 1]['code'] === T_DOC_COMMENT_WHITESPACE && + $tokens[$pointer + 2]['code'] === T_DOC_COMMENT_STRING + ) { + $file->addError( + 'Wrong %s annotation, it must be empty', + $pointer, + 'NotEmpty', + [$tag] + ); } } if ($tag === '@covers' || $tag === '@coversDefaultClass') { // Check that there is whitespace and string. - if ($tokens[$pointer + 1]['code'] !== T_DOC_COMMENT_WHITESPACE || - $tokens[$pointer + 2]['code'] !== T_DOC_COMMENT_STRING) { - $file->addError('Wrong %s annotation, it must contain some value', - $pointer, 'Empty', [$tag]); + if ( + $tokens[$pointer + 1]['code'] !== T_DOC_COMMENT_WHITESPACE || + $tokens[$pointer + 2]['code'] !== T_DOC_COMMENT_STRING + ) { + $file->addError( + 'Wrong %s annotation, it must contain some value', + $pointer, + 'Empty', + [$tag] + ); // No value, nothing else to check. return; } @@ -249,22 +295,36 @@ protected function checkCoversTagsSyntax(File $file, int $pointer, string $tag) if ($tag === '@coversDefaultClass') { // Check that value begins with \ (FQCN). if (strpos($tokens[$pointer + 2]['content'], '\\') !== 0) { - $file->addError('Wrong %s annotation, it must be FQCN (\\ prefixed)', - $pointer, 'NoFQCN', [$tag]); + $file->addError( + 'Wrong %s annotation, it must be FQCN (\\ prefixed)', + $pointer, + 'NoFQCN', + [$tag] + ); } // Check that value does not contain :: (method). if (strpos($tokens[$pointer + 2]['content'], '::') !== false) { - $file->addError('Wrong %s annotation, cannot point to a method (contains ::)', - $pointer, 'WrongMethod', [$tag]); + $file->addError( + 'Wrong %s annotation, cannot point to a method (contains ::)', + $pointer, + 'WrongMethod', + [$tag] + ); } } if ($tag === '@covers') { // Check value begins with \ (FQCN) or :: (method). - if (strpos($tokens[$pointer + 2]['content'], '\\') !== 0 && - strpos($tokens[$pointer + 2]['content'], '::') !== 0) { - $file->addError('Wrong %s annotation, it must be FQCN (\\ prefixed) or point to method (:: prefixed)', - $pointer, 'NoFQCNOrMethod', [$tag]); + if ( + strpos($tokens[$pointer + 2]['content'], '\\') !== 0 && + strpos($tokens[$pointer + 2]['content'], '::') !== 0 + ) { + $file->addError( + 'Wrong %s annotation, it must be FQCN (\\ prefixed) or point to method (:: prefixed)', + $pointer, + 'NoFQCNOrMethod', + [$tag] + ); } } } diff --git a/moodle/Sniffs/PHPUnit/TestCaseNamesSniff.php b/moodle/Sniffs/PHPUnit/TestCaseNamesSniff.php index c8ec5d8..5e81c37 100644 --- a/moodle/Sniffs/PHPUnit/TestCaseNamesSniff.php +++ b/moodle/Sniffs/PHPUnit/TestCaseNamesSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that a test file has a class name matching the file name. * - * @package local_codechecker * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; -class TestCaseNamesSniff implements Sniff { - +class TestCaseNamesSniff implements Sniff +{ /** * List of classes that have been found during checking. * @@ -50,7 +48,7 @@ class TestCaseNamesSniff implements Sniff { * Register for open tag (only process once per file). */ public function register() { - return array(T_OPEN_TAG); + return [T_OPEN_TAG]; } /** @@ -153,15 +151,23 @@ public function process(File $file, $pointer) { // Error if the found classname is "strange" (not "_test|_testcase" ended). if (substr($class, -5) !== '_test' && substr($class, -9) != '_testcase') { - $file->addError('PHPUnit irregular testcase name found: %s (_test/_testcase ended expected)', $cStart, - 'Irregular', [$class]); + $file->addError( + 'PHPUnit irregular testcase name found: %s (_test/_testcase ended expected)', + $cStart, + 'Irregular', + [$class] + ); } // Check if the file name and the class name match, warn if not. $baseName = pathinfo($fileName, PATHINFO_FILENAME); if ($baseName !== $class) { - $fix = $file->addFixableWarning('PHPUnit testcase name "%s" does not match file name "%s"', $cStart, - 'NoMatch', [$class, $baseName]); + $fix = $file->addFixableWarning( + 'PHPUnit testcase name "%s" does not match file name "%s"', + $cStart, + 'NoMatch', + [$class, $baseName] + ); if ($fix === true) { if ($cNameToken = $file->findNext(T_STRING, $cStart + 1, $tokens[$cStart]['scope_opener'])) { @@ -175,8 +181,12 @@ public function process(File $file, $pointer) { if (isset($this->foundClasses[$fdqnClass])) { // Already found, this is a dupe class name, error! foreach ($this->foundClasses[$fdqnClass] as $exists) { - $file->addError('PHPUnit testcase "%s" already exists at "%s" line %s', $cStart, - 'DuplicateExists', [$fdqnClass, $exists['file'], $exists['line']]); + $file->addError( + 'PHPUnit testcase "%s" already exists at "%s" line %s', + $cStart, + 'DuplicateExists', + [$fdqnClass, $exists['file'], $exists['line']] + ); } } else { // Create the empty element. @@ -193,9 +203,13 @@ public function process(File $file, $pointer) { if (isset($this->proposedClasses[$fdqnClass])) { // Already found, this is a dupe class name, error! foreach ($this->proposedClasses[$fdqnClass] as $exists) { - $file->addError('PHPUnit testcase "%s" already proposed for "%s" line %s. You ' . - 'may want to change the testcase name (file and class)', $cStart, - 'ProposedExists', [$fdqnClass, $exists['file'], $exists['line']]); + $file->addError( + 'PHPUnit testcase "%s" already proposed for "%s" line %s. You ' . + 'may want to change the testcase name (file and class)', + $cStart, + 'ProposedExists', + [$fdqnClass, $exists['file'], $exists['line']] + ); } } @@ -206,8 +220,12 @@ public function process(File $file, $pointer) { if ($namespace && $moodleComponent) { // Verify that the namespace declared in the class matches the namespace expected for the file. if (strpos($namespace . '\\', $moodleComponent . '\\') !== 0) { - $file->addError('PHPUnit class namespace "%s" does not match expected file namespace "%s"', $nsStart, - 'UnexpectedNS', [$namespace, $moodleComponent]); + $file->addError( + 'PHPUnit class namespace "%s" does not match expected file namespace "%s"', + $nsStart, + 'UnexpectedNS', + [$namespace, $moodleComponent] + ); } // Verify that level2 and down match the directory structure under tests. Soft warn if not (till we fix all). @@ -221,30 +239,41 @@ public function process(File $file, $pointer) { // Warning if the relative namespace does not match the relative directory. if ($reldir !== $relns) { - $file->addWarning('PHPUnit class "%s", with namespace "%s", currently located at "tests/%s" directory, '. - 'does not match its expected location at "tests/%s"', $nsStart, - 'UnexpectedLevel2NS', [$fdqnClass, $namespace, $reldir, $relns]); + $file->addWarning( + 'PHPUnit class "%s", with namespace "%s", currently located at "tests/%s" directory, ' . + 'does not match its expected location at "tests/%s"', + $nsStart, + 'UnexpectedLevel2NS', + [$fdqnClass, $namespace, $reldir, $relns] + ); } // TODO: When we have APIs (https://docs.moodle.org/dev/Core_APIs) somewhere at hand (in core) // let's add here an error when incorrect ones are used. See MDL-71096 about it. } - } if (!$namespace && $moodleComponent) { - $file->addWarning('PHPUnit class "%s" does not have any namespace. It is recommended to add it to the "%s" ' . - 'namespace, using more levels if needed, in order to match the code being tested', $cStart, - 'MissingNS', [$fdqnClass, $moodleComponent]); + $file->addWarning( + 'PHPUnit class "%s" does not have any namespace. It is recommended to add it to the "%s" ' . + 'namespace, using more levels if needed, in order to match the code being tested', + $cStart, + 'MissingNS', + [$fdqnClass, $moodleComponent] + ); // Check if the proposed class has been already proposed (this is useful when running against a lot of files). $fdqnProposed = $moodleComponent . '\\' . $fdqnClass; if (isset($this->proposedClasses[$fdqnProposed])) { // Already found, this is a dupe class name, error! foreach ($this->proposedClasses[$fdqnProposed] as $exists) { - $file->addError('Proposed PHPUnit testcase "%s" already proposed for "%s" line %s. You ' . - 'may want to change the testcase name (file and class)', $cStart, - 'DuplicateProposed', [$fdqnProposed, $exists['file'], $exists['line']]); + $file->addError( + 'Proposed PHPUnit testcase "%s" already proposed for "%s" line %s. You ' . + 'may want to change the testcase name (file and class)', + $cStart, + 'DuplicateProposed', + [$fdqnProposed, $exists['file'], $exists['line']] + ); } } else { // Create the empty element. @@ -261,9 +290,13 @@ public function process(File $file, $pointer) { if (isset($this->foundClasses[$fdqnProposed])) { // Already found, this is a dupe class name, error! foreach ($this->foundClasses[$fdqnProposed] as $exists) { - $file->addError('Proposed PHPUnit testcase "%s" already exists at "%s" line %s. You ' . - 'may want to change the testcase name (file and class)', $cStart, - 'ExistsProposed', [$fdqnProposed, $exists['file'], $exists['line']]); + $file->addError( + 'Proposed PHPUnit testcase "%s" already exists at "%s" line %s. You ' . + 'may want to change the testcase name (file and class)', + $cStart, + 'ExistsProposed', + [$fdqnProposed, $exists['file'], $exists['line']] + ); } } } diff --git a/moodle/Sniffs/PHPUnit/TestCaseProviderSniff.php b/moodle/Sniffs/PHPUnit/TestCaseProviderSniff.php index 709dfbd..db010eb 100644 --- a/moodle/Sniffs/PHPUnit/TestCaseProviderSniff.php +++ b/moodle/Sniffs/PHPUnit/TestCaseProviderSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; @@ -27,12 +26,11 @@ /** * Checks that a test file has the @coversxxx annotations properly defined. * - * @package local_codechecker * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class TestCaseProviderSniff implements Sniff { - +class TestCaseProviderSniff implements Sniff +{ /** * Whether to autofix static providers. * @@ -255,7 +253,7 @@ protected function checkDataProvider( } $file->fixer->endChangeset(); } - } else if ($methodProps['scope'] !== 'public') { + } elseif ($methodProps['scope'] !== 'public') { $scopePointer = $file->findPrevious(Tokens::$scopeModifiers, $providerPointer - 1); $fix = $file->addFixableError( 'Data provider method "%s" must be public.', @@ -357,8 +355,7 @@ protected static function findMethodCalls( File $phpcsFile, int $classPtr, string $methodName - ): array - { + ): array { $data = []; $mStart = $classPtr; diff --git a/moodle/Sniffs/PHPUnit/TestCasesAbstractSniff.php b/moodle/Sniffs/PHPUnit/TestCasesAbstractSniff.php index e44e6d7..26e6ce7 100644 --- a/moodle/Sniffs/PHPUnit/TestCasesAbstractSniff.php +++ b/moodle/Sniffs/PHPUnit/TestCasesAbstractSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; @@ -27,9 +26,10 @@ * Checks that testcase classes are declared as abstract. * * @copyright 2024 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class TestCasesAbstractSniff implements Sniff { +class TestCasesAbstractSniff implements Sniff +{ public function register() { return [ T_OPEN_TAG, diff --git a/moodle/Sniffs/PHPUnit/TestClassesFinalSniff.php b/moodle/Sniffs/PHPUnit/TestClassesFinalSniff.php index 189f1fc..923a9b0 100644 --- a/moodle/Sniffs/PHPUnit/TestClassesFinalSniff.php +++ b/moodle/Sniffs/PHPUnit/TestClassesFinalSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; @@ -27,9 +26,10 @@ * Checks that test classes are declared as final. * * @copyright 2024 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class TestClassesFinalSniff implements Sniff { +class TestClassesFinalSniff implements Sniff +{ public function register() { return [ T_OPEN_TAG, @@ -105,7 +105,7 @@ public function process(File $file, $pointer) { $file->fixer->endChangeset(); } } - } else if (!$classInfo['is_final']) { + } elseif (!$classInfo['is_final']) { $fix = $file->addFixableWarning( 'Unit test %s should be declared as final.', $cStart, diff --git a/moodle/Sniffs/PHPUnit/TestReturnTypeSniff.php b/moodle/Sniffs/PHPUnit/TestReturnTypeSniff.php index af5776a..c27588b 100644 --- a/moodle/Sniffs/PHPUnit/TestReturnTypeSniff.php +++ b/moodle/Sniffs/PHPUnit/TestReturnTypeSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; @@ -27,13 +26,11 @@ /** * Checks that a test file has the @coversxxx annotations properly defined. * - * @package local_codechecker * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class TestReturnTypeSniff implements Sniff { - /** * Register for open tag (only process once per file). */ @@ -70,7 +67,8 @@ public function process(File $file, $pointer) $tokens = $file->getTokens(); // We only want to do this once per file. - $prevopentag = $file->findPrevious(T_OPEN_TAG, + $prevopentag = $file->findPrevious( + T_OPEN_TAG, $pointer - 1 ); if ($prevopentag !== false) { diff --git a/moodle/Sniffs/Strings/ForbiddenStringsSniff.php b/moodle/Sniffs/Strings/ForbiddenStringsSniff.php index 70f4ffd..527f582 100644 --- a/moodle/Sniffs/Strings/ForbiddenStringsSniff.php +++ b/moodle/Sniffs/Strings/ForbiddenStringsSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Inspect some strings that may lead to incorrect uses of Moodle/PHP APIs. * - * @package local_codechecker - * @copyright 2014 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2014 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\Strings; -// phpcs:disable moodle.NamingConventions - use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; -class ForbiddenStringsSniff implements Sniff { - +class ForbiddenStringsSniff implements Sniff +{ /** * Returns an array of tokens this test wants to listen for. * @@ -38,7 +36,7 @@ class ForbiddenStringsSniff implements Sniff { */ public function register() { // We are going to handle strings here. - return array(T_CONSTANT_ENCAPSED_STRING); + return [T_CONSTANT_ENCAPSED_STRING]; } /** @@ -51,9 +49,9 @@ public function register() { */ public function process(File $phpcsFile, $stackPtr) { // Delegate the processing to specialised methods. - $this->process_sql_as_keyword($phpcsFile, $stackPtr); - $this->process_regexp_separator_e($phpcsFile, $stackPtr); - $this->process_string_with_backticks($phpcsFile, $stackPtr); + $this->processSqlAsKeyword($phpcsFile, $stackPtr); + $this->processRegexpSeparatorE($phpcsFile, $stackPtr); + $this->processStringWithBackticks($phpcsFile, $stackPtr); } /** @@ -64,7 +62,7 @@ public function process(File $phpcsFile, $stackPtr) { * * @return void */ - protected function process_sql_as_keyword(File $phpcsFile, $stackPtr) { + protected function processSqlAsKeyword(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $token = $tokens[$stackPtr]; $text = trim($token['content'], "'\""); @@ -82,7 +80,7 @@ protected function process_sql_as_keyword(File $phpcsFile, $stackPtr) { * * @return void */ - protected function process_regexp_separator_e(File $phpcsFile, $stackPtr) { + protected function processRegexpSeparatorE(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $token = $tokens[$stackPtr]; $text = trim($token['content'], " '\"\t\n"); @@ -113,28 +111,21 @@ protected function process_regexp_separator_e(File $phpcsFile, $stackPtr) { * * @return void */ - protected function process_string_with_backticks(File $phpcsFile, $stackPtr) { + protected function processStringWithBackticks(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $token = $tokens[$stackPtr]; $text = trim($token['content'], "'\""); if (strpos($text, '`') !== false) { //phpcs:ignore moodle.Strings.ForbiddenStrings.Found - // Exception. lang strings ending with _desc or _help can // contain backticks as they are correct Markdown formatting. // Look for previous string. - $prevString = $phpcsFile->findPrevious( - T_CONSTANT_ENCAPSED_STRING, - ($stackPtr - 1)); + $prevString = $phpcsFile->findPrevious(T_CONSTANT_ENCAPSED_STRING, ($stackPtr - 1)); if ($prevString) { $prevtext = trim($tokens[$prevString]['content'], "'\""); // Verify it matches _desc|_help. if (preg_match('/(_desc|_help)$/', $prevtext)) { // Verify it's an $string array element. - $prevToken = $phpcsFile->findPrevious( - T_OPEN_SQUARE_BRACKET, - ($prevString - 1), - null, - true); + $prevToken = $phpcsFile->findPrevious(T_OPEN_SQUARE_BRACKET, ($prevString - 1), null, true); if ($prevToken) { if ($tokens[$prevToken]['code'] === T_VARIABLE && $tokens[$prevToken]['content'] === '$string') { // Confirmed we are in a valid lang string using Markdown, skip any warning. diff --git a/moodle/Sniffs/WhiteSpace/SpaceAfterCommaSniff.php b/moodle/Sniffs/WhiteSpace/SpaceAfterCommaSniff.php index 56df6c9..3fd3d7b 100644 --- a/moodle/Sniffs/WhiteSpace/SpaceAfterCommaSniff.php +++ b/moodle/Sniffs/WhiteSpace/SpaceAfterCommaSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Verify there is a single space after a comma. * - * @package local_codechecker * @copyright 2011 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\WhiteSpace; @@ -27,9 +27,10 @@ use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; -class SpaceAfterCommaSniff implements Sniff { +class SpaceAfterCommaSniff implements Sniff +{ public function register() { - return array(T_COMMA); + return [T_COMMA]; } /** diff --git a/moodle/Sniffs/WhiteSpace/WhiteSpaceInStringsSniff.php b/moodle/Sniffs/WhiteSpace/WhiteSpaceInStringsSniff.php index acff03f..25177cd 100644 --- a/moodle/Sniffs/WhiteSpace/WhiteSpaceInStringsSniff.php +++ b/moodle/Sniffs/WhiteSpace/WhiteSpaceInStringsSniff.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . /** * Checks that each string does not have extra whitespace at end of line * - * @package local_codechecker * @copyright 2011 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodleHQ\MoodleCS\moodle\Sniffs\WhiteSpace; @@ -27,20 +27,20 @@ use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; -class WhiteSpaceInStringsSniff implements Sniff { - +class WhiteSpaceInStringsSniff implements Sniff +{ /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { - return array( - T_CONSTANT_ENCAPSED_STRING, - T_DOUBLE_QUOTED_STRING, - T_HEREDOC, - T_WHITESPACE - ); + return [ + T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING, + T_HEREDOC, + T_WHITESPACE, + ]; } /** diff --git a/moodle/Tests/FilesBoilerPlateCommentTest.php b/moodle/Tests/FilesBoilerPlateCommentTest.php index afddea0..e83f4e5 100644 --- a/moodle/Tests/FilesBoilerPlateCommentTest.php +++ b/moodle/Tests/FilesBoilerPlateCommentTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the BoilerplateCommentSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\BoilerplateCommentSniff */ -class FilesBoilerPlateCommentTest extends MoodleCSBaseTestCase { - - public function test_moodle_files_boilerplatecomment_ok() { +class FilesBoilerPlateCommentTest extends MoodleCSBaseTestCase +{ + public function testMoodleFilesBoilerplateCommentOk() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); $this->set_fixture(__DIR__ . '/fixtures/files/boilerplatecomment/ok.php'); @@ -53,7 +50,7 @@ public function test_moodle_files_boilerplatecomment_ok() { $this->verify_cs_results(); } - public function test_moodle_files_boilerplatecomment_nophp() { + public function testMoodleFilesBoilerplateCommentNoPHP() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); $this->set_fixture(__DIR__ . '/fixtures/files/boilerplatecomment/nophp.php'); @@ -66,7 +63,7 @@ public function test_moodle_files_boilerplatecomment_nophp() { $this->verify_cs_results(); } - public function test_moodle_files_boilerplatecomment_blank() { + public function testMoodleFilesBoilerplateCommentBlank() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); $this->set_fixture(__DIR__ . '/fixtures/files/boilerplatecomment/blank.php'); @@ -79,7 +76,7 @@ public function test_moodle_files_boilerplatecomment_blank() { $this->verify_cs_results(); } - public function test_moodle_files_boilerplatecomment_short() { + public function testMoodleFilesBoilerplateCommentShort() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); $this->set_fixture(__DIR__ . '/fixtures/files/boilerplatecomment/short.php'); @@ -92,7 +89,7 @@ public function test_moodle_files_boilerplatecomment_short() { $this->verify_cs_results(); } - public function test_moodle_files_boilerplatecomment_short_empty() { + public function testMoodleFilesBoilerplateCommentShortEmpty() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); $this->set_fixture(__DIR__ . '/fixtures/files/boilerplatecomment/short_empty.php'); @@ -105,7 +102,7 @@ public function test_moodle_files_boilerplatecomment_short_empty() { $this->verify_cs_results(); } - public function test_moodle_files_boilerplatecomment_wrongline() { + public function testMoodleFilesBoilerplateCommentWrongLine() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); $this->set_fixture(__DIR__ . '/fixtures/files/boilerplatecomment/wrongline.php'); @@ -119,7 +116,7 @@ public function test_moodle_files_boilerplatecomment_wrongline() { $this->verify_cs_results(); } - public function test_moodle_files_boilerplatecomment_gnu_http() { + public function testMoodleFilesBoilerplateCommentGnuHttp() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); @@ -134,7 +131,7 @@ public function test_moodle_files_boilerplatecomment_gnu_http() { /** * Assert that www.gnu.org can be referred to via https URL in the boilerplate. */ - public function test_moodle_files_boilerplatecomment_gnu_https() { + public function testMoodleFilesBoilerplateCommentGnuHttps() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.BoilerplateComment'); diff --git a/moodle/Tests/MoodleCSBaseTestCase.php b/moodle/Tests/MoodleCSBaseTestCase.php index 738eabd..0e3a118 100644 --- a/moodle/Tests/MoodleCSBaseTestCase.php +++ b/moodle/Tests/MoodleCSBaseTestCase.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; @@ -36,43 +37,41 @@ * * This file contains helper testcase for testing "moodle" CS Sniffs. * - * @category test - * @package MoodleHq\Moodle-Cs - * @copyright 2013 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2013 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -abstract class MoodleCSBaseTestCase extends \PHPUnit\Framework\TestCase { - +abstract class MoodleCSBaseTestCase extends \PHPUnit\Framework\TestCase +{ /** - * @var string name of the standard to be tested. + * @var string|null name of the standard to be tested. */ - protected $standard = null; + protected ?string $standard = null; /** - * @var string code of the sniff to be tested. Must be part of the standard definition. + * @var string|null code of the sniff to be tested. Must be part of the standard definition. * See {@see ::set_sniff()} for more information. */ - protected $sniff = null; + protected ?string $sniff = null; /** - * @var string full path to the file used as input (fixture). + * @var string|null full path to the file used as input (fixture). */ - protected $fixture = null; + protected ?string $fixture = null; /** * @var array custom config elements to setup before running phpcs. name => value. */ - protected $customConfigs = []; + protected array $customConfigs = []; /** - * @var array error expectations to ve verified against execution results. + * @var array|null error expectations to ve verified against execution results. */ - protected $errors = null; + protected ?array $errors = null; /** - * @var array warning expectations to ve verified against execution results. + * @var array|null warning expectations to ve verified against execution results. */ - protected $warnings = null; + protected ?array $warnings = null; public function tearDown(): void { \MoodleHQ\MoodleCS\moodle\Util\MoodleUtil::setMockedComponentMappings([]); @@ -143,7 +142,7 @@ protected function set_sniff($sniff) { */ protected function set_fixture($fixture) { if (!is_readable($fixture)) { - $this->fail('Unreadable fixture passed: '. $fixture); + $this->fail('Unreadable fixture passed: ' . $fixture); } $this->fixture = $fixture; } @@ -157,12 +156,12 @@ protected function set_errors(array $errors) { $this->errors = $errors; // Let's normalize numeric, empty and string errors. foreach ($this->errors as $line => $errordef) { - if (is_int($errordef) and $errordef > 0) { + if (is_int($errordef) && $errordef > 0) { $this->errors[$line] = array_fill(0, $errordef, $errordef); - } else if (empty($errordef)) { - $this->errors[$line] = array(); - } else if (is_string($errordef)) { - $this->errors[$line] = array($errordef); + } elseif (empty($errordef)) { + $this->errors[$line] = []; + } elseif (is_string($errordef)) { + $this->errors[$line] = [$errordef]; } } } @@ -190,12 +189,12 @@ protected function set_warnings(array $warnings) { $this->warnings = $warnings; // Let's normalize numeric, empty and string warnings. foreach ($this->warnings as $line => $warningdef) { - if (is_int($warningdef) and $warningdef > 0) { + if (is_int($warningdef) && $warningdef > 0) { $this->warnings[$line] = array_fill(0, $warningdef, $warningdef); - } else if (empty($warningdef)) { - $this->warnings[$line] = array(); - } else if (is_string($warningdef)) { - $this->warnings[$line] = array($warningdef); + } elseif (empty($warningdef)) { + $this->warnings[$line] = []; + } elseif (is_string($warningdef)) { + $this->warnings[$line] = [$warningdef]; } } } @@ -226,13 +225,13 @@ protected function setUp(): void { protected function verify_cs_results() { $config = new \PHP_CodeSniffer\Config(); $config->cache = false; - $config->standards = array($this->standard); - $config->sniffs = array($this->sniff); - $config->ignored = array(); + $config->standards = [$this->standard]; + $config->sniffs = [$this->sniff]; + $config->ignored = []; $ruleset = new \PHP_CodeSniffer\Ruleset($config); // We don't accept undefined errors and warnings. - if (is_null($this->errors) and is_null($this->warnings)) { + if (is_null($this->errors) && is_null($this->warnings)) { $this->fail('Error and warning expectations undefined. You must define at least one.'); } @@ -240,8 +239,8 @@ protected function verify_cs_results() { try { $phpcsfile = new \PHP_CodeSniffer\Files\LocalFile($this->fixture, $ruleset, $config); $phpcsfile->process(); - } catch (Exception $e) { - $this->fail('An unexpected exception has been caught: '. $e->getMessage()); + } catch (\Exception $e) { + $this->fail('An unexpected exception has been caught: ' . $e->getMessage()); } // Capture results. @@ -326,21 +325,30 @@ private function assert_results($expectations, $results, $type) { $info .= PHP_EOL . 'Actual: ' . json_encode($results[$line]); } // Verify counts for a line are the same. - $this->assertSame(count($expectation), $countresults, - 'Failed number of ' . $type . ' for line ' . $line . '.' . $info); + $this->assertSame( + count($expectation), + $countresults, + 'Failed number of ' . $type . ' for line ' . $line . '.' . $info + ); // Now verify every expectation requiring matching. foreach ($expectation as $key => $expectedcontent) { if (is_string($expectedcontent)) { - $this->assertStringContainsString($expectedcontent, $results[$line][$key], - 'Failed contents matching of ' . $type . ' for element ' . ($key + 1) . ' of line ' . $line . '.'); + $this->assertStringContainsString( + $expectedcontent, + $results[$line][$key], + 'Failed contents matching of ' . $type . ' for element ' . ($key + 1) . ' of line ' . $line . '.' + ); } } // Delete this line from results. unset($results[$line]); } // Ended looping, verify there aren't remaining results (errors, warnings). - $this->assertSame(array(), $results, - 'Failed to verify that all the ' . $type . ' have been defined by expectations.'); + $this->assertSame( + [], + $results, + 'Failed to verify that all the ' . $type . ' have been defined by expectations.' + ); } /** @@ -354,14 +362,14 @@ private function assert_results($expectations, $results, $type) { * @return array normalized array. */ private function normalize_cs_results($results) { - $normalized = array(); + $normalized = []; foreach ($results as $line => $lineerrors) { foreach ($lineerrors as $errors) { foreach ($errors as $error) { if (isset($normalized[$line])) { $normalized[$line][] = '@Message: ' . $error['message'] . ' @Source: ' . $error['source']; } else { - $normalized[$line] = array('@Message: ' . $error['message'] . ' @Source: ' . $error['source']); + $normalized[$line] = ['@Message: ' . $error['message'] . ' @Source: ' . $error['source']]; } } } diff --git a/moodle/Tests/MoodleStandardTest.php b/moodle/Tests/MoodleStandardTest.php index b4bcaf6..dca7433 100644 --- a/moodle/Tests/MoodleStandardTest.php +++ b/moodle/Tests/MoodleStandardTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test various "moodle" phpcs standard sniffs. * * Each case covers one sniff. Self-explanatory * - * @package local_codechecker - * @category test - * @copyright 2013 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2013 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @todo Complete coverage of all Sniffs. */ -class MoodleStandardTest extends MoodleCSBaseTestCase { - +class MoodleStandardTest extends MoodleCSBaseTestCase +{ /** * Test the PSR12.Functions.ReturnTypeDeclaration sniff. * * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions\ReturnTypeDeclarationSniff */ - public function test_psr12_functions_returntypedeclaration() { + public function testPSR12FunctionsReturnTypeDeclaration() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -66,7 +63,7 @@ public function test_psr12_functions_returntypedeclaration() { * * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions\NullableTypeDeclarationSniff */ - public function test_psr12_functions_nullabletypedeclaration() { + public function testPSR12FunctionsNullableTypeDeclaration() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -94,7 +91,7 @@ public function test_psr12_functions_nullabletypedeclaration() { * * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\MethodDeclarationSniff */ - public function test_psr2_methods_methoddeclaration() { + public function testPSR2MethodsMethodDeclaration() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -105,21 +102,22 @@ public function test_psr2_methods_methoddeclaration() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 33 => 'The static declaration must come after the visibility', 34 => 1, 35 => 1, 37 => 'The final declaration must precede the visibility', 38 => 1, 39 => 1, - 41 => array('FinalAfterVisibility', 'StaticBeforeVisibility'), + 41 => ['FinalAfterVisibility', 'StaticBeforeVisibility'], 42 => 2, 43 => 2, 45 => 'The abstract declaration must precede the visibility', 46 => 1, - 48 => array('AbstractAfterVisibility', 'StaticBeforeVisibility'), - 49 => 2)); - $this->set_warnings(array()); + 48 => ['AbstractAfterVisibility', 'StaticBeforeVisibility'], + 49 => 2, + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -130,7 +128,7 @@ public function test_psr2_methods_methoddeclaration() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Commenting\InlineCommentSniff */ - public function test_moodle_commenting_inlinecomment() { + public function testMoodleCommentingInlineComment() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -142,7 +140,7 @@ public function test_moodle_commenting_inlinecomment() { // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). $this->set_errors([ - 4 => array('3 slashes comments are not allowed'), + 4 => ['3 slashes comments are not allowed'], 6 => 1, 8 => 'No space found before comment text', 28 => 'Inline doc block comments are not allowed; use "// Comment." instead', @@ -169,15 +167,15 @@ public function test_moodle_commenting_inlinecomment() { ]); $this->set_warnings([ 4 => 0, - 6 => array(null, 'Commenting.InlineComment.InvalidEndChar'), - 55 => array('19 found'), - 57 => array('121 found'), - 59 => array('Found: (no)'), + 6 => [null, 'Commenting.InlineComment.InvalidEndChar'], + 55 => ['19 found'], + 57 => ['121 found'], + 59 => ['Found: (no)'], 61 => 1, 63 => 1, 65 => 1, 67 => 1, - 69 => array('WrongCommentCodeFoundBefore'), + 69 => ['WrongCommentCodeFoundBefore'], 71 => 3, 75 => 2, 77 => 1, @@ -200,7 +198,7 @@ public function test_moodle_commenting_inlinecomment() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Commenting\InlineCommentSniff */ - public function test_moodle_commenting_inlinecomment_js() { + public function testMoodleCommentingInlineCommentJS() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -211,14 +209,14 @@ public function test_moodle_commenting_inlinecomment_js() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( - 1 => array('3 slashes comments are not allowed'), + $this->set_errors([ + 1 => ['3 slashes comments are not allowed'], 3 => 1, 5 => 'No space found before comment text', - )); - $this->set_warnings(array( - 3 => array(null, 'Commenting.InlineComment.InvalidEndChar'), - )); + ]); + $this->set_warnings([ + 3 => [null, 'Commenting.InlineComment.InvalidEndChar'], + ]); // Let's do all the hard work! $this->verify_cs_results(); @@ -229,7 +227,7 @@ public function test_moodle_commenting_inlinecomment_js() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\ControlStructures\ControlSignatureSniff */ - public function test_moodle_controlstructures_controlsignature() { + public function testMoodleControlStructuresControlsignature() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -240,12 +238,13 @@ public function test_moodle_controlstructures_controlsignature() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 3 => 0, - 4 => array('found "if(...) {'), + 4 => ['found "if(...) {'], 5 => 0, - 6 => '@Message: Expected "} else {\n"')); - $this->set_warnings(array()); + 6 => '@Message: Expected "} else {\n"', + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -256,7 +255,7 @@ public function test_moodle_controlstructures_controlsignature() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\LineLengthSniff */ - public function test_moodle_files_linelength() { + public function testMoodleFilesLineLength() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -267,14 +266,16 @@ public function test_moodle_files_linelength() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 21 => 'maximum limit of 180 characters; contains 181 characters', - 22 => 'maximum limit of 180 characters; contains 181 characters')); - $this->set_warnings(array( + 22 => 'maximum limit of 180 characters; contains 181 characters', + ]); + $this->set_warnings([ 13 => 'exceeds 132 characters; contains 133 characters', 14 => 'exceeds 132 characters; contains 133 characters', 17 => 'exceeds 132 characters; contains 180 characters', - 18 => 'exceeds 132 characters; contains 180 characters')); + 18 => 'exceeds 132 characters; contains 180 characters', + ]); // Let's do all the hard work! $this->verify_cs_results(); @@ -285,7 +286,7 @@ public function test_moodle_files_linelength() { * * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays\DisallowLongArraySyntaxSniff */ - public function test_generic_array_disallowlongarraysyntax(): void { + public function testGenericArraysDisallowLongArraySyntax(): void { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); $this->set_sniff('Generic.Arrays.DisallowLongArraySyntax'); @@ -301,7 +302,7 @@ public function test_generic_array_disallowlongarraysyntax(): void { 9 => 'Short array syntax must be used to define arrays @Source: Generic.Arrays.DisallowLongArraySyntax.Found', ]); - $this->set_warnings(array()); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -312,7 +313,7 @@ public function test_generic_array_disallowlongarraysyntax(): void { * * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineEndingsSniff */ - public function test_generic_files_lineendings() { + public function testGeneriFilesLineEndings() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -323,10 +324,11 @@ public function test_generic_files_lineendings() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( - 1 => 'line character is invalid; expected "\n" but found "\r\n" @Source: Generic.Files.LineEndings.InvalidEOLChar')); + $this->set_errors([ + 1 => 'line character is invalid; expected "\n" but found "\r\n" @Source: Generic.Files.LineEndings.InvalidEOLChar', + ]); - $this->set_warnings(array()); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -337,7 +339,7 @@ public function test_generic_files_lineendings() { * * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\Files\EndFileNewlineSniff */ - public function test_generic_files_endfilenewline() { + public function testGenericFilesEndFileNewLine() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -348,10 +350,11 @@ public function test_generic_files_endfilenewline() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( - 4 => 'File must end with a newline character @Source: Generic.Files.EndFileNewline.NotFound')); + $this->set_errors([ + 4 => 'File must end with a newline character @Source: Generic.Files.EndFileNewline.NotFound', + ]); - $this->set_warnings(array()); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -362,7 +365,7 @@ public function test_generic_files_endfilenewline() { * * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\Whitespace\DisallowTabIndentSniff */ - public function test_generic_whitespace_disalowtabindent() { + public function testGenericWhiteSpaceDisalowTabIndent() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -373,12 +376,13 @@ public function test_generic_whitespace_disalowtabindent() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 9 => 'Spaces must be used to indent lines; tabs are not allowed', 10 => 1, - 11 => 1)); + 11 => 1, + ]); - $this->set_warnings(array()); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -389,7 +393,7 @@ public function test_generic_whitespace_disalowtabindent() { * * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\Functions\OpeningFunctionBraceKernighanRitchieSniff */ - public function test_generic_functions_openingfunctionbracekerninghanritchie() { + public function testGenericFunctionsOpeningFunctionBraceKernighanRitchie() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -400,7 +404,7 @@ public function test_generic_functions_openingfunctionbracekerninghanritchie() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 6 => 'Expected 1 space before opening brace; found 0', 9 => 1, 12 => 'Expected 1 space before opening brace; found 3', @@ -408,9 +412,9 @@ public function test_generic_functions_openingfunctionbracekerninghanritchie() { 20 => 'Expected 1 space before opening brace; found 0', 23 => 1, 26 => 'Expected 1 space before opening brace; found 3', - 29 => 1)); + 29 => 1]); - $this->set_warnings(array()); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -421,7 +425,7 @@ public function test_generic_functions_openingfunctionbracekerninghanritchie() { * * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\Classes\OpeningBraceSameLineSniff */ - public function test_generic_classes_openingclassbrace() { + public function testGenericClassesOpeningBraceSameLine() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -451,7 +455,7 @@ public function test_generic_classes_openingclassbrace() { * * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff */ - public function test_generic_whitespace_scopeindent() { + public function testGenericWhiteSpaceScopeIndent() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -462,12 +466,12 @@ public function test_generic_whitespace_scopeindent() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 7 => 'indented incorrectly; expected at least 4 spaces, found 2 @Source: Generic.WhiteSpace.ScopeIndent.Incorrect', 19 => 'indented incorrectly; expected at least 4 spaces, found 2 @Source: Generic.WhiteSpace.ScopeIndent.Incorrect', 44 => 'expected at least 8 spaces', - )); - $this->set_warnings(array()); + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -478,7 +482,7 @@ public function test_generic_whitespace_scopeindent() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHP\DeprecatedFunctionsSniff */ - public function test_moodle_php_deprecatedfunctions() { + public function testMoodlePHPDeprecatedFunctions() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -489,8 +493,8 @@ public function test_moodle_php_deprecatedfunctions() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array()); - $warnings = array(7 => 'print_error() has been deprecated; use throw new moodle_exception()'); + $this->set_errors([]); + $warnings = [7 => 'print_error() has been deprecated; use throw new moodle_exception()']; if (PHP_VERSION_ID >= 70300 && PHP_VERSION_ID < 80000) { $warnings[10] = 'mbsplit() has been deprecated'; } @@ -505,7 +509,7 @@ public function test_moodle_php_deprecatedfunctions() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHP\ForbiddenFunctionsSniff */ - public function test_moodle_php_forbiddenfunctions() { + public function testMoodlePHPForbiddenFunctions() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -516,7 +520,7 @@ public function test_moodle_php_forbiddenfunctions() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 5 => 'function sizeof() is forbidden; use count()', 6 => 1, 8 => 1, @@ -527,8 +531,8 @@ public function test_moodle_php_forbiddenfunctions() { 15 => 0, 16 => 0, 17 => 0, - )); - $this->set_warnings(array()); + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -539,7 +543,7 @@ public function test_moodle_php_forbiddenfunctions() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHP\ForbiddenGlobalUseSniff */ - public function test_moodle_php_forbidden_global_use() { + public function testMoodlePHPForbiddenGlobalUse() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); $this->set_sniff('moodle.PHP.ForbiddenGlobalUse'); @@ -623,7 +627,7 @@ public function test_moodle_php_forbidden_global_use() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHP\ForbiddenTokensSniff */ - public function test_moodle_php_forbiddentokens() { + public function testMoodlePHPForbiddenTokens() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -634,13 +638,13 @@ public function test_moodle_php_forbiddentokens() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 5 => 'The use of function eval() is forbidden', 6 => 'The use of operator goto is forbidden', 8 => 'The use of goto labels is forbidden', 11 => 1, - 13 => array('backticks', 'backticks'))); - $this->set_warnings(array()); + 13 => ['backticks', 'backticks']]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -651,7 +655,7 @@ public function test_moodle_php_forbiddentokens() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Strings\ForbiddenStringsSniff */ - public function test_moodle_strings_forbiddenstrings() { + public function testMoodleStringsForbiddenStrings() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -662,7 +666,7 @@ public function test_moodle_strings_forbiddenstrings() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 8 => 'The use of the AS keyword to alias tables is bad for cross-db', 10 => 1, 11 => 'The use of the AS keyword to alias tables is bad for cross-db', @@ -673,13 +677,13 @@ public function test_moodle_strings_forbiddenstrings() { 16 => (version_compare(PHP_VERSION, '7.3.0', '<') ? 1 : 0), 23 => (version_compare(PHP_VERSION, '7.3.0', '<') ? 2 : 1), 26 => 0, - 27 => 0)); - $this->set_warnings(array( - 19 => array('backticks in strings is not recommended'), + 27 => 0]); + $this->set_warnings([ + 19 => ['backticks in strings is not recommended'], 20 => 1, 23 => 1, 36 => 'backticks in strings', - 37 => 1)); + 37 => 1]); // Let's do all the hard work! $this->verify_cs_results(); @@ -690,7 +694,7 @@ public function test_moodle_strings_forbiddenstrings() { * * @covers \PHPCompatibility\Sniffs\FunctionUse\RemovedFunctionsSniff */ - public function test_phpcompatibility_php_deprecatedfunctions() { + public function testPHPCompatibilityFunctionUseRemovedFunctions() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -701,10 +705,10 @@ public function test_phpcompatibility_php_deprecatedfunctions() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( - 5 => array('Function ereg_replace', 'Use call_user_func() instead', '@Source: PHPCompat') - )); - $this->set_warnings(array()); + $this->set_errors([ + 5 => ['Function ereg_replace', 'Use call_user_func() instead', '@Source: PHPCompat'], + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -715,7 +719,7 @@ public function test_phpcompatibility_php_deprecatedfunctions() { * * @covers \PHPCompatibility\Sniffs\Syntax\ForbiddenCallTimePassByReferenceSniff */ - public function test_phpcompatibility_php_forbiddencalltimepassbyreference() { + public function testPHPCompatibilitySyntaxForbiddenCallTimePassByReference() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -726,10 +730,10 @@ public function test_phpcompatibility_php_forbiddencalltimepassbyreference() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( - 6 => array('call-time pass-by-reference is deprecated'), - 7 => array('@Source: PHPCompat'))); - $this->set_warnings(array()); + $this->set_errors([ + 6 => ['call-time pass-by-reference is deprecated'], + 7 => ['@Source: PHPCompat']]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -740,7 +744,7 @@ public function test_phpcompatibility_php_forbiddencalltimepassbyreference() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\NamingConventions\ValidVariableNameSniff */ - public function test_moodle_namingconventions_variablename() { + public function testMoodleNamingConventionsValidVariableName() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -751,24 +755,24 @@ public function test_moodle_namingconventions_variablename() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 4 => 'must not contain underscores', 5 => 'must be all lower-case', 6 => 'must not contain underscores', - 7 => array('must be all lower-case', 'must not contain underscores'), + 7 => ['must be all lower-case', 'must not contain underscores'], 8 => 0, 9 => 0, 12 => 'must not contain underscores', 13 => 'must be all lower-case', - 14 => array('must be all lower-case', 'must not contain underscores'), + 14 => ['must be all lower-case', 'must not contain underscores'], 15 => 0, 16 => 0, 17 => 'The \'var\' keyword is not permitted', 20 => 'must be all lower-case', 21 => 2, - 22 => array('must be all lower-case', 'must not contain underscores'), - )); - $this->set_warnings(array()); + 22 => ['must be all lower-case', 'must not contain underscores'], + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -779,7 +783,7 @@ public function test_moodle_namingconventions_variablename() { * * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff */ - public function test_squiz_operator_spacing() { + public function testSquizWhiteSpaceOperatorSpacing() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -790,18 +794,18 @@ public function test_squiz_operator_spacing() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 6 => 0, 7 => 'Expected 1 space before', 8 => 'Expected 1 space after', - 9 => array('Expected 1 space before', 'Expected 1 space after'), + 9 => ['Expected 1 space before', 'Expected 1 space after'], 10 => 0, 11 => 'Expected 1 space after "=>"; 3 found', 12 => 0, 13 => 0, 14 => 'Expected 1 space before', 15 => 'Expected 1 space after', - 16 => array('Expected 1 space before', 'Expected 1 space after'), + 16 => ['Expected 1 space before', 'Expected 1 space after'], 17 => 0, 18 => 'Expected 1 space after "="; 2 found', 19 => 0, @@ -809,28 +813,28 @@ public function test_squiz_operator_spacing() { 21 => 0, 22 => 'Expected 1 space before', 23 => 'Expected 1 space after', - 24 => array('Expected 1 space before', 'Expected 1 space after'), + 24 => ['Expected 1 space before', 'Expected 1 space after'], 25 => 0, 26 => 'Expected 1 space after "+"; 2 found', 27 => 'Expected 1 space before "+"; 2 found', 28 => 0, 29 => 'Expected 1 space before', 30 => 'Expected 1 space after', - 31 => array('Expected 1 space before', 'Expected 1 space after'), + 31 => ['Expected 1 space before', 'Expected 1 space after'], 32 => 0, 33 => 'Expected 1 space after "-"; 2 found', 34 => 'Expected 1 space before "-"; 2 found', 35 => 0, 36 => 'Expected 1 space before', 37 => 'Expected 1 space after', - 38 => array('Expected 1 space before', 'Expected 1 space after'), + 38 => ['Expected 1 space before', 'Expected 1 space after'], 39 => 0, 40 => 'Expected 1 space after "*"; 2 found', 41 => 'Expected 1 space before "*"; 2 found', 42 => 0, 43 => 'Expected 1 space before', 44 => 'Expected 1 space after', - 45 => array('Expected 1 space before', 'Expected 1 space after'), + 45 => ['Expected 1 space before', 'Expected 1 space after'], 46 => 0, 47 => 'Expected 1 space after "/"; 2 found', 48 => 'Expected 1 space before "/"; 2 found', @@ -848,9 +852,9 @@ public function test_squiz_operator_spacing() { 60 => 0, 61 => 0, 62 => 0, - 63 => 0 - )); - $this->set_warnings(array()); + 63 => 0, + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -861,7 +865,7 @@ public function test_squiz_operator_spacing() { * * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ObjectOperatorSpacingSniff */ - public function test_squiz_object_operator_spacing() { + public function testSquizWhiteSpaceObjectOperatorSpacing() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -872,8 +876,8 @@ public function test_squiz_object_operator_spacing() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array()); - $this->set_warnings(array()); + $this->set_errors([]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -884,7 +888,7 @@ public function test_squiz_object_operator_spacing() { * * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ObjectOperatorIndentSniff */ - public function test_pear_object_operator_indent() { + public function testPEARWhiteSpaceObjectOperatorIndent() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -895,7 +899,7 @@ public function test_pear_object_operator_indent() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array( + $this->set_errors([ 40 => 'not indented correctly; expected 4 spaces but found 2', 41 => '@Source: PEAR.WhiteSpace.ObjectOperatorIndent.Incorrect', 44 => 1, @@ -910,8 +914,8 @@ public function test_pear_object_operator_indent() { 66 => 1, 69 => 1, 70 => 1, - )); - $this->set_warnings(array()); + ]); + $this->set_warnings([]); // Let's do all the hard work! $this->verify_cs_results(); @@ -922,7 +926,7 @@ public function test_pear_object_operator_indent() { * * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\CommentedOutCodeSniff */ - public function test_squid_php_commentedoutcode() { + public function testSquizPHPCommentedOutCode() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); @@ -933,11 +937,11 @@ public function test_squid_php_commentedoutcode() { // - line => number of problems, or // - line => array of contents for message / source problem matching. // - line => string of contents for message / source problem matching (only 1). - $this->set_errors(array()); - $this->set_warnings(array( + $this->set_errors([]); + $this->set_warnings([ 5 => 'This comment is 72% valid code; is this commented out code', - 9 => '@Source: Squiz.PHP.CommentedOutCode.Found' - )); + 9 => '@Source: Squiz.PHP.CommentedOutCode.Found', + ]); // Let's do all the hard work! $this->verify_cs_results(); @@ -948,15 +952,15 @@ public function test_squid_php_commentedoutcode() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\RequireLoginSniff */ - public function test_moodle_files_requirelogin_problem() { + public function testMoodleFilesRequireLoginProblem() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.RequireLogin'); $this->set_fixture(__DIR__ . '/fixtures/moodle_files_requirelogin/problem.php'); - $this->set_errors(array()); - $this->set_warnings(array( - 25 => ', require_course_login, require_admin, admin_externalpage_setup) following config inclusion. None found' - )); + $this->set_errors([]); + $this->set_warnings([ + 25 => ', require_course_login, require_admin, admin_externalpage_setup) following config inclusion. None found', + ]); $this->verify_cs_results(); } @@ -966,13 +970,13 @@ public function test_moodle_files_requirelogin_problem() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\RequireLoginSniff */ - public function test_moodle_files_requirelogin_require_login_ok() { + public function testMoodleFilesRequireLoginOk() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.RequireLogin'); $this->set_fixture(__DIR__ . '/fixtures/moodle_files_requirelogin/require_login_ok.php'); - $this->set_errors(array()); - $this->set_warnings(array()); + $this->set_errors([]); + $this->set_warnings([]); $this->verify_cs_results(); } @@ -982,13 +986,13 @@ public function test_moodle_files_requirelogin_require_login_ok() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\RequireLoginSniff */ - public function test_moodle_files_requirelogin_require_course_login_ok() { + public function testMoodleFilesRequireLoginCourseOk() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.RequireLogin'); $this->set_fixture(__DIR__ . '/fixtures/moodle_files_requirelogin/require_course_login_ok.php'); - $this->set_errors(array()); - $this->set_warnings(array()); + $this->set_errors([]); + $this->set_warnings([]); $this->verify_cs_results(); } @@ -998,13 +1002,13 @@ public function test_moodle_files_requirelogin_require_course_login_ok() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\RequireLoginSniff */ - public function test_moodle_files_requirelogin_admin_externalpage_setup_ok() { + public function testMoodleFilesRequireLoginAdminExtenalPageOk() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.RequireLogin'); $this->set_fixture(__DIR__ . '/fixtures/moodle_files_requirelogin/admin_externalpage_setup_ok.php'); - $this->set_errors(array()); - $this->set_warnings(array()); + $this->set_errors([]); + $this->set_warnings([]); $this->verify_cs_results(); } @@ -1014,13 +1018,13 @@ public function test_moodle_files_requirelogin_admin_externalpage_setup_ok() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\RequireLoginSniff */ - public function test_moodle_files_requirelogin_cliscript_ok() { + public function testMoodleFilesRequireLoginCLIScriptOk() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.RequireLogin'); $this->set_fixture(__DIR__ . '/fixtures/moodle_files_requirelogin/cliscript_ok.php'); - $this->set_errors(array()); - $this->set_warnings(array()); + $this->set_errors([]); + $this->set_warnings([]); $this->verify_cs_results(); } @@ -1030,13 +1034,13 @@ public function test_moodle_files_requirelogin_cliscript_ok() { * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\RequireLoginSniff */ - public function test_moodle_files_requirelogin_nomoodlecookies_ok() { + public function testMoodleFilesRequireLoginNoMoodlCookiesOk() { $this->set_standard('moodle'); $this->set_sniff('moodle.Files.RequireLogin'); $this->set_fixture(__DIR__ . '/fixtures/moodle_files_requirelogin/nomoodlecookies_ok.php'); - $this->set_errors(array()); - $this->set_warnings(array()); + $this->set_errors([]); + $this->set_warnings([]); $this->verify_cs_results(); } diff --git a/moodle/Tests/NamingConventionsValidFunctionNameTest.php b/moodle/Tests/NamingConventionsValidFunctionNameTest.php index 501830c..c0588a3 100644 --- a/moodle/Tests/NamingConventionsValidFunctionNameTest.php +++ b/moodle/Tests/NamingConventionsValidFunctionNameTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; -// phpcs:disable moodle.NamingConventions - /** * Test the ValidFunctionName sniff. * - * @package local_codechecker - * @category test - * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\NamingConventions\ValidFunctionNameSniff */ -class NamingConventionsValidFunctionNameTest extends MoodleCSBaseTestCase { - +class NamingConventionsValidFunctionNameTest extends MoodleCSBaseTestCase +{ /** - * Data provider for self::test_namingconventions_validfunctionname + * Data provider for self::testNamingConventionsValidFunctionName */ - public function provider_namingconventions_validfunctionname() { + public function providerNamingConventionsValidFunctionName() { return [ 'Correct' => [ 'fixture' => 'fixtures/namingconventions/validfunctionname_correct.php', @@ -76,9 +73,9 @@ public function provider_namingconventions_validfunctionname() { * @param string $fixture relative path to fixture to use. * @param array $errors array of errors expected. * @param array $warnings array of warnings expected. - * @dataProvider provider_namingconventions_validfunctionname + * @dataProvider providerNamingConventionsValidFunctionName */ - public function test_namingconventions_validfunctionname(string $fixture, array $errors, array $warnings) { + public function testNamingConventionsValidFunctionName(string $fixture, array $errors, array $warnings) { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); diff --git a/moodle/Tests/NormalizedArraysArraysCommaAfterLastTest.php b/moodle/Tests/NormalizedArraysArraysCommaAfterLastTest.php index 7ab7254..d07a469 100644 --- a/moodle/Tests/NormalizedArraysArraysCommaAfterLastTest.php +++ b/moodle/Tests/NormalizedArraysArraysCommaAfterLastTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the \PHPCSExtra\NormalizedArrays\Sniffs\Arrays\CommaAfterLastSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2023 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2023 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \PHPCSExtra\NormalizedArrays\Sniffs\Arrays\CommaAfterLastSniff */ diff --git a/moodle/Tests/PHPIncludingFileTest.php b/moodle/Tests/PHPIncludingFileTest.php index 641f1a9..fa5000f 100644 --- a/moodle/Tests/PHPIncludingFileTest.php +++ b/moodle/Tests/PHPIncludingFileTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the IncludingFile sniff. * - * @package local_codechecker - * @category test - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHP\IncludingFileSniff */ -class PHPIncludingFileTest extends MoodleCSBaseTestCase { - - public function test_php_includingfile() { +class PHPIncludingFileTest extends MoodleCSBaseTestCase +{ + public function testPHPIncludingFile() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); $this->set_sniff('moodle.PHP.IncludingFile'); diff --git a/moodle/Tests/PHPMemberVarScopeTest.php b/moodle/Tests/PHPMemberVarScopeTest.php index 9becd59..e946c20 100644 --- a/moodle/Tests/PHPMemberVarScopeTest.php +++ b/moodle/Tests/PHPMemberVarScopeTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the IncludingFile sniff. * - * @package local_codechecker - * @category test - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHP\MemberVarScopeSniff */ -class PHPMemberVarScopeTest extends MoodleCSBaseTestCase { - - public function test_php_membervarscope() { +class PHPMemberVarScopeTest extends MoodleCSBaseTestCase +{ + public function testPHPMemberVarScope() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); $this->set_sniff('moodle.PHP.MemberVarScope'); diff --git a/moodle/Tests/PHPUnitTestCaseCoversTest.php b/moodle/Tests/PHPUnitTestCaseCoversTest.php index 67434b1..1da6ba5 100644 --- a/moodle/Tests/PHPUnitTestCaseCoversTest.php +++ b/moodle/Tests/PHPUnitTestCaseCoversTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; -// phpcs:disable moodle.NamingConventions - /** * Test the TestCaseCoversSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit\TestCaseCoversSniff */ -class PHPUnitTestCaseCoversTest extends MoodleCSBaseTestCase { - +class PHPUnitTestCaseCoversTest extends MoodleCSBaseTestCase +{ /** - * Data provider for self::test_phpunit_testcasecovers + * Data provider for self::testPHPUnitTestCaseCovers */ - public function provider_phpunit_testcasecovers() { + public function phpunitTestCaseCoversProvider() { return [ 'Correct' => [ 'fixture' => 'fixtures/phpunit/testcasecovers_correct.php', @@ -124,9 +121,9 @@ public function provider_phpunit_testcasecovers() { * @param string $fixture relative path to fixture to use. * @param array $errors array of errors expected. * @param array $warnings array of warnings expected. - * @dataProvider provider_phpunit_testcasecovers + * @dataProvider phpunitTestCaseCoversProvider */ - public function test_phpunit_testcasecovers(string $fixture, array $errors, array $warnings) { + public function testPHPUnitTestCaseCovers(string $fixture, array $errors, array $warnings) { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); diff --git a/moodle/Tests/PHPUnitTestCaseNamesTest.php b/moodle/Tests/PHPUnitTestCaseNamesTest.php index 191519e..4c5d449 100644 --- a/moodle/Tests/PHPUnitTestCaseNamesTest.php +++ b/moodle/Tests/PHPUnitTestCaseNamesTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; - -// phpcs:disable moodle.NamingConventions - /** * Test the TestCaseNamesSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit\TestCaseNamesSniff */ -class PHPUnitTestCaseNamesTest extends MoodleCSBaseTestCase { - +class PHPUnitTestCaseNamesTest extends MoodleCSBaseTestCase +{ /** - * Data provider for self::test_phpunit_testcasenames + * Data provider for self::testPHPUnitTestCaseNamesProvider */ - public function provider_phpunit_testcasenames() { + public function phpunitTestCaseNamesProvider() { return [ 'Missing' => [ 'fixture' => 'fixtures/phpunit/testcasenames_missing.php', @@ -78,7 +73,7 @@ public function provider_phpunit_testcasenames() { 8 => 1, ], 'warnings' => [ - 2 => 'does not match its expected location at "tests/level2/level3"' + 2 => 'does not match its expected location at "tests/level2/level3"', ], ], 'CorrectLevel2NS' => [ @@ -126,7 +121,7 @@ public function provider_phpunit_testcasenames() { ], ], 'warnings' => [ - 7 => 1 + 7 => 1, ], ], 'ExistsProposed' => [ @@ -138,7 +133,7 @@ public function provider_phpunit_testcasenames() { ], ], 'warnings' => [ - 7 => 1 + 7 => 1, ], ], ]; @@ -150,10 +145,10 @@ public function provider_phpunit_testcasenames() { * @param string $fixture relative path to fixture to use. * @param array $errors array of errors expected. * @param array $warnings array of warnings expected. - * @dataProvider provider_phpunit_testcasenames + * @dataProvider phpunitTestCaseNamesProvider * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit\TestCaseNamesSniff */ - public function test_phpunit_testcasenames(string $fixture, array $errors, array $warnings) { + public function testPHPUnitTestCaseNames(string $fixture, array $errors, array $warnings) { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); $this->set_sniff('moodle.PHPUnit.TestCaseNames'); diff --git a/moodle/Tests/PHPUnitTestCaseProviderTest.php b/moodle/Tests/PHPUnitTestCaseProviderTest.php index 059ee47..2edcde7 100644 --- a/moodle/Tests/PHPUnitTestCaseProviderTest.php +++ b/moodle/Tests/PHPUnitTestCaseProviderTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -use MoodleHQ\MoodleCS\moodle\Util\MoodleUtil; - -// phpcs:disable moodle.NamingConventions - /** * Test the TestCaseCoversSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit\TestCaseProviderSniff */ -class PHPUnitTestCaseProviderTest extends MoodleCSBaseTestCase { - +class PHPUnitTestCaseProviderTest extends MoodleCSBaseTestCase +{ /** - * Data provider for self::test_phpunit_test_providers + * Data provider for self::testPHPUnitTestCaseProvider */ - public function provider_phpunit_data_providers() { + public function phpunitTestCaseProviderProvider() { return [ 'Correct' => [ 'fixture' => 'fixtures/phpunit/provider/correct_test.php', @@ -135,9 +130,9 @@ public function provider_phpunit_data_providers() { * @param string $fixture relative path to fixture to use. * @param array $errors array of errors expected. * @param array $warnings array of warnings expected. - * @dataProvider provider_phpunit_data_providers + * @dataProvider phpunitTestCaseProviderProvider */ - public function test_phpunit_test_providers( + public function testPHPUnitTestCaseProvider( string $fixture, array $errors, array $warnings diff --git a/moodle/Tests/PHPUnitTestReturnTypeTest.php b/moodle/Tests/PHPUnitTestReturnTypeTest.php index b937f9e..eadfe69 100644 --- a/moodle/Tests/PHPUnitTestReturnTypeTest.php +++ b/moodle/Tests/PHPUnitTestReturnTypeTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the PHPUnitTestReturnTypeSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit\TestReturnTypeSniff */ -class PHPUnitTestReturnTypeTest extends MoodleCSBaseTestCase { - +class PHPUnitTestReturnTypeTest extends MoodleCSBaseTestCase +{ /** - * Data provider for self::provider_phpunit_data_returntypes + * Data provider for self::testPHPUnitTestReturnType */ - public function provider_phpunit_data_returntypes(): array { + public function providerPHPUnitTestReturnType(): array { return [ 'Provider Casing' => [ 'fixture' => 'fixtures/phpunit/TestReturnType/returntypes.php', @@ -50,14 +47,14 @@ public function provider_phpunit_data_returntypes(): array { } /** - * Test the moodle.PHPUnit.TestCaseCovers sniff + * Test the moodle.PHPUnit.TestReturnType sniff * * @param string $fixture relative path to fixture to use. * @param array $errors array of errors expected. * @param array $warnings array of warnings expected. - * @dataProvider provider_phpunit_data_returntypes + * @dataProvider providerPHPUnitTestReturnType */ - public function test_phpunit_test_returntypes( + public function testPHPUnitTestReturnType( string $fixture, array $errors, array $warnings diff --git a/moodle/Tests/Sniffs/Commenting/CategorySniffTest.php b/moodle/Tests/Sniffs/Commenting/CategorySniffTest.php index 029fd29..96b93a9 100644 --- a/moodle/Tests/Sniffs/Commenting/CategorySniffTest.php +++ b/moodle/Tests/Sniffs/Commenting/CategorySniffTest.php @@ -1,4 +1,5 @@ * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @@ -34,7 +32,7 @@ class CategorySniffTest extends MoodleCSBaseTestCase /** * @dataProvider provider */ - public function test_category_correctness( + public function testCategoryCorrectness( string $fixture, array $errors, array $warnings diff --git a/moodle/Tests/Sniffs/Commenting/InlineCommentSniffTest.php b/moodle/Tests/Sniffs/Commenting/InlineCommentSniffTest.php index 6ac6dd8..8e68a54 100644 --- a/moodle/Tests/Sniffs/Commenting/InlineCommentSniffTest.php +++ b/moodle/Tests/Sniffs/Commenting/InlineCommentSniffTest.php @@ -1,4 +1,5 @@ * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * diff --git a/moodle/Tests/Sniffs/Commenting/PackageSniffTest.php b/moodle/Tests/Sniffs/Commenting/PackageSniffTest.php index c4ee0ff..2e23112 100644 --- a/moodle/Tests/Sniffs/Commenting/PackageSniffTest.php +++ b/moodle/Tests/Sniffs/Commenting/PackageSniffTest.php @@ -1,4 +1,5 @@ * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @@ -31,11 +29,10 @@ */ class PackageSniffTest extends MoodleCSBaseTestCase { - /** - * @dataProvider package_correctness_provider + * @dataProvider packageCorrectnessProvider */ - public function test_package_correctness( + public function testPackageCorrectness( string $fixture, array $errors, array $warnings @@ -52,7 +49,7 @@ public function test_package_correctness( $this->verify_cs_results(); } - public static function package_correctness_provider(): array { + public static function packageCorrectnessProvider(): array { return [ 'Standard fixes' => [ 'fixture' => 'package_tags', @@ -61,8 +58,8 @@ public static function package_correctness_provider(): array { 31 => 'DocBlock missing a @package tag for class package_absent. Expected @package local_codechecker', 34 => 'Missing doc comment for function missing_docblock_in_function', 38 => 'Missing doc comment for class missing_docblock_in_class', - 42 => 'Incorrect @package tag for function package_wrong_in_function. Expected local_codechecker, found wrong_package.', - 48 => 'Incorrect @package tag for class package_wrong_in_class. Expected local_codechecker, found wrong_package.', + 42 => '@package tag for function package_wrong_in_function. Expected local_codechecker, found wrong_package.', + 48 => '@package tag for class package_wrong_in_class. Expected local_codechecker, found wrong_package.', 57 => 'More than one @package tag found in function package_multiple_in_function', 64 => 'More than one @package tag found in class package_multiple_in_class', 71 => 'More than one @package tag found in function package_multiple_in_function_all_wrong', @@ -70,11 +67,11 @@ public static function package_correctness_provider(): array { 85 => 'More than one @package tag found in interface package_multiple_in_interface_all_wrong', 92 => 'More than one @package tag found in trait package_multiple_in_trait_all_wrong', 95 => 'Missing doc comment for interface missing_docblock_interface', - 101 => 'DocBlock missing a @package tag for interface missing_package_interface. Expected @package local_codechecker', - 106 => 'Incorrect @package tag for interface incorrect_package_interface. Expected local_codechecker, found local_codecheckers.', + 101 => 'missing a @package tag for interface missing_package_interface. Expected @package', + 106 => '@package tag for interface incorrect_package_interface. Expected local_codechecker, found', 118 => 'Missing doc comment for trait missing_docblock_trait', - 124 => 'DocBlock missing a @package tag for trait missing_package_trait. Expected @package local_codechecker', - 129 => 'Incorrect @package tag for trait incorrect_package_trait. Expected local_codechecker, found local_codecheckers.', + 124 => 'DocBlock missing a @package tag for trait missing_package_trait. Expected @package', + 129 => 'Incorrect @package tag for trait incorrect_package_trait. Expected local_codechecker, found', ], 'warnings' => [], ], diff --git a/moodle/Tests/Sniffs/Commenting/TodoCommentSniffTest.php b/moodle/Tests/Sniffs/Commenting/TodoCommentSniffTest.php index 613f455..a2dd6e7 100644 --- a/moodle/Tests/Sniffs/Commenting/TodoCommentSniffTest.php +++ b/moodle/Tests/Sniffs/Commenting/TodoCommentSniffTest.php @@ -1,4 +1,5 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests\Files; -// phpcs:disable moodle.NamingConventions - /** * Test the MoodleInternalSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2013 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2013 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Files\MoodleInternalSniff */ -class MoodleInternalTest extends \MoodleHQ\MoodleCS\moodle\Tests\MoodleCSBaseTestCase { +class MoodleInternalTest extends \MoodleHQ\MoodleCS\moodle\Tests\MoodleCSBaseTestCase +{ /** * @dataProvider provider */ diff --git a/moodle/Tests/Sniffs/Methods/MethodDeclarationSpacingSniffTest.php b/moodle/Tests/Sniffs/Methods/MethodDeclarationSpacingSniffTest.php index 365cd10..68cff74 100644 --- a/moodle/Tests/Sniffs/Methods/MethodDeclarationSpacingSniffTest.php +++ b/moodle/Tests/Sniffs/Methods/MethodDeclarationSpacingSniffTest.php @@ -1,4 +1,5 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests\Sniffs\Namespaces; use MoodleHQ\MoodleCS\moodle\Tests\MoodleCSBaseTestCase; -// phpcs:disable moodle.NamingConventions - /** * Test the NoLeadingSlash sniff. * - * @package moodle-cs - * @category test * @copyright 2023 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\Namespaces\NamespaceStatementSniff */ class NamespaceStatementSniffTest extends MoodleCSBaseTestCase { - public static function leading_slash_provider(): array + public static function leadingSlashProvider(): array { return [ [ @@ -57,14 +54,13 @@ public static function leading_slash_provider(): array ]; } /** - * @dataProvider leading_slash_provider + * @dataProvider leadingSlashProvider */ - public function test_leading_slash( + public function testLeadingSlash( string $fixture, array $warnings, array $errors - ): void - { + ): void { $this->set_standard('moodle'); $this->set_sniff('moodle.Namespaces.NamespaceStatement'); $this->set_fixture(sprintf("%s/fixtures/%s.php", __DIR__, $fixture)); diff --git a/moodle/Tests/Sniffs/PHPUnit/TestCasesAbstractSniffTest.php b/moodle/Tests/Sniffs/PHPUnit/TestCasesAbstractSniffTest.php index bbdf095..f70fca4 100644 --- a/moodle/Tests/Sniffs/PHPUnit/TestCasesAbstractSniffTest.php +++ b/moodle/Tests/Sniffs/PHPUnit/TestCasesAbstractSniffTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Tests\MoodleCSBaseTestCase; /** * Test the TestCasesAbstractSniff sniff. * * @copyright 2024 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit\TestCasesAbstractSniff */ -class TestCasesAbstractSniffTest extends MoodleCSBaseTestCase { - +class TestCasesAbstractSniffTest extends MoodleCSBaseTestCase +{ /** - * Data provider for self::provider_phpunit_data_returntypes + * Data provider for self::testPHPUnitTestCasesAbstract */ - public static function phpunit_classes_final_provider(): array { + public static function phpunitTestCasesAbstractProvider(): array { return [ 'Standard fixes' => [ 'fixture' => 'testcaseclassesabstract', @@ -47,9 +46,9 @@ public static function phpunit_classes_final_provider(): array { } /** - * @dataProvider phpunit_classes_final_provider + * @dataProvider phpunitTestCasesAbstractProvider */ - public function test_phpunit_classes_final( + public function testPHPUnitTestCasesAbstract( string $fixture, array $errors, array $warnings diff --git a/moodle/Tests/Sniffs/PHPUnit/TestClassesFinalSniffTest.php b/moodle/Tests/Sniffs/PHPUnit/TestClassesFinalSniffTest.php index 03c8acd..8d16ffd 100644 --- a/moodle/Tests/Sniffs/PHPUnit/TestClassesFinalSniffTest.php +++ b/moodle/Tests/Sniffs/PHPUnit/TestClassesFinalSniffTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests\Sniffs\PHPUnit; -// phpcs:disable moodle.NamingConventions - use MoodleHQ\MoodleCS\moodle\Tests\MoodleCSBaseTestCase; /** * Test the TestClassesFinalSniff sniff. * * @copyright 2024 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\PHPUnit\TestClassesFinalSniff */ -class TestclassesFinalSniffTest extends MoodleCSBaseTestCase { - +class TestclassesFinalSniffTest extends MoodleCSBaseTestCase +{ /** - * Data provider for self::provider_phpunit_data_returntypes + * Data provider for self::testPHPUnitClassesFinal */ - public static function phpunit_classes_final_provider(): array { + public static function phpunitClassesFinalProvider(): array { return [ 'Standard fixes' => [ 'fixture' => 'testclassesfinal', 'errors' => [ ], 'warnings' => [ - 15 => 'Unit test example_abstract_test_with_abstract_children_test should be declared as final and not abstract.', - 19 => 'Unit test example_abstract_test should be declared as final and not abstract.', - 23 => 'Unit test example_standard_test should be declared as final.', + 15 => 'example_abstract_test_with_abstract_children_test should be declared as final and not abstract.', + 19 => 'example_abstract_test should be declared as final and not abstract.', + 23 => 'example_standard_test should be declared as final.', ], ], ]; } /** - * @dataProvider phpunit_classes_final_provider + * @dataProvider phpunitClassesFinalProvider */ - public function test_phpunit_classes_final( + public function testPHPUnitClassesFinal( string $fixture, array $errors, array $warnings diff --git a/moodle/Tests/SquizArraysArrayBrackerSpacingTest.php b/moodle/Tests/SquizArraysArrayBrackerSpacingTest.php index 5731d18..43ff79a 100644 --- a/moodle/Tests/SquizArraysArrayBrackerSpacingTest.php +++ b/moodle/Tests/SquizArraysArrayBrackerSpacingTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayBracketSpacingSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayBracketSpacingSniff */ -class SquizArraysArrayBrackerSpacingTest extends MoodleCSBaseTestCase { - +class SquizArraysArrayBrackerSpacingTest extends MoodleCSBaseTestCase +{ /** * Test the Squid.Arrays.ArrayBracketSpacing sniff */ - public function test_squiz_arrays_arraybracketspacing() { + public function testSquizArrayaArrayBracketSpacing() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); diff --git a/moodle/Tests/SquizOperatorsValidLogicalOperatorsTest.php b/moodle/Tests/SquizOperatorsValidLogicalOperatorsTest.php index 82d2c46..df27269 100644 --- a/moodle/Tests/SquizOperatorsValidLogicalOperatorsTest.php +++ b/moodle/Tests/SquizOperatorsValidLogicalOperatorsTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators\ValidLogicalOperatorsSniff sniff. * - * @package local_codechecker - * @category test - * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2022 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators\ValidLogicalOperatorsSniff */ -class SquizOperatorsValidLogicalOperatorsTest extends MoodleCSBaseTestCase { - +class SquizOperatorsValidLogicalOperatorsTest extends MoodleCSBaseTestCase +{ /** - * Test the Squid.Arrays.ValidLogicalOperators sniff + * Test the Squid.Operators.ValidLogicalOperators sniff */ - public function test_squiz_operators_validlogicaloperators() { + public function testSquizOperatorsValidLogicalOperators() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); diff --git a/moodle/Tests/Util/DocblocksTest.php b/moodle/Tests/Util/DocblocksTest.php index 3de1d86..193fe36 100644 --- a/moodle/Tests/Util/DocblocksTest.php +++ b/moodle/Tests/Util/DocblocksTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests\Util; @@ -21,19 +22,16 @@ use PHP_CodeSniffer\Config; use PHP_CodeSniffer\Ruleset; -// phpcs:disable moodle.NamingConventions - /** * Test the Docblocks specific moodle utilities class * - * @package local_codechecker - * @category test - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Util\Docblocks */ -class DocblocksTest extends MoodleCSBaseTestCase { +class DocblocksTest extends MoodleCSBaseTestCase +{ public function testGetDocBlock(): void { $phpcsConfig = new Config(); $phpcsRuleset = new Ruleset($phpcsConfig); diff --git a/moodle/Tests/Util/MoodleUtilTest.php b/moodle/Tests/Util/MoodleUtilTest.php index 1cb19ac..e3877bb 100644 --- a/moodle/Tests/Util/MoodleUtilTest.php +++ b/moodle/Tests/Util/MoodleUtilTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests\Util; @@ -25,20 +26,16 @@ use org\bovigo\vfs\vfsStream; use PHPCSUtils\Utils\ObjectDeclarations; -// phpcs:disable moodle.NamingConventions - /** * Test the MoodleUtil specific moodle utilities class * - * @package local_codechecker - * @category test - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Util\MoodleUtil */ -class MoodleUtilTest extends MoodleCSBaseTestCase { - +class MoodleUtilTest extends MoodleCSBaseTestCase +{ /** * Unit test for calculateAllComponents. * @@ -46,21 +43,21 @@ class MoodleUtilTest extends MoodleCSBaseTestCase { * and it's already indirectly tested by {@see test_getMoodleComponent()} * but it has some feature that we need to test individually here. */ - public function test_calculateAllComponents() { + public function testCalculateAllComponents() { // Let's calculate moodleRoot. $vfs = vfsStream::setup('root', null, []); $moodleRoot = $vfs->url(); // Let's prepare a components file, with some correct and incorrect entries. $components = - "nonono,mod_forum,{$moodleRoot}/mod_forum\n" . // Wrong type. - "plugin,mod__nono,{$moodleRoot}/mod_forum\n" . // Wrong component. - "plugin,mod_forum,/no/no/no/no//mod_forum\n" . // Wrong path. - "plugin,local_codechecker,{$moodleRoot}/local/codechecker\n" .// All ok. - "plugin,mod_forum,{$moodleRoot}/mod/forum\n"; // All ok. + "nonono,mod_forum,{$moodleRoot}/mod_forum\n" . // Wrong type. + "plugin,mod__nono,{$moodleRoot}/mod_forum\n" . // Wrong component. + "plugin,mod_forum,/no/no/no/no//mod_forum\n" . // Wrong path. + "plugin,local_codechecker,{$moodleRoot}/local/codechecker\n" . // All ok. + "plugin,mod_forum,{$moodleRoot}/mod/forum\n"; // All ok. vfsStream::create( - ['components.txt' => $components,], + ['components.txt' => $components], $vfs ); @@ -78,10 +75,16 @@ public function test_calculateAllComponents() { $loadedComponents = $property->getValue(); $this->assertCount(2, $loadedComponents); - $this->assertSame(['mod_forum', 'local_codechecker'], - array_keys($loadedComponents)); // Verify they are ordered in ascending order. - $this->assertSame(["{$moodleRoot}/mod/forum", "{$moodleRoot}/local/codechecker"], - array_values($loadedComponents)); // Verify component paths are also the expected ones. + // Verify they are ordered in ascending order. + $this->assertSame( + ['mod_forum', 'local_codechecker'], + array_keys($loadedComponents) + ); + // Verify component paths are also the expected ones. + $this->assertSame( + ["{$moodleRoot}/mod/forum", "{$moodleRoot}/local/codechecker"], + array_values($loadedComponents) + ); // Now be evil and try with an unreadable file, it must throw an exception. @@ -162,7 +165,7 @@ public function getMoodleComponentProvider() { * * @dataProvider getMoodleComponentProvider */ - public function test_getMoodleComponent( + public function testGetMoodleComponent( array $config, array $return, bool $reset = true, @@ -205,8 +208,7 @@ public function test_getMoodleComponent( $this->assertInstanceOf($return['exception'], $e); $this->assertStringContainsString($return['message'], $e->getMessage()); } - - } else if (array_key_exists('value', $return)) { + } elseif (array_key_exists('value', $return)) { // Normal asserting result. $this->assertSame($return['value'], MoodleUtil::getMoodleComponent($file, $selfPath)); } @@ -276,7 +278,7 @@ public function getMoodleBranchProvider() { * * @dataProvider getMoodleBranchProvider */ - public function test_getMoodleBranch(array $config, array $return, bool $reset = true, bool $selfPath = true) { + public function testGetMoodleBranch(array $config, array $return, bool $reset = true, bool $selfPath = true) { $file = null; // Set config options when passed. if ($config) { @@ -301,8 +303,7 @@ public function test_getMoodleBranch(array $config, array $return, bool $reset = $this->assertInstanceOf($return['exception'], $e); $this->assertStringContainsString($return['message'], $e->getMessage()); } - - } else if (array_key_exists('value', $return)) { + } elseif (array_key_exists('value', $return)) { // Normal asserting result. $this->assertSame($return['value'], MoodleUtil::getMoodleBranch($file, $selfPath)); } @@ -385,7 +386,7 @@ public function getMoodleRootProvider() { * * @dataProvider getMoodleRootProvider */ - public function test_getMoodleRoot( + public function testGetMoodleRoot( array $config, array $return, bool $requireMockMoodle = false, @@ -433,8 +434,7 @@ public function test_getMoodleRoot( $this->assertInstanceOf($return['exception'], $e); $this->assertStringContainsString($return['message'], $e->getMessage()); } - - } else if (array_key_exists('value', $return)) { + } elseif (array_key_exists('value', $return)) { // Normal asserting result. $this->assertSame($return['value'], MoodleUtil::getMoodleRoot($file), $selfPath); } @@ -533,8 +533,7 @@ public static function isUnitTestProvider(): array public function testIsUnitTest( string $filepath, bool $expected - ): void - { + ): void { $phpcsConfig = new Config(); $phpcsRuleset = new Ruleset($phpcsConfig); $file = new File($filepath, $phpcsRuleset, $phpcsConfig); @@ -589,8 +588,7 @@ public function testIsUnitTestCaseClass( string $filepath, string $testClassName, bool $expected - ): void - { + ): void { $phpcsConfig = new Config(); $phpcsRuleset = new Ruleset($phpcsConfig); @@ -655,15 +653,14 @@ public static function meetsMinimumMoodleVersionProvider(): array /** * @dataProvider meetsMinimumMoodleVersionProvider * @param string|int $moodleVersion - * @param int $minversion + * @param int $minVersion * @param array $return */ public function testMeetsMinimumMoodleVersion( $moodleVersion, int $minVersion, array $return - ): void - { + ): void { Config::setConfigData('moodleBranch', $moodleVersion, true); $phpcsConfig = new Config(); @@ -678,7 +675,7 @@ public function testMeetsMinimumMoodleVersion( $this->assertInstanceOf($return['exception'], $e); $this->assertStringContainsString($return['message'], $e->getMessage()); } - } else if (array_key_exists('value', $return)) { + } elseif (array_key_exists('value', $return)) { // Normal asserting result. $this->assertSame($return['value'], MoodleUtil::meetsMinimumMoodleVersion($file, $minVersion)); } @@ -730,8 +727,7 @@ public static function findClassMethodPointerProvider(): array public function testFindClassMethodPointer( string $methodName, bool $found - ): void - { + ): void { $phpcsConfig = new Config(); $phpcsRuleset = new Ruleset($phpcsConfig); $phpcsFile = new \PHP_CodeSniffer\Files\LocalFile( @@ -756,8 +752,7 @@ public function testFindClassMethodPointer( } } - public function testGetTokensOnLine(): void - { + public function testGetTokensOnLine(): void { $phpcsConfig = new Config(); $phpcsRuleset = new Ruleset($phpcsConfig); $phpcsFile = new \PHP_CodeSniffer\Files\LocalFile( @@ -809,7 +804,7 @@ public function testGetMoodleApis(): void { $apis, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ), - 'example.php' => '' + 'example.php' => '', ], ], $vfs @@ -856,7 +851,7 @@ public function testGetMoodleApisInvalidJson(): void { [ 'lib' => [ 'apis.json' => 'invalid:"json"', - 'example.php' => '' + 'example.php' => '', ], ], $vfs @@ -901,7 +896,7 @@ public function testGetMoodleApisNotAMoodle(): void { $apis, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ), - 'example.php' => '' + 'example.php' => '', ], ], $vfs @@ -940,7 +935,7 @@ public function testGetMoodleApisMocked(): void { [ 'lib' => [ 'apis.json' => json_encode([]), - 'example.php' => '' + 'example.php' => '', ], ], $vfs diff --git a/moodle/Tests/WhiteSpaceSpaceAfterCommaTest.php b/moodle/Tests/WhiteSpaceSpaceAfterCommaTest.php index 83fee62..3a8f873 100644 --- a/moodle/Tests/WhiteSpaceSpaceAfterCommaTest.php +++ b/moodle/Tests/WhiteSpaceSpaceAfterCommaTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the SpaceAfterComma sniff. * - * @package local_codechecker - * @category test - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\WhiteSpace\SpaceAfterCommaSniff */ -class WhiteSpaceSpaceAfterCommaTest extends MoodleCSBaseTestCase { - - public function test_whitespace_spaceaftercomma() { +class WhiteSpaceSpaceAfterCommaTest extends MoodleCSBaseTestCase +{ + public function testWhitespaceSpaceAfterComma() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); $this->set_sniff('moodle.WhiteSpace.SpaceAfterComma'); diff --git a/moodle/Tests/WhiteSpaceWhiteSpaceInStringsTest.php b/moodle/Tests/WhiteSpaceWhiteSpaceInStringsTest.php index 7c0fb69..b7ab990 100644 --- a/moodle/Tests/WhiteSpaceWhiteSpaceInStringsTest.php +++ b/moodle/Tests/WhiteSpaceWhiteSpaceInStringsTest.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Tests; -// phpcs:disable moodle.NamingConventions - /** * Test the WhiteSpaceInStrings sniff. * - * @package local_codechecker - * @category test - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @covers \MoodleHQ\MoodleCS\moodle\Sniffs\WhiteSpace\WhiteSpaceInStringsSniff */ -class WhiteSpaceWhiteSpaceInStringsTest extends MoodleCSBaseTestCase { - - public function test_whitespace_whitespaceinstrings() { +class WhiteSpaceWhiteSpaceInStringsTest extends MoodleCSBaseTestCase +{ + public function testWhiteSpaceWhiteSpaceInStrings() { // Define the standard, sniff and fixture to use. $this->set_standard('moodle'); $this->set_sniff('moodle.WhiteSpace.WhiteSpaceInStrings'); diff --git a/moodle/Tests/bootstrap.php b/moodle/Tests/bootstrap.php index 85081c2..1274ebb 100644 --- a/moodle/Tests/bootstrap.php +++ b/moodle/Tests/bootstrap.php @@ -1,12 +1,12 @@ - */ diff --git a/moodle/Util/Docblocks.php b/moodle/Util/Docblocks.php index 1bf55bd..129f74b 100644 --- a/moodle/Util/Docblocks.php +++ b/moodle/Util/Docblocks.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Util; @@ -22,16 +23,14 @@ use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Ruleset; -// phpcs:disable moodle.NamingConventions - /** * Utilities related to PHP DocBlocks. * - * @package local_codechecker * @copyright 2024 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -abstract class Docblocks { +abstract class Docblocks +{ /** * Get the docblock for a file, class, interface, trait, or method. * @@ -56,9 +55,9 @@ public static function getDocBlock( ]; if ($token['code'] === T_DOC_COMMENT_OPEN_TAG) { return $token; - } else if ($token['code'] === T_DOC_COMMENT_CLOSE_TAG) { + } elseif ($token['code'] === T_DOC_COMMENT_CLOSE_TAG) { return $tokens[$token['comment_opener']]; - } else if (in_array($token['code'], $midDocBlockTokens)) { + } elseif (in_array($token['code'], $midDocBlockTokens)) { $commentStart = $phpcsFile->findPrevious(T_DOC_COMMENT_OPEN_TAG, $stackPtr); return $commentStart ? $tokens[$commentStart] : null; } diff --git a/moodle/Util/MoodleUtil.php b/moodle/Util/MoodleUtil.php index 6b7d47d..563c28f 100644 --- a/moodle/Util/MoodleUtil.php +++ b/moodle/Util/MoodleUtil.php @@ -1,5 +1,6 @@ . +// along with Moodle. If not, see . namespace MoodleHQ\MoodleCS\moodle\Util; @@ -22,17 +23,14 @@ use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Ruleset; -// phpcs:disable moodle.NamingConventions - /** * Various utility methods specific to Moodle stuff. * - * @package local_codechecker - * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright 2021 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com} + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -abstract class MoodleUtil { - +abstract class MoodleUtil +{ /** * @var string Absolute path, cached, containing moodle root detected directory. */ @@ -139,7 +137,9 @@ protected static function calculateAllComponents(string $moodleRoot): ?array { if ($componentsFile = Config::getConfigData('moodleComponentsListPath')) { if (!is_readable($componentsFile)) { throw new DeepExitException( - "ERROR: Incorrect 'moodleComponentsListPath' config/runtime option. File not found: '$componentsFile'", 3); + "ERROR: Incorrect 'moodleComponentsListPath' config/runtime option. File not found: '$componentsFile'", + 3 + ); } // Go processing the file. $handle = fopen($componentsFile, "r"); @@ -328,11 +328,15 @@ public static function getMoodleBranch(?File $file = null, bool $selfPath = true // Verify it's integer value and <= 9999 (4 digits max). if (filter_var($branch, FILTER_VALIDATE_INT) === false) { throw new DeepExitException( - "ERROR: Incorrect 'moodleBranch' config/runtime option. Value in not an integer: '$branch'", 3); + "ERROR: Incorrect 'moodleBranch' config/runtime option. Value in not an integer: '$branch'", + 3 + ); } if ($branch > 9999) { throw new DeepExitException( - "ERROR: Incorrect 'moodleBranch' config/runtime option. Value must be 4 digit max.: '$branch'", 3); + "ERROR: Incorrect 'moodleBranch' config/runtime option. Value must be 4 digit max.: '$branch'", + 3 + ); } self::$moodleBranch = $branch; return self::$moodleBranch; @@ -388,12 +392,16 @@ public static function getMoodleRoot(?File $file = null, bool $selfPath = true): // Verify the path is exists and is readable. if (!is_dir($path) || !is_readable($path)) { throw new DeepExitException( - "ERROR: Incorrect 'moodleRoot' config/runtime option. Directory does not exist or is not readable: '$path'", 3); + "ERROR: Incorrect 'moodleRoot' config/runtime option. Directory does not exist or is not readable: '$path'", + 3 + ); } // Verify the path has version.php and config-dist.php files. Very basic, but effective check. if (!is_readable($path . '/version.php') || !is_readable($path . '/config-dist.php')) { throw new DeepExitException( - "ERROR: Incorrect 'moodleRoot' config/runtime option. Directory is not a valid moodle root: '$path'", 3); + "ERROR: Incorrect 'moodleRoot' config/runtime option. Directory is not a valid moodle root: '$path'", + 3 + ); } self::$moodleRoot = $path; return self::$moodleRoot; @@ -441,8 +449,8 @@ public static function getMoodleRoot(?File $file = null, bool $selfPath = true): * * Any file which is not correctly named will be ignored. * - * @param File $phpcsFile - * @return bool + * @param File $phpcsFile + * @return bool */ public static function isUnitTest(File $phpcsFile): bool { @@ -527,8 +535,7 @@ public static function isUnitTestCaseClass( public static function meetsMinimumMoodleVersion( File $phpcsFile, int $version - ): ?bool - { + ): ?bool { $moodleBranch = self::getMoodleBranch($phpcsFile); if (!isset($moodleBranch)) { // We cannot determine the moodle branch, so we cannot determine if the version is met. @@ -550,8 +557,7 @@ public static function findClassMethodPointer( File $phpcsFile, int $classPtr, string $methodName - ): ?int - { + ): ?int { $mStart = $classPtr; $tokens = $phpcsFile->getTokens(); while ($mStart = $phpcsFile->findNext(T_FUNCTION, $mStart + 1, $tokens[$classPtr]['scope_closer'])) {