Skip to content

Commit f34c6c8

Browse files
committed
feat: enforce return types on controllers
1 parent 4886dde commit f34c6c8

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Markup\Sniffs\Next;
4+
5+
use SlevomatCodingStandard\Helpers\FunctionHelper;
6+
7+
class ControllerActionReturnTypesSniff 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'])) {
53+
return;
54+
}
55+
56+
$returnType = FunctionHelper::findReturnTypeHint($phpcsFile, $openTagPointer);
57+
58+
if (!$returnType) {
59+
$phpcsFile->addError(
60+
sprintf(
61+
'Controller action(%s) must have a return type ', $name
62+
),
63+
$openTagPointer,
64+
'SymfonyControllerActionReturnType'
65+
);
66+
67+
return;
68+
}
69+
70+
if (stripos($returnType->getTypeHint(), 'Response') === false) {
71+
$phpcsFile->addError(
72+
sprintf(
73+
'Controller action(%s) must have a response return type ', $name
74+
),
75+
$openTagPointer,
76+
'SymfonyControllerActionReturnType'
77+
);
78+
}
79+
}
80+
81+
}

0 commit comments

Comments
 (0)