|
7 | 7 | use PHP_CodeSniffer\Files\File; |
8 | 8 | use PHP_CodeSniffer\Util\Tokens; |
9 | 9 |
|
| 10 | +use function mb_strtolower; |
| 11 | +use function preg_match; |
| 12 | +use function trim; |
| 13 | + |
10 | 14 | /** |
11 | 15 | * Class SniffHelper |
12 | 16 | */ |
@@ -187,6 +191,67 @@ public static function isGlobalUse(File $phpcsFile, int $stackPtr): bool |
187 | 191 | return true; |
188 | 192 | } |
189 | 193 |
|
| 194 | + /** |
| 195 | + * @param File $phpcsFile |
| 196 | + * @param int $scopePtr |
| 197 | + * |
| 198 | + * @return array |
| 199 | + */ |
| 200 | + public static function getUseStatements(File $phpcsFile, int $scopePtr): array |
| 201 | + { |
| 202 | + $tokens = $phpcsFile->getTokens(); |
| 203 | + |
| 204 | + $uses = []; |
| 205 | + |
| 206 | + if (isset($tokens[$scopePtr]['scope_opener'])) { |
| 207 | + $start = $tokens[$scopePtr]['scope_opener']; |
| 208 | + $end = $tokens[$scopePtr]['scope_closer']; |
| 209 | + } else { |
| 210 | + $start = $scopePtr; |
| 211 | + $end = null; |
| 212 | + } |
| 213 | + |
| 214 | + $use = $phpcsFile->findNext(T_USE, $start + 1, $end); |
| 215 | + while (false !== $use && T_USE === $tokens[$use]['code']) { |
| 216 | + if ( |
| 217 | + !self::isGlobalUse($phpcsFile, $use) |
| 218 | + || (null !== $end |
| 219 | + && (!isset($tokens[$use]['conditions'][$scopePtr]) |
| 220 | + || $tokens[$use]['level'] !== $tokens[$scopePtr]['level'] + 1)) |
| 221 | + ) { |
| 222 | + $use = $phpcsFile->findNext(Tokens::$emptyTokens, $use + 1, $end, true); |
| 223 | + continue; |
| 224 | + } |
| 225 | + |
| 226 | + // find semicolon as the end of the global use scope |
| 227 | + $endOfScope = $phpcsFile->findNext(T_SEMICOLON, $use + 1); |
| 228 | + |
| 229 | + $startOfName = $phpcsFile->findNext([T_STRING, T_NS_SEPARATOR], $use + 1, $endOfScope); |
| 230 | + |
| 231 | + $type = 'class'; |
| 232 | + if (T_STRING === $tokens[$startOfName]['code']) { |
| 233 | + $lowerContent = mb_strtolower($tokens[$startOfName]['content']); |
| 234 | + if ('function' === $lowerContent || 'const' === $lowerContent) { |
| 235 | + $type = $lowerContent; |
| 236 | + |
| 237 | + $startOfName = $phpcsFile->findNext([T_STRING, T_NS_SEPARATOR], $startOfName + 1, $endOfScope); |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + $uses[] = [ |
| 242 | + 'ptrUse' => $use, |
| 243 | + 'name' => trim($phpcsFile->getTokensAsString($startOfName, $endOfScope - $startOfName)), |
| 244 | + 'ptrEnd' => $endOfScope, |
| 245 | + 'string' => trim($phpcsFile->getTokensAsString($use, $endOfScope - $use + 1)), |
| 246 | + 'type' => $type, |
| 247 | + ]; |
| 248 | + |
| 249 | + $use = $phpcsFile->findNext(Tokens::$emptyTokens, $endOfScope + 1, $end, true); |
| 250 | + } |
| 251 | + |
| 252 | + return $uses; |
| 253 | + } |
| 254 | + |
190 | 255 | /** |
191 | 256 | * @param string $content |
192 | 257 | * |
|
0 commit comments