1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gskema\TypeSniff\Sniffs\CodeElement; |
4
|
|
|
|
5
|
|
|
use Gskema\TypeSniff\Core\Type\DocBlock\CompoundType; |
6
|
|
|
use Gskema\TypeSniff\Core\Type\DocBlock\TypedArrayType; |
7
|
|
|
use Gskema\TypeSniff\Core\Type\TypeInterface; |
8
|
|
|
use PHP_CodeSniffer\Files\File; |
9
|
|
|
use Gskema\TypeSniff\Core\CodeElement\Element\AbstractFqcnConstElement; |
10
|
|
|
use Gskema\TypeSniff\Core\CodeElement\Element\ClassConstElement; |
11
|
|
|
use Gskema\TypeSniff\Core\CodeElement\Element\CodeElementInterface; |
12
|
|
|
use Gskema\TypeSniff\Core\CodeElement\Element\InterfaceConstElement; |
13
|
|
|
use Gskema\TypeSniff\Core\DocBlock\Tag\VarTag; |
14
|
|
|
use Gskema\TypeSniff\Core\Type\Common\ArrayType; |
15
|
|
|
|
16
|
|
|
class FqcnConstSniff implements CodeElementSniffInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @inheritDoc |
20
|
|
|
*/ |
21
|
4 |
|
public function configure(array $config): void |
22
|
|
|
{ |
23
|
|
|
// nothing to do |
24
|
4 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @inheritDoc |
28
|
|
|
*/ |
29
|
4 |
|
public function register(): array |
30
|
|
|
{ |
31
|
|
|
return [ |
32
|
4 |
|
ClassConstElement::class, |
33
|
|
|
InterfaceConstElement::class, |
34
|
|
|
]; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @inheritDoc |
39
|
|
|
* |
40
|
|
|
* @param AbstractFqcnConstElement $const |
41
|
|
|
*/ |
42
|
1 |
|
public function process(File $file, CodeElementInterface $const): void |
43
|
|
|
{ |
44
|
|
|
// @TODO Infer type from value? |
45
|
1 |
|
$docBlock = $const->getDocBlock(); |
46
|
|
|
|
47
|
|
|
/** @var VarTag|null $varTag */ |
48
|
1 |
|
$varTag = $docBlock->getTagsByName('var')[0] ?? null; |
49
|
1 |
|
$docType = $varTag ? $varTag->getType() : null; |
50
|
|
|
|
51
|
1 |
|
$subject = $const->getConstName().' constant'; |
52
|
|
|
|
53
|
1 |
|
if ($this->containsType($docType, ArrayType::class)) { |
54
|
1 |
|
$file->addWarningOnLine( |
55
|
1 |
|
'Replace array type with typed array type in PHPDoc for '.$subject.'. Use mixed[] for generic arrays.', |
56
|
1 |
|
$const->getLine(), |
57
|
1 |
|
'FqcnConstSniff' |
58
|
|
|
); |
59
|
1 |
|
} elseif (is_a($const->getValueType(), ArrayType::class) |
60
|
1 |
|
&& !$this->containsType($docType, TypedArrayType::class) |
61
|
|
|
) { |
62
|
1 |
|
$file->addWarningOnLine( |
63
|
1 |
|
'Add PHPDoc with typed array type hint for '.$subject.'. Use mixed[] for generic arrays.', |
64
|
1 |
|
$const->getLine(), |
65
|
1 |
|
'FqcnConstSniff' |
66
|
|
|
); |
67
|
|
|
} |
68
|
1 |
|
} |
69
|
|
|
|
70
|
|
|
|
71
|
1 |
|
protected function containsType(?TypeInterface $type, string $typeClassName): bool |
72
|
|
|
{ |
73
|
1 |
|
return is_a($type, $typeClassName) |
74
|
1 |
|
|| ($type instanceof CompoundType && $type->containsType($typeClassName)); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|