Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Function Length Sniff #8

Merged
merged 1 commit into from
Dec 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}