|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Php; |
| 4 | + |
| 5 | +use PhpParser\Node\Expr\FuncCall; |
| 6 | +use PhpParser\Node\Name; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\DependencyInjection\AutowiredService; |
| 9 | +use PHPStan\Reflection\FunctionReflection; |
| 10 | +use PHPStan\Reflection\ReflectionProvider; |
| 11 | +use PHPStan\Type\Constant\ConstantIntegerType; |
| 12 | +use PHPStan\Type\Constant\ConstantStringType; |
| 13 | +use PHPStan\Type\DynamicFunctionThrowTypeExtension; |
| 14 | +use PHPStan\Type\ObjectType; |
| 15 | +use PHPStan\Type\Type; |
| 16 | + |
| 17 | +#[AutowiredService] |
| 18 | +final class FilterVarThrowTypeExtension implements DynamicFunctionThrowTypeExtension |
| 19 | +{ |
| 20 | + |
| 21 | + public function __construct( |
| 22 | + private ReflectionProvider $reflectionProvider, |
| 23 | + ) |
| 24 | + { |
| 25 | + } |
| 26 | + |
| 27 | + public function isFunctionSupported( |
| 28 | + FunctionReflection $functionReflection, |
| 29 | + ): bool |
| 30 | + { |
| 31 | + return $functionReflection->getName() === 'filter_var' |
| 32 | + && $this->reflectionProvider->hasConstant(new Name\FullyQualified('FILTER_THROW_ON_FAILURE'), null); |
| 33 | + } |
| 34 | + |
| 35 | + public function getThrowTypeFromFunctionCall( |
| 36 | + FunctionReflection $functionReflection, |
| 37 | + FuncCall $funcCall, |
| 38 | + Scope $scope, |
| 39 | + ): ?Type |
| 40 | + { |
| 41 | + if (!isset($funcCall->getArgs()[3])) { |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + $flagsExpr = $funcCall->getArgs()[3]->value; |
| 46 | + $flagsType = $scope->getType($flagsExpr); |
| 47 | + |
| 48 | + if ($flagsType->isConstantArray()->yes()) { |
| 49 | + $flagsType = $flagsType->getOffsetValueType(new ConstantStringType('flags')); |
| 50 | + } |
| 51 | + |
| 52 | + $flag = $this->getConstant(); |
| 53 | + |
| 54 | + if ($flag !== null && $flagsType instanceof ConstantIntegerType && ($flagsType->getValue() & $flag) === $flag) { |
| 55 | + return new ObjectType('Filter\FilterFailedException'); |
| 56 | + } |
| 57 | + |
| 58 | + return null; |
| 59 | + } |
| 60 | + |
| 61 | + private function getConstant(): ?int |
| 62 | + { |
| 63 | + $constant = $this->reflectionProvider->getConstant(new Name('FILTER_THROW_ON_FAILURE'), null); |
| 64 | + $valueType = $constant->getValueType(); |
| 65 | + if (!$valueType instanceof ConstantIntegerType) { |
| 66 | + return null; |
| 67 | + } |
| 68 | + |
| 69 | + return $valueType->getValue(); |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments