-
Notifications
You must be signed in to change notification settings - Fork 571
Expand file tree
/
Copy pathDomDocumentCreateElementDynamicThrowTypeExtension.php
More file actions
57 lines (45 loc) · 1.5 KB
/
DomDocumentCreateElementDynamicThrowTypeExtension.php
File metadata and controls
57 lines (45 loc) · 1.5 KB
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
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use DOMDocument;
use DOMException;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicMethodThrowTypeExtension;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function extension_loaded;
#[AutowiredService]
final class DomDocumentCreateElementDynamicThrowTypeExtension implements DynamicMethodThrowTypeExtension
{
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return extension_loaded('dom')
&& $methodReflection->getDeclaringClass()->getName() === DOMDocument::class
&& $methodReflection->getName() === 'createElement';
}
public function getThrowTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type
{
$args = $methodCall->getArgs();
if (!isset($args[0])) {
return new ObjectType(DOMException::class);
}
$argType = $scope->getType($args[0]->value);
$doc = new DOMDocument();
foreach ($argType->getConstantStrings() as $constantString) {
try {
$doc->createElement($constantString->getValue());
} catch (DOMException) {
return new ObjectType(DOMException::class);
}
$argType = TypeCombinator::remove($argType, $constantString);
}
if (!$argType instanceof NeverType) {
return new ObjectType(DOMException::class);
}
return null;
}
}