Skip to content

Commit

Permalink
Added Function Length Sniff
Browse files Browse the repository at this point in the history
  • Loading branch information
bmitch committed Dec 3, 2016
1 parent 4546de8 commit 0d4500b
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Codor/Sniffs/Files/FunctionLengthSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Codor\Sniffs\Files;

use PHP_CodeSniffer_Sniff;
use PHP_CodeSniffer_File;

class FunctionLengthSniff implements PHP_CodeSniffer_Sniff
{

protected $maxLength = 20;

public function register()
{
return [T_FUNCTION];
}

public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->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)));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

function someFunctionLongerThan21Lines()
{




















}

function someFunctionLessThan21Lines()
{

}

class SomeClass
{
public function someMethodLongerThan21Lines()
{




















}

public function someMethodLessThan21Lines()
{

}
}
22 changes: 22 additions & 0 deletions tests/Sniffs/Files/FunctionLengthSniffTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Codor\Tests\Sniffs\ControlStructures;

use Codor\Tests\CodeSnifferRunner;
use PHPUnit\Framework\TestCase;

/** @group Files */
class FunctionLengthSniffTest extends TestCase
{
/** @test */
public function it_detects_functions_that_are_over_the_max_allowed()
{
$codeSnifferRunner = new CodeSnifferRunner();
$errorCount = $codeSnifferRunner->detectErrorCountInFileForSniff(
__DIR__.'/Assets/FunctionLengthSniff/FunctionLengthSniff.inc',
'Codor.Files.FunctionLength'
);

$this->assertSame(2, $errorCount);
}
}

0 comments on commit 0d4500b

Please sign in to comment.