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

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

namespace Rector\Tests\Php86\Rector\FuncCall\MinMaxToClampRector\Fixture;

fn (int $value) => max(10, min(5, $value));
fn (int $value) => min(5, max(10, $value));
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

namespace Rector\Tests\Php86\Rector\FuncCall\MinMaxToClampRector\Fixture;

fn (float $value) => max(NAN, min(5.0, $value));
fn (float $value) => max(0.0, min(NAN, $value));
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

namespace Rector\Tests\Php86\Rector\FuncCall\MinMaxToClampRector\Fixture;

fn (int $value, int $min) => max($min, min(100, $value));
fn (int $value, int $max) => min($max, max(0, $value));
41 changes: 39 additions & 2 deletions rules/Php86/Rector/FuncCall/MinMaxToClampRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,47 @@ private function createClampFuncCall(
[$valueExpr, $innerBoundExpr] = $valueAndBound;

if ($this->isName($outerFuncCall, 'max')) {
return $this->nodeFactory->createFuncCall('clamp', [$valueExpr, $outerBoundExpr, $innerBoundExpr]);
[$minExpr, $maxExpr] = [$outerBoundExpr, $innerBoundExpr];
} else {
[$minExpr, $maxExpr] = [$innerBoundExpr, $outerBoundExpr];
}

return $this->nodeFactory->createFuncCall('clamp', [$valueExpr, $innerBoundExpr, $outerBoundExpr]);
// clamp() throws ValueError when min > max, while nested min()/max() returns a value
if (! $this->isProvenMinLowerOrEqualMax($minExpr, $maxExpr)) {
return null;
}

return $this->nodeFactory->createFuncCall('clamp', [$valueExpr, $minExpr, $maxExpr]);
}

private function isProvenMinLowerOrEqualMax(Expr $minExpr, Expr $maxExpr): bool
{
$minValues = $this->getNativeType($minExpr)
->getConstantScalarValues();
$maxValues = $this->getNativeType($maxExpr)
->getConstantScalarValues();

if ($minValues === [] || $maxValues === []) {
return false;
}

// clamp() throws ValueError on NAN bounds as well
foreach ([...$minValues, ...$maxValues] as $boundValue) {
if (is_float($boundValue) && is_nan($boundValue)) {
return false;
}
}

// constants like PHP_INT_MAX resolve to several platform values, all of them must hold
foreach ($minValues as $minValue) {
foreach ($maxValues as $maxValue) {
if ($minValue > $maxValue) {
return false;
}
}
}

return true;
}

private function isSupportedArg(Arg $arg): bool
Expand Down
Loading