Skip to content

Commit

Permalink
Merge pull request #8619 from kkmuffme/keep-literal-string-for-simple…
Browse files Browse the repository at this point in the history
…-str_replace

keep literal string for simple str_replace
  • Loading branch information
orklah committed Oct 27, 2022
2 parents 25b3937 + e064a0c commit 7c83878
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
Expand Up @@ -10,6 +10,7 @@
use Psalm\Type\Atomic\TString;
use Psalm\Type\Union;

use function call_user_func;
use function count;
use function in_array;

Expand Down Expand Up @@ -50,7 +51,27 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev

$return_type = Type::getString();

if (in_array($function_id, ['preg_replace', 'preg_replace_callback'], true)) {
if (in_array($function_id, ['str_replace', 'str_ireplace'], true)
&& $subject_type->isSingleStringLiteral()
) {
$first_arg = $statements_source->node_data->getType($call_args[0]->value);
$second_arg = $statements_source->node_data->getType($call_args[1]->value);
if ($first_arg
&& $second_arg && $first_arg->isSingleStringLiteral()
&& $second_arg->isSingleStringLiteral()
) {
/**
* @var string $replaced_string
*/
$replaced_string = call_user_func(
$function_id,
$first_arg->getSingleStringLiteral()->value,
$second_arg->getSingleStringLiteral()->value,
$subject_type->getSingleStringLiteral()->value
);
$return_type = Type::getString($replaced_string);
}
} elseif (in_array($function_id, ['preg_replace', 'preg_replace_callback'], true)) {
$return_type = new Union([new TString, new TNull()]);

$codebase = $statements_source->getCodebase();
Expand Down
2 changes: 2 additions & 0 deletions tests/ReturnTypeProvider/DirnameTest.php
Expand Up @@ -5,6 +5,8 @@
use Psalm\Tests\TestCase;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;

use function addslashes;

use const DIRECTORY_SEPARATOR;

class DirnameTest extends TestCase
Expand Down

0 comments on commit 7c83878

Please sign in to comment.