Skip to content

Commit

Permalink
Test for hash return types
Browse files Browse the repository at this point in the history
  • Loading branch information
Synchro committed Oct 14, 2020
1 parent 882a87e commit 1bbd625
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/Type/Php/HashFunctionsReturnTypeExtension.php
@@ -0,0 +1,50 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\MixedType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeUtils;

final class HashFunctionsReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{

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

public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
if ($functionReflection->getName() === 'hash') {
$defaultReturnType = new StringType();
} else {
$defaultReturnType = ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType();
}

if (!isset($functionCall->args[0])) {
return $defaultReturnType;
}

$argType = $scope->getType($functionCall->args[0]->value);
if ($argType instanceof MixedType) {
return TypeUtils::toBenevolentUnion($defaultReturnType);
}

$values = TypeUtils::getConstantStrings($argType);
if (count($values) !== 1) {
return TypeUtils::toBenevolentUnion($defaultReturnType);
}
$string = $values[0];

return in_array($string->getValue(), hash_algos(), true) ? $defaultReturnType : new ConstantBooleanType(false);
}

}
12 changes: 12 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Expand Up @@ -5954,6 +5954,18 @@ public function dataFunctions(): array
'(string|false)',
'$hashHmacFileVariable',
],
[
'string',
'$hash',
],
[
'string',
'$hashRaw',
],
[
'false',
'$hashRandom',
],
];
}

Expand Down
3 changes: 3 additions & 0 deletions tests/PHPStan/Analyser/data/functions.php
Expand Up @@ -135,4 +135,7 @@
$hashHmacFileRandom = hash_hmac_file('random', 'data', 'key');
$hashHmacFileVariable = hash_hmac_file($string, 'data', 'key');

$hash = hash('sha256', 'data', false);
$hashRaw = hash('sha256', 'data', true);
$hashRandom = hash('random', 'data', false);
die;

0 comments on commit 1bbd625

Please sign in to comment.