Skip to content

Commit

Permalink
Merge pull request #9422 from EgorBakulin/#9411/concat-should-never-r…
Browse files Browse the repository at this point in the history
…emove-non-empty-non-falsy-from-string

concat should never remove non empty non falsy from string #9411
  • Loading branch information
orklah committed Feb 27, 2023
2 parents 5083e18 + 67d26d3 commit 99b5987
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@
use Psalm\Type\Atomic\TFalse;
use Psalm\Type\Atomic\TFloat;
use Psalm\Type\Atomic\TInt;
use Psalm\Type\Atomic\TLiteralString;
use Psalm\Type\Atomic\TLowercaseString;
use Psalm\Type\Atomic\TNamedObject;
use Psalm\Type\Atomic\TNonEmptyNonspecificLiteralString;
use Psalm\Type\Atomic\TNonEmptyString;
use Psalm\Type\Atomic\TNonFalsyString;
use Psalm\Type\Atomic\TNonspecificLiteralString;
use Psalm\Type\Atomic\TNull;
use Psalm\Type\Atomic\TNumericString;
Expand Down Expand Up @@ -277,6 +279,31 @@ public static function analyze(
}
}
}
} elseif ($left_type || $right_type) {
/**
* @var Union $known_operand
*/
$known_operand = $right_type ?? $left_type;

if ($known_operand->isSingle()) {
$known_operands_atomic = $known_operand->getSingleAtomic();

if ($known_operands_atomic instanceof TNonEmptyString) {
$result_type = Type::getNonEmptyString();
}

if ($known_operands_atomic instanceof TNonFalsyString) {
$result_type = Type::getNonFalsyString();
}

if ($known_operands_atomic instanceof TLiteralString) {
if ($known_operands_atomic->value) {
$result_type = Type::getNonFalsyString();
} elseif ($known_operands_atomic->value !== '') {
$result_type = Type::getNonEmptyString();
}
}
}
}
}

Expand Down
24 changes: 24 additions & 0 deletions tests/BinaryOperationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,30 @@ function foobar(string $bar): string
foobar($foo . $bar);
',
],
'concatenateNonFalsyStringWithUndefinedConstant' => [
'code' => '<?php
/**
* @param non-falsy-string $arg
* @return non-falsy-string
*/
function foo( $arg ) {
/** @psalm-suppress UndefinedConstant */
return FOO . $arg;
}
',
],
'concatenateNonEmptyStringWithUndefinedConstant' => [
'code' => '<?php
/**
* @param non-empty-string $arg
* @return non-empty-string
*/
function foo( $arg ) {
/** @psalm-suppress UndefinedConstant */
return FOO . $arg;
}
',
],
'possiblyInvalidAdditionOnBothSides' => [
'code' => '<?php
function foo(string $s) : int {
Expand Down

0 comments on commit 99b5987

Please sign in to comment.