Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -1397,6 +1397,11 @@ services:
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension

-
class: PHPStan\Type\Php\StrvalFunctionReturnTypeExtension
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension

-
class: PHPStan\Type\Php\StrWordCountFunctionDynamicReturnTypeExtension
tags:
Expand Down
33 changes: 33 additions & 0 deletions src/Type/Php/StrvalFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;

class StrvalFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{

public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'strval';
}

public function getTypeFromFunctionCall(
FunctionReflection $functionReflection,
FuncCall $functionCall,
Scope $scope
): Type
{
if (count($functionCall->args) === 0) {
return new NullType();
}
$argType = $scope->getType($functionCall->args[0]->value);
return $argType->toString();
}

}
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,7 @@ public function dataFileAsserts(): iterable

yield from $this->gatherAssertTypes(__DIR__ . '/data/closure-types.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-5219.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/strval.php');
}

/**
Expand Down
19 changes: 19 additions & 0 deletions tests/PHPStan/Analyser/data/strval.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace StrvalTest;

use function PHPStan\Testing\assertType;

/**
* @param class-string<\stdClass> $class
*/
function test(string $class)
{
assertType('\'foo\'', strval('foo'));
assertType('\'\'', strval(null));
assertType('\'\'|\'1\'', strval(rand(0, 1) === 0));
assertType('string&numeric', strval(rand()));
assertType('string&numeric', strval(rand() * 0.1));
assertType('string&numeric', strval(strval(rand())));
assertType('class-string<stdClass>', strval($class));
}