Are you also struggling with how to send arguments into the FILTER_CALLBACK.
Lets say you like to have a collection of custom filters that you can use in filter_var, filter_var_array and so on, but you want be able to call the new filters with different arguments, as you can in filter_var.
The easiest way to do this is to make a new class with all your custom filters. Then construct the class with your arguments inside filter_var argument array and enter the method in your class you like to run after.
If you send the argument as an array it is easy to make default values. But you can pass as many arguments you want and in any type, with this solution.
Example:
<?php
class CustomFilters {
private $options = array();
public function __construct(array $options=array()){
$this->options = $options;
}
private function get_options(array $defaults){
return array_merge($defaults, $this->options);
}
public function FILTER_STEP_RANGE($val){
$options = $this->get_options(
array(
"min_range" => 1,
"max_range" => 10,
"step" => 1,
"default" => null, "strict" => false, "cast" => false )
);
if(in_array( $val, range($options["min_range"], $options["max_range"], $options["step"]), $options["strict"])){
if( $options["cast"] && !settype($val, $options["cast"])) {
return $options["default"];
}
return $val;
}else{
return $options["default"];
}
}
public function FILTER_ENUM($val){
$options = $this->get_options(
array(
"values" => array(),
"strict" => false, "default" => null, "cast" => false )
);
if(in_array($val, $options["values"], $options["strict"])){
if( $options["cast"] && !settype($val, $options["cast"])){
return $options["default"];
}
return $val;
}else{
return $options["default"];
}
}
}
$data = array(
"range1" => "200",
"range2" => 25,
"enum" => "yes"
);
$args = array(
"range1" => array(
"filter" => FILTER_CALLBACK,
"options" => array(
new CustomFilters(array( "min_range" => 10, "max_range" => 600, "step" => 10, "default" => 120,
"cast" => "integer")),
'FILTER_STEP_RANGE'
)
),
"range2" => array(
"filter" => FILTER_CALLBACK,
"options" => array(
new CustomFilters(array( "min_range" => 0, "max_range" => 1, "step" => .1, "default" => .5,
"cast" => "float")),
'FILTER_STEP_RANGE'
)
),
"enum" => array(
"filter" => FILTER_CALLBACK,
"options" => array(
new CustomFilters(array( "values" => array("yes", "no", "Yes","No"), "cast" => "string")),
'FILTER_ENUM'
)
)
);
var_dump( filter_var_array($data, $args) );
?>
Returns:
array(3) {
["range1"] => int(200)
["range2"] => float(0.5)
["enum"] => string(3) "yes"
}