Skip to content

Commit 2150b9b

Browse files
committed
feat: Only allow actions as public controller functions
1 parent a948ff5 commit 2150b9b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Markup\Sniffs\Symfony;
4+
5+
use SlevomatCodingStandard\Helpers\FunctionHelper;
6+
7+
class ControllerPublicMethodNamesSniff implements \PHP_CodeSniffer\Sniffs\Sniff
8+
{
9+
private const CONTROLLER_NAMESPACE = '/Controller/';
10+
private const CONTROLLER_FILE_SUFFIX = 'Controller.php';
11+
/**
12+
* @return mixed[]
13+
*/
14+
public function register()
15+
{
16+
return [
17+
T_FUNCTION,
18+
];
19+
}
20+
21+
/**
22+
* @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint
23+
* @param \PHP_CodeSniffer\Files\File $phpcsFile
24+
* @param int $openTagPointer
25+
*/
26+
public function process(\PHP_CodeSniffer\Files\File $phpcsFile, $openTagPointer)
27+
{
28+
if (stripos($phpcsFile->getFilename(), self::CONTROLLER_NAMESPACE) === false) {
29+
return;
30+
}
31+
32+
if (stripos($phpcsFile->getFilename(), self::CONTROLLER_FILE_SUFFIX) === false) {
33+
return;
34+
}
35+
36+
if (!FunctionHelper::isMethod($phpcsFile, $openTagPointer)) {
37+
return;
38+
}
39+
40+
$name = FunctionHelper::getName($phpcsFile, $openTagPointer);
41+
42+
try {
43+
$properties = $phpcsFile->getMethodProperties($openTagPointer);
44+
45+
if (!isset($properties['scope']) || $properties['scope'] !== 'public') {
46+
return;
47+
}
48+
} catch (\Throwable $e) {
49+
return;
50+
}
51+
52+
if (in_array($name, ['__construct', '__invoke'])) {
53+
return;
54+
}
55+
56+
if (substr($name, -6) !== 'Action') {
57+
$phpcsFile->addError(
58+
sprintf(
59+
'Controller public function name(%s) must end in *Action ', $name
60+
),
61+
$openTagPointer,
62+
'SymfonyControllerPublicMethodName'
63+
);
64+
}
65+
}
66+
67+
}

0 commit comments

Comments
 (0)