-
Notifications
You must be signed in to change notification settings - Fork 101
/
TypeHintingSniff.php
106 lines (96 loc) · 2.91 KB
/
TypeHintingSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/**
* This file is part of the Symfony-coding-standard (phpcs standard)
*
* PHP version 5
*
* @category PHP
* @package Symfony-coding-standard
* @author Authors <Symfony-coding-standard@djoos.github.com>
* @license http://spdx.org/licenses/MIT MIT License
* @link https://github.com/djoos/Symfony-coding-standard
*/
namespace Symfony\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
/**
* Checks for proper type hinting.
*
* @category PHP
* @package Symfony-coding-standard
* @author wicliff wolda <wicliff.wolda@gmail.com>
* @license http://spdx.org/licenses/MIT MIT License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class TypeHintingSniff implements Sniff
{
private static $_blacklist = [
'boolean' => 'bool',
'integer' => 'int',
'double' => 'float',
'real' => 'float',
];
private static $_casts = [
T_BOOL_CAST,
T_INT_CAST,
T_DOUBLE_CAST,
];
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array
*/
public function register()
{
return [
T_DOC_COMMENT_TAG,
T_BOOL_CAST,
T_INT_CAST,
T_DOUBLE_CAST,
];
}
/**
* Called when one of the token types that this sniff is listening for
* is found.
*
* @param File $phpcsFile The file where the token was found.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void|int Optionally returns a stack pointer. The sniff will not be
* called again on the current file until the returned stack
* pointer is reached. Return (count($tokens) + 1) to skip
* the rest of the file.
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$tag = $tokens[$stackPtr];
if ('@var' === $tag['content']) {
$type = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $stackPtr + 1);
$hint = strtolower(
preg_replace(
'/([^\s]+)[\s]+.*/',
'$1',
$tokens[$type]['content']
)
);
} elseif (in_array($tag['code'], self::$_casts)) {
$hint = strtolower(
preg_replace(
'/\(([^\s]+)\)/',
'$1',
$tag['content']
)
);
}
if (isset($hint) && isset(self::$_blacklist[$hint])) {
$error = sprintf(
'For type-hinting in PHPDocs and casting, use %s instead of %s',
self::$_blacklist[$hint],
$hint
);
$phpcsFile->addError($error, $stackPtr, 'Invalid');
}
}
}