15
15
*/
16
16
class ValidScalarTypeNameSniff implements Sniff
17
17
{
18
+ private const OPENER = '\<\[\{\( ' ;
19
+ private const CLOSER = '\>\]\}\) ' ;
20
+ private const MIDDLE = '\,\: ' ;
21
+
18
22
/**
19
23
* @return array
20
24
*/
@@ -32,29 +36,26 @@ public function process(File $phpcsFile, $stackPtr): void
32
36
$ tokens = $ phpcsFile ->getTokens ();
33
37
34
38
if (in_array ($ tokens [$ stackPtr ]['content ' ], SniffHelper::TAGS_WITH_TYPE )) {
39
+ $ openerWithSpace = '[ ' .self ::OPENER .']\s* ' ;
40
+ $ closerWithSpace =
41
+ '(?:[ ' .self ::CLOSER .']\s+)(?=[\| ' .self ::OPENER .self ::MIDDLE .self ::CLOSER .']) '
42
+ .'|[ ' .self ::CLOSER .'] ' ;
43
+ $ middleWithSpace = '\s*[ ' .self ::MIDDLE .']\s* ' ;
44
+
35
45
preg_match (
36
- ' `^((?:\|?(?:array\([^\)]*\)|[ \\\\ a-z0-9\[\<\,\>\]] +))*)( .*)?`i ' ,
46
+ " `^((?:\|?(?:(?:[ \\\\ a-z0-9]| $ {openerWithSpace} | $ {middleWithSpace} | $ {closerWithSpace} ) +))*)(.*)?`i" ,
37
47
$ tokens [($ stackPtr + 2 )]['content ' ],
38
48
$ match
39
49
);
40
50
51
+ var_dump ($ match );
41
52
if (isset ($ match [1 ]) === false ) {
42
53
return ;
43
54
}
44
55
45
56
// Check type (can be multiple, separated by '|').
46
57
$ 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 );
58
+ $ suggestedType = $ this ->getValidTypeName ($ type );
58
59
if ($ type !== $ suggestedType ) {
59
60
$ fix = $ phpcsFile ->addFixableError (
60
61
'For type-hinting in PHPDocs, use %s instead of %s ' ,
@@ -82,7 +83,13 @@ public function process(File $phpcsFile, $stackPtr): void
82
83
*/
83
84
private function getValidTypeName (string $ typeName ): string
84
85
{
85
- $ parts = preg_split ('/([\<\,\>])/ ' , $ typeName , -1 , PREG_SPLIT_DELIM_CAPTURE );
86
+ $ typeNameWithoutSpace = str_replace (' ' , '' , $ typeName );
87
+ $ parts = preg_split (
88
+ '/([\| ' .self ::OPENER .self ::MIDDLE .self ::CLOSER .'])/ ' ,
89
+ $ typeNameWithoutSpace ,
90
+ -1 ,
91
+ PREG_SPLIT_DELIM_CAPTURE
92
+ );
86
93
$ partsNumber = count ($ parts ) - 1 ;
87
94
88
95
$ validType = '' ;
@@ -104,10 +111,6 @@ private function getValidTypeName(string $typeName): string
104
111
*/
105
112
private function suggestType (string $ typeName ): string
106
113
{
107
- if ('[] ' === substr ($ typeName , -2 )) {
108
- return $ this ->suggestType (substr ($ typeName , 0 , -2 )).'[] ' ;
109
- }
110
-
111
114
$ lowerType = strtolower ($ typeName );
112
115
switch ($ lowerType ) {
113
116
case 'bool ' :
0 commit comments