Skip to content

Numberfilter

mikey179 edited this page May 1, 2012 · 5 revisions

NumberFilter

Stubbles Input provides several different filters to filter for numbers.

IntegerFilter

The net\stubbles\input\filter\IntegerFilter allows to cast parameter values to integers. It takes any value and casts it to int. See PHP manual about converting values to integer for further details. The only difference is that null remains null and does not become 0.

FloatFilter

The net\stubbles\input\filter\FloatFilter allows to cast parameter values to floats. It takes any value and casts it to float. See PHP manual about converting values to float for further details. The only difference is that null remains null and does not become 0.

Additionally it allows to turn given float values into integer values by multiplying them with any power of ten:

$floatFilter = new FloatFilter();
var_dump($floatFilter->setDecimals(2)->apply(new Param('price', '1.99')));

This will print int(199) as the given parameter value is not only casted to float, but also multiplied with the power of ten to 2. Please be aware that the return value can still be a float if the parameter value to filter has more decimal places than the supplied decimal value.

RangeFilter

Additionally, both IntegerFilter and FloatFilter can be decorated with net\stubbles\input\filter\RangeFilter. The RangeFilter ensures that the filtered number is within a certain range:

$range = new RangeFilter(new IntegerFilter(),
                         new NumberRange(1, 10) // accepts all numbers inbetween and including 1 to 10
         );
var_dump($range->apply(new Param('ok', 4)));
var_dump($range->apply(new Param('not ok', 13)));

The example will print int(4) and NULL as only 4 is inbetween 1 and 10, whereas 13 is not.

Both the minimum value and the maximum value are optional. If not supplied the RangeFilter does nothing else as passing the result of the decorated number filter. If only minimum value or only maximum value is supplied it will only check for the supplied borders:

$range = new RangeFilter(new IntegerFilter(),
                         new NumberRange(1, null) // accepts all positive numbers >= 1
          ); 
$range = new RangeFilter(new IntegerFilter(), 
                         new NumberRange(null, -1) // accepts all negative numbers <= -1
         ); 

In case the value is below the minimum value the param will receive an error with id VALUE_TOO_SMALL, in case the value is greater than the maximum value the param will receive an error with id VALUE_TOO_GREAT.

Something went wrong with that request. Please try again.