/
AbstractIdentifierLengthSniff.php
88 lines (70 loc) · 1.9 KB
/
AbstractIdentifierLengthSniff.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
<?php
declare(strict_types=1);
namespace ObjectCalisthenics;
use PHP_CodeSniffer_File;
/**
* Identifier length checker, part of "Do not abbreviate" OC rule.
*/
abstract class AbstractIdentifierLengthSniff
{
/**
* Token string representation.
*
* @var string
*/
protected $tokenString = 'variable';
/**
* Token type length factor, reducing the actual size of token by a factor of value.
*
* @var int
*/
protected $tokenTypeLengthFactor = 1;
/**
* Minimum variable/method name length.
*
* @var int
*/
protected $minLength = 3;
/**
* @var PHP_CodeSniffer_File
*/
private $phpcsFile;
/**
* @var int
*/
private $stackPtr;
public function register() : array
{
return [T_STRING];
}
/**
* @param PHP_CodeSniffer_File $phpcsFile
* @param int $stackPtr
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$this->phpcsFile = $phpcsFile;
$this->stackPtr = $stackPtr;
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
if (!$this->isValid($phpcsFile, $stackPtr)) {
return;
}
$length = strlen($token['content']) - $this->tokenTypeLengthFactor;
$this->handleMinLength($length);
}
abstract protected function isValid(PHP_CodeSniffer_File $phpcsFile, int $stackPtr) : bool;
private function handleMinLength(int $length)
{
if ($length >= $this->minLength) {
return;
}
$error = sprintf(
'Your %s is too short (currently %d chars, must be more or equals than %d chars)',
$this->tokenString,
$length,
$this->minLength
);
$this->phpcsFile->addError($error, $this->stackPtr, sprintf('%sTooShort', ucfirst($this->tokenString)));
}
}