diff --git a/conf/config.neon b/conf/config.neon index 83a69fd93e..0f54599481 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -1418,6 +1418,11 @@ services: tags: - phpstan.broker.dynamicFunctionReturnTypeExtension + - + class: PHPStan\Type\Php\LtrimFunctionReturnTypeExtension + tags: + - phpstan.broker.dynamicFunctionReturnTypeExtension + - class: PHPStan\Type\Php\MbFunctionsReturnTypeExtension tags: diff --git a/src/Type/Php/LtrimFunctionReturnTypeExtension.php b/src/Type/Php/LtrimFunctionReturnTypeExtension.php new file mode 100644 index 0000000000..a70f736661 --- /dev/null +++ b/src/Type/Php/LtrimFunctionReturnTypeExtension.php @@ -0,0 +1,45 @@ +getName() === 'ltrim'; + } + + public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): ?Type + { + if (count($functionCall->getArgs()) !== 2) { + return null; + } + + $string = $scope->getType($functionCall->getArgs()[0]->value); + $trimChars = $scope->getType($functionCall->getArgs()[1]->value); + + if ($trimChars instanceof ConstantStringType && $trimChars->getValue() === '\\') { + if ($string instanceof ConstantStringType && $string->isClassString()) { + return new ConstantStringType(ltrim($string->getValue(), $trimChars->getValue()), true); + } + + if ($string instanceof ClassStringType) { + return new ClassStringType(); + } + } + + return null; + } + +} diff --git a/tests/PHPStan/Analyser/NodeScopeResolverTest.php b/tests/PHPStan/Analyser/NodeScopeResolverTest.php index 01b3febe36..6f91873dd7 100644 --- a/tests/PHPStan/Analyser/NodeScopeResolverTest.php +++ b/tests/PHPStan/Analyser/NodeScopeResolverTest.php @@ -964,6 +964,7 @@ public function dataFileAsserts(): iterable yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-5223.php'); yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7698.php'); yield from $this->gatherAssertTypes(__DIR__ . '/data/non-falsy-string.php'); + yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7483.php'); } /** diff --git a/tests/PHPStan/Analyser/data/bug-7483.php b/tests/PHPStan/Analyser/data/bug-7483.php new file mode 100644 index 0000000000..c6fe12d899 --- /dev/null +++ b/tests/PHPStan/Analyser/data/bug-7483.php @@ -0,0 +1,25 @@ + $class + */ +function bar($class): string +{ + assertType('class-string', ltrim($class, '\\')); +} + +/** + * @param class-string $class + * @return class-string + */ +function foo($class): string +{ + assertType('class-string', ltrim($class, '\\')); + assertType("'Bug7483\\\\A'", ltrim(A::class, '\\')); +}