diff --git a/composer.json b/composer.json index 804d1b5..014dccc 100644 --- a/composer.json +++ b/composer.json @@ -35,7 +35,7 @@ "larapack/dd": "^1.1" }, "scripts": { - "test": [ + "code-standards": [ "vendor/bin/parallel-lint src tests", "vendor/bin/phpcs --standard=psr2 src -sp", "vendor/bin/phpcs --standard=phpcs.xml src tests --ignore=tests/Sniffs -sp", diff --git a/src/Codor/Sniffs/Files/ForbiddenMethodsSniff.php b/src/Codor/Sniffs/Files/ForbiddenMethodsSniff.php new file mode 100644 index 0000000..782f2f7 --- /dev/null +++ b/src/Codor/Sniffs/Files/ForbiddenMethodsSniff.php @@ -0,0 +1,48 @@ +getTokens(); + $potentialMethodToken = $tokens[$stackPtr + 1]; + $openParenToken = $tokens[$stackPtr + 2]; + + if ($openParenToken['type'] !== 'T_OPEN_PARENTHESIS') { + return; + } + + $methodName = $potentialMethodToken['content']; + if (in_array($methodName, $this->forbiddenMethods, true)) { + $phpcsFile->addError("Call to method {$methodName} is forbidden.", $potentialMethodToken['line']); + } + } +} diff --git a/tests/Sniffs/Files/Assets/ForbiddenMethodsSniff/CallingForbiddenMethods.inc b/tests/Sniffs/Files/Assets/ForbiddenMethodsSniff/CallingForbiddenMethods.inc new file mode 100644 index 0000000..a437101 --- /dev/null +++ b/tests/Sniffs/Files/Assets/ForbiddenMethodsSniff/CallingForbiddenMethods.inc @@ -0,0 +1,5 @@ +raw(); +$foo->statement(); \ No newline at end of file diff --git a/tests/Sniffs/Files/Assets/ForbiddenMethodsSniff/CallingForbiddenMethodsStatic.inc b/tests/Sniffs/Files/Assets/ForbiddenMethodsSniff/CallingForbiddenMethodsStatic.inc new file mode 100644 index 0000000..a7bb52e --- /dev/null +++ b/tests/Sniffs/Files/Assets/ForbiddenMethodsSniff/CallingForbiddenMethodsStatic.inc @@ -0,0 +1,4 @@ +runner->setSniff('Codor.Files.ForbiddenMethods')->setFolder(__DIR__.'/Assets/ForbiddenMethodsSniff/'); + } + + /** @test */ + public function it_produces_errors_for_each_forbidden_method_call_found() + { + $results = $this->runner->sniff('CallingForbiddenMethods.inc'); + $this->assertSame(2, $results->getErrorCount()); + $this->assertSame(0, $results->getWarningCount()); + + $errorMessages = $results->getAllErrorMessages(); + $this->assertCount(2, $errorMessages); + $this->assertSame('Call to method raw is forbidden.', $errorMessages[0]); + $this->assertSame('Call to method statement is forbidden.', $errorMessages[1]); + } + + /** @test */ + public function it_produces_errors_for_each_forbidden_method_static_call_found() + { + $results = $this->runner->sniff('CallingForbiddenMethodsStatic.inc'); + $this->assertSame(2, $results->getErrorCount()); + $this->assertSame(0, $results->getWarningCount()); + + $errorMessages = $results->getAllErrorMessages(); + $this->assertCount(2, $errorMessages); + $this->assertSame('Call to method raw is forbidden.', $errorMessages[0]); + $this->assertSame('Call to method statement is forbidden.', $errorMessages[1]); + } +}