From 0d4500bfeee239ebfc0f5ba494df2c7532caf311 Mon Sep 17 00:00:00 2001 From: Bill Mitchell Date: Sat, 3 Dec 2016 21:51:07 +0000 Subject: [PATCH] Added Function Length Sniff --- .../Sniffs/Files/FunctionLengthSniff.php | 38 ++++++++++++ .../FunctionLengthSniff.inc | 62 +++++++++++++++++++ .../Sniffs/Files/FunctionLengthSniffTest.php | 22 +++++++ 3 files changed, 122 insertions(+) create mode 100644 src/Codor/Sniffs/Files/FunctionLengthSniff.php create mode 100644 tests/Sniffs/Files/Assets/FunctionLengthSniff/FunctionLengthSniff.inc create mode 100644 tests/Sniffs/Files/FunctionLengthSniffTest.php diff --git a/src/Codor/Sniffs/Files/FunctionLengthSniff.php b/src/Codor/Sniffs/Files/FunctionLengthSniff.php new file mode 100644 index 0000000..1e56028 --- /dev/null +++ b/src/Codor/Sniffs/Files/FunctionLengthSniff.php @@ -0,0 +1,38 @@ +getTokens(); + $token = $tokens[$stackPtr]; + + // Skip function without body. + if (isset($token['scope_opener']) === false) { + return 0; + } + + $firstToken = $tokens[$token['scope_opener']]; + $lastToken = $tokens[$token['scope_closer']]; + $length = $lastToken['line'] - $firstToken['line']; + + if ($length > $this->maxLength) { + $tokenType = strtolower(substr($token['type'], 2)); + $error = "Function is {$length} lines. Must be {$this->maxLength} lines or fewer."; + $phpcsFile->addError($error, $stackPtr, sprintf('%sTooBig', ucfirst($tokenType))); + } + } +} diff --git a/tests/Sniffs/Files/Assets/FunctionLengthSniff/FunctionLengthSniff.inc b/tests/Sniffs/Files/Assets/FunctionLengthSniff/FunctionLengthSniff.inc new file mode 100644 index 0000000..3fd20db --- /dev/null +++ b/tests/Sniffs/Files/Assets/FunctionLengthSniff/FunctionLengthSniff.inc @@ -0,0 +1,62 @@ +detectErrorCountInFileForSniff( + __DIR__.'/Assets/FunctionLengthSniff/FunctionLengthSniff.inc', + 'Codor.Files.FunctionLength' + ); + + $this->assertSame(2, $errorCount); + } +} \ No newline at end of file