forked from phpstan/phpstan-symfony
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequiredAutowiringExtension.php
91 lines (70 loc) · 2.45 KB
/
RequiredAutowiringExtension.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
<?php declare(strict_types = 1);
namespace PHPStan\Symfony;
use PHPStan\Reflection\AdditionalConstructorsExtension;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\Php\PhpPropertyReflection;
use PHPStan\Reflection\PropertyReflection;
use PHPStan\Rules\Properties\ReadWritePropertiesExtension;
use PHPStan\Type\FileTypeMapper;
use function count;
class RequiredAutowiringExtension implements ReadWritePropertiesExtension, AdditionalConstructorsExtension
{
/** @var FileTypeMapper */
private $fileTypeMapper;
public function __construct(FileTypeMapper $fileTypeMapper)
{
$this->fileTypeMapper = $fileTypeMapper;
}
public function isAlwaysRead(PropertyReflection $property, string $propertyName): bool
{
return false;
}
public function isAlwaysWritten(PropertyReflection $property, string $propertyName): bool
{
return false;
}
public function isInitialized(PropertyReflection $property, string $propertyName): bool
{
// If the property is public, check for @required on the property itself
if (!$property->isPublic()) {
return false;
}
if ($property->getDocComment() !== null && $this->isRequiredFromDocComment($property->getDocComment())) {
return true;
}
// Check for the attribute version
if ($property instanceof PhpPropertyReflection && count($property->getNativeReflection()->getAttributes('Symfony\Contracts\Service\Attribute\Required')) > 0) {
return true;
}
return false;
}
public function getAdditionalConstructors(ClassReflection $classReflection): array
{
$additionalConstructors = [];
$nativeReflection = $classReflection->getNativeReflection();
foreach ($nativeReflection->getMethods() as $method) {
if (!$method->isPublic()) {
continue;
}
if ($method->getDocComment() !== false && $this->isRequiredFromDocComment($method->getDocComment())) {
$additionalConstructors[] = $method->getName();
}
if (count($method->getAttributes('Symfony\Contracts\Service\Attribute\Required')) === 0) {
continue;
}
$additionalConstructors[] = $method->getName();
}
return $additionalConstructors;
}
private function isRequiredFromDocComment(string $docComment): bool
{
$phpDoc = $this->fileTypeMapper->getResolvedPhpDoc(null, null, null, null, $docComment);
foreach ($phpDoc->getPhpDocNodes() as $node) {
// @required tag is available, meaning this property is always initialized
if (count($node->getTagsByName('@required')) > 0) {
return true;
}
}
return false;
}
}