/
ElementNameMinimalLengthSniff.php
64 lines (52 loc) · 1.65 KB
/
ElementNameMinimalLengthSniff.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
<?php declare(strict_types=1);
namespace ObjectCalisthenics\Sniffs\NamingConventions;
use ObjectCalisthenics\Helper\NamingHelper;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
final class ElementNameMinimalLengthSniff implements Sniff
{
/**
* @var string
*/
private const ERROR_MESSAGE = '%s name "%s" is only %d chars long. Must be at least %d.';
/**
* @var int
*/
public $minLength = 3;
/**
* @var string[]
*/
public $allowedShortNames = ['i', 'id', 'to', 'up'];
/**
* @return int[]
*/
public function register(): array
{
return [T_CLASS, T_TRAIT, T_INTERFACE, T_CONST, T_FUNCTION, T_VARIABLE];
}
/**
* @param int $position
*/
public function process(File $file, $position): void
{
$elementName = NamingHelper::getElementName($file, $position);
$elementNameLength = mb_strlen($elementName);
if ($this->shouldBeSkipped($elementNameLength, $elementName)) {
return;
}
$typeName = NamingHelper::getTypeName($file, $position);
$message = sprintf(self::ERROR_MESSAGE, $typeName, $elementName, $elementNameLength, $this->minLength);
$file->addError($message, $position, self::class);
}
private function shouldBeSkipped(int $elementNameLength, string $elementName): bool
{
if ($elementNameLength >= $this->minLength) {
return true;
}
return $this->isShortNameAllowed($elementName);
}
private function isShortNameAllowed(string $variableName): bool
{
return in_array($variableName, $this->allowedShortNames, true);
}
}