Skip to content

Instantly share code, notes, and snippets.

@AnrDaemon
Last active March 10, 2023 07:55
Show Gist options
  • Save AnrDaemon/2a68ac5c6d5a750a04fa66b1e23a038e to your computer and use it in GitHub Desktop.
Save AnrDaemon/2a68ac5c6d5a750a04fa66b1e23a038e to your computer and use it in GitHub Desktop.
<?php
class Utility
{
public function createValidator($spec)
{
list($type, $name) = explode(":", $spec, 2) + ['', ''];
$options = ["default" => null];
switch($type)
{
case 'dummy': // Dummy "non-empty" validator
return function($var)
{
$var = trim((string)$var);
return strlen($var) ? $var : null;
};
break;
case 'bool': // "Boolean" validator. Accepts toggle words like yes/no and on/off.
$filter = \filter_id("boolean");
return function($var)
use($filter)
{
return \filter_var($var, $filter, FILTER_NULL_ON_FAILURE);
};
break;
case 'float': // C-type floating point number validator
$filter = \filter_id("float");
return function($var)
use($filter, $options)
{
return \filter_var($var, $filter, ["options" => $options]);
};
break;
case 'int': // "int" [ ":" [<min>] [ ":" <max> ] ]
$filter = \filter_id("int");
if(strlen($name))
{
$pattern = explode(":", $name, 2) + ['', ''];
if(strlen($pattern[0])) $options['min_range'] = (int)$pattern[0];
if(strlen($pattern[1])) $options['max_range'] = (int)$pattern[1];
}
return function($var)
use($filter, $options)
{
return \filter_var($var, $filter, ["options" => $options]);
};
break;
case 'string': // "string" [ ":" <regexp> ]
$filter = \filter_id("validate_regexp");
$options["regexp"] = $name;
return function($var)
use($filter, $options)
{
if(!strlen($options["regexp"]))
return $var;
return \filter_var($var, $filter, ["options" => $options]);
};
break;
case 'dict': // "dict:" <dictionary>
$dict = $this->getDictionary($name);
if(empty($dict))
throw new Exceptions\InvalidConfigurationException("Unknown dictionary '{$name}'.");
return function($var)
use($dict)
{
$result = $dict->get($var);
return is_null($result) ? null : $var;
};
break;
/*
case "custom": // Warning: extremely unsafe!
// Use a strong whitelisting approach to validate origins for this spec.
// For a more sane approach, see dict: specification above.
list($class, $method) = explode("::", $name, 2) + [null, null];
if(empty($method))
throw new Exceptions\InvalidConfigurationException("Validators may only be public class methods.");
if($class === "@")
$class = null;
return function($var)
use($class, $method)
{
$var = (string)$var;
return empty($class) ? $this->$method($var) : $class::$method($var);
};
break;
*/
default:
throw new Exceptions\InvalidConfigurationException("Unknown validator type '{$type}'.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment