/// <summary>
/// Filters a variable with a specified filter.
/// </summary>
/// <param name="ctx">Runtime context.</param>
/// <param name="variable">Value to filter.</param>
/// <param name="filter">The ID of the filter to apply.</param>
/// <param name="options">Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.</param>
/// <returns>Returns the filtered data, or <c>false</c> if the filter fails.</returns>
public static PhpValue filter_var(Context ctx, PhpValue variable, int filter /*= FILTER_DEFAULT*/, PhpValue options /*= NULL*/)
{
switch (filter)
{
//
// SANITIZE
//
case (int)FilterSanitize.FILTER_DEFAULT:
return((PhpValue)variable.ToString(ctx));
case (int)FilterSanitize.EMAIL:
// Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
return((PhpValue)FilterSanitizeString(variable.ToString(ctx), (c) =>
(int)c <= 0x7f && (Char.IsLetterOrDigit(c) ||
c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' ||
c == '*' || c == '+' || c == '-' || c == '/' || c == '=' || c == '!' ||
c == '?' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' ||
c == '}' || c == '~' || c == '@' || c == '.' || c == '[' || c == ']')));
//
// VALIDATE
//
case (int)FilterValidate.EMAIL:
{
var str = variable.ToString(ctx);
return(RegexUtilities.IsValidEmail(str) ? (PhpValue)str : PhpValue.False);
}
case (int)FilterValidate.INT:
{
int result;
if (int.TryParse((PhpVariable.AsString(variable) ?? string.Empty).Trim(), out result))
{
if (!options.IsNull)
{
PhpException.ArgumentValueNotSupported("options", "!null");
}
return((PhpValue)result); // TODO: options: min_range, max_range
}
else
{
return(PhpValue.False);
}
}
case (int)FilterValidate.REGEXP:
{
PhpArray optarray;
// options = options['options']['regexp']
if ((optarray = options.ArrayOrNull()) != null &&
optarray.TryGetValue("options", out options) && (optarray = options.ArrayOrNull()) != null &&
optarray.TryGetValue("regexp", out options))
{
if (PCRE.preg_match(ctx, options.ToString(ctx), variable.ToString(ctx)) > 0)
{
return(variable);
}
}
else
{
PhpException.InvalidArgument("options", string.Format(Resources.LibResources.option_missing, "regexp"));
}
return(PhpValue.False);
}
default:
PhpException.ArgumentValueNotSupported(nameof(filter), filter);
break;
}
return(PhpValue.False);
}