@@ -122,10 +122,47 @@ private function createClampFuncCall(
122122 [$ valueExpr , $ innerBoundExpr ] = $ valueAndBound ;
123123
124124 if ($ this ->isName ($ outerFuncCall , 'max ' )) {
125- return $ this ->nodeFactory ->createFuncCall ('clamp ' , [$ valueExpr , $ outerBoundExpr , $ innerBoundExpr ]);
125+ [$ minExpr , $ maxExpr ] = [$ outerBoundExpr , $ innerBoundExpr ];
126+ } else {
127+ [$ minExpr , $ maxExpr ] = [$ innerBoundExpr , $ outerBoundExpr ];
126128 }
127129
128- return $ this ->nodeFactory ->createFuncCall ('clamp ' , [$ valueExpr , $ innerBoundExpr , $ outerBoundExpr ]);
130+ // clamp() throws ValueError when min > max, while nested min()/max() returns a value
131+ if (! $ this ->isProvenMinLowerOrEqualMax ($ minExpr , $ maxExpr )) {
132+ return null ;
133+ }
134+
135+ return $ this ->nodeFactory ->createFuncCall ('clamp ' , [$ valueExpr , $ minExpr , $ maxExpr ]);
136+ }
137+
138+ private function isProvenMinLowerOrEqualMax (Expr $ minExpr , Expr $ maxExpr ): bool
139+ {
140+ $ minValues = $ this ->getNativeType ($ minExpr )
141+ ->getConstantScalarValues ();
142+ $ maxValues = $ this ->getNativeType ($ maxExpr )
143+ ->getConstantScalarValues ();
144+
145+ if ($ minValues === [] || $ maxValues === []) {
146+ return false ;
147+ }
148+
149+ // clamp() throws ValueError on NAN bounds as well
150+ foreach ([...$ minValues , ...$ maxValues ] as $ boundValue ) {
151+ if (is_float ($ boundValue ) && is_nan ($ boundValue )) {
152+ return false ;
153+ }
154+ }
155+
156+ // constants like PHP_INT_MAX resolve to several platform values, all of them must hold
157+ foreach ($ minValues as $ minValue ) {
158+ foreach ($ maxValues as $ maxValue ) {
159+ if ($ minValue > $ maxValue ) {
160+ return false ;
161+ }
162+ }
163+ }
164+
165+ return true ;
129166 }
130167
131168 private function isSupportedArg (Arg $ arg ): bool
0 commit comments