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
23 changes: 21 additions & 2 deletions src/Type/MixedType.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use PHPStan\Type\Accessory\OversizedArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Generic\TemplateMixedType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
Expand Down Expand Up @@ -471,10 +472,10 @@ public function toBoolean(): BooleanType

public function toNumber(): Type
{
return new UnionType([
return TypeCombinator::union(
$this->toInteger(),
$this->toFloat(),
]);
);
}

public function toAbsoluteNumber(): Type
Expand All @@ -484,6 +485,24 @@ public function toAbsoluteNumber(): Type

public function toInteger(): Type
{
$castsToZero = new UnionType([
new NullType(),
new ConstantBooleanType(false),
new ConstantIntegerType(0),
new ConstantArrayType([], []),
new StringType(),
new FloatType(),
]);
if (
$this->subtractedType !== null
&& $this->subtractedType->isSuperTypeOf($castsToZero)->yes()
) {
return new UnionType([
IntegerRangeType::fromInterval(null, -1),
IntegerRangeType::fromInterval(1, null),
]);
}

return new IntegerType();
}

Expand Down
41 changes: 41 additions & 0 deletions tests/PHPStan/Analyser/nsrt/integer-range-types.php
Original file line number Diff line number Diff line change
Expand Up @@ -446,3 +446,44 @@ public function zeroIssues($positive, $negative)
}

}

function subtract($m) {
if ($m != 0) {
assertType("mixed", $m); // could be "mixed~0|0.0|''|'0'|array{}|false|null"
assertType('int', (int) $m);
}
if ($m !== 0) {
assertType("mixed~0", $m);
assertType('int', (int) $m); // mixed could still contain falsey values, which cast to 0
}
if (!is_int($m)) {
assertType("mixed~int", $m);
assertType('int', (int) $m); // mixed could still contain falsey values, which cast to 0
}

if ($m != true) {
assertType("0|0.0|''|'0'|array{}|false|null", $m);
assertType('0', (int) $m);
}
if ($m !== true) {
assertType("mixed~true", $m);
assertType('int', (int) $m);
}

if ($m != false) {
assertType("mixed~0|0.0|''|'0'|array{}|false|null", $m);
assertType('int', (int) $m);
}
if ($m !== false) {
assertType("mixed~false", $m);
assertType('int', (int) $m); // mixed could still contain falsey values, which cast to 0
}
if (!is_string($m) && !is_float($m)) {
assertType("mixed~float|string", $m);
assertType('int', (int) $m);
if ($m != false) {
assertType("mixed~0|array{}|float|string|false|null", $m);
assertType('int<min, -1>|int<1, max>', (int) $m);
}
}
}
Loading