7
7
use PHP_CodeSniffer \Files \File ;
8
8
use PHP_CodeSniffer \Sniffs \Sniff ;
9
9
use PHP_CodeSniffer \Util \Common ;
10
- use PHP_CodeSniffer \Util \Tokens ;
11
10
use SymfonyCustom \Helpers \SniffHelper ;
12
11
13
12
/**
14
13
* Throws errors if scalar type name are not valid.
15
14
*/
16
15
class ValidScalarTypeNameSniff implements Sniff
17
16
{
17
+ private const TYPING = '\\\\a-z0-9 ' ;
18
+ private const OPENER = '\<\[\{\( ' ;
19
+ private const CLOSER = '\>\]\}\) ' ;
20
+ private const MIDDLE = '\,\:\&\| ' ;
21
+
18
22
/**
19
23
* @return array
20
24
*/
@@ -33,7 +37,11 @@ public function process(File $phpcsFile, $stackPtr): void
33
37
34
38
if (in_array ($ tokens [$ stackPtr ]['content ' ], SniffHelper::TAGS_WITH_TYPE )) {
35
39
preg_match (
36
- '`^((?:\|?(?:array\([^\)]*\)|[ \\\\a-z0-9\[\<\,\>\]]+))*)( .*)?`i ' ,
40
+ '`^((?: '
41
+ .'[ ' .self ::OPENER .self ::MIDDLE .']\s* '
42
+ .'|(?:[ ' .self ::TYPING .self ::CLOSER .']\s+)(?=[\| ' .self ::OPENER .self ::MIDDLE .self ::CLOSER .']) '
43
+ .'|[ ' .self ::TYPING .self ::CLOSER .'] '
44
+ .')+)(.*)?`i ' ,
37
45
$ tokens [($ stackPtr + 2 )]['content ' ],
38
46
$ match
39
47
);
@@ -44,17 +52,7 @@ public function process(File $phpcsFile, $stackPtr): void
44
52
45
53
// Check type (can be multiple, separated by '|').
46
54
$ type = $ match [1 ];
47
- $ typeNames = explode ('| ' , $ type );
48
- $ suggestedNames = [];
49
- foreach ($ typeNames as $ i => $ typeName ) {
50
- $ suggestedName = $ this ->getValidTypeName ($ typeName );
51
-
52
- if (in_array ($ suggestedName , $ suggestedNames , true ) === false ) {
53
- $ suggestedNames [] = $ suggestedName ;
54
- }
55
- }
56
-
57
- $ suggestedType = implode ('| ' , $ suggestedNames );
55
+ $ suggestedType = $ this ->getValidTypeName ($ type );
58
56
if ($ type !== $ suggestedType ) {
59
57
$ fix = $ phpcsFile ->addFixableError (
60
58
'For type-hinting in PHPDocs, use %s instead of %s ' ,
@@ -82,7 +80,13 @@ public function process(File $phpcsFile, $stackPtr): void
82
80
*/
83
81
private function getValidTypeName (string $ typeName ): string
84
82
{
85
- $ parts = preg_split ('/([\<\,\>])/ ' , $ typeName , -1 , PREG_SPLIT_DELIM_CAPTURE );
83
+ $ typeNameWithoutSpace = str_replace (' ' , '' , $ typeName );
84
+ $ parts = preg_split (
85
+ '/([\| ' .self ::OPENER .self ::MIDDLE .self ::CLOSER .'])/ ' ,
86
+ $ typeNameWithoutSpace ,
87
+ -1 ,
88
+ PREG_SPLIT_DELIM_CAPTURE
89
+ );
86
90
$ partsNumber = count ($ parts ) - 1 ;
87
91
88
92
$ validType = '' ;
@@ -104,10 +108,6 @@ private function getValidTypeName(string $typeName): string
104
108
*/
105
109
private function suggestType (string $ typeName ): string
106
110
{
107
- if ('[] ' === substr ($ typeName , -2 )) {
108
- return $ this ->suggestType (substr ($ typeName , 0 , -2 )).'[] ' ;
109
- }
110
-
111
111
$ lowerType = strtolower ($ typeName );
112
112
switch ($ lowerType ) {
113
113
case 'bool ' :
0 commit comments