|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Php; |
| 4 | + |
| 5 | +use DOMDocument; |
| 6 | +use DOMException; |
| 7 | +use PhpParser\Node\Expr\MethodCall; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\DependencyInjection\AutowiredService; |
| 10 | +use PHPStan\Reflection\MethodReflection; |
| 11 | +use PHPStan\Reflection\ParametersAcceptorSelector; |
| 12 | +use PHPStan\Type\Constant\ConstantBooleanType; |
| 13 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 14 | +use PHPStan\Type\NeverType; |
| 15 | +use PHPStan\Type\Type; |
| 16 | +use PHPStan\Type\TypeCombinator; |
| 17 | +use function extension_loaded; |
| 18 | + |
| 19 | +#[AutowiredService] |
| 20 | +final class DomDocumentCreateElementDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension |
| 21 | +{ |
| 22 | + |
| 23 | + public function getClass(): string |
| 24 | + { |
| 25 | + return DOMDocument::class; |
| 26 | + } |
| 27 | + |
| 28 | + public function isMethodSupported(MethodReflection $methodReflection): bool |
| 29 | + { |
| 30 | + return extension_loaded('dom') && $methodReflection->getName() === 'createElement'; |
| 31 | + } |
| 32 | + |
| 33 | + public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type |
| 34 | + { |
| 35 | + $args = $methodCall->getArgs(); |
| 36 | + if (!isset($args[0])) { |
| 37 | + return null; |
| 38 | + } |
| 39 | + |
| 40 | + $argType = $scope->getType($args[0]->value); |
| 41 | + |
| 42 | + $doc = new DOMDocument(); |
| 43 | + |
| 44 | + foreach ($argType->getConstantStrings() as $constantString) { |
| 45 | + try { |
| 46 | + $doc->createElement($constantString->getValue()); |
| 47 | + } catch (DOMException) { |
| 48 | + return null; |
| 49 | + } |
| 50 | + |
| 51 | + $argType = TypeCombinator::remove($argType, $constantString); |
| 52 | + } |
| 53 | + |
| 54 | + if (!$argType instanceof NeverType) { |
| 55 | + return null; |
| 56 | + } |
| 57 | + |
| 58 | + $variant = ParametersAcceptorSelector::selectFromArgs($scope, $args, $methodReflection->getVariants()); |
| 59 | + |
| 60 | + return TypeCombinator::remove($variant->getReturnType(), new ConstantBooleanType(false)); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments