I'm in the process of creating a flexible INI parser class that I can use for a project and in the future. I need the ability to add filters easily.
I went through several versions of this INI parser, and in the middle of using it, I realized it wasn't as flexible as I had thought. What I'd like are some suggestions on how to create an advanced filtering method in my class. Here's what I'd like to do:
use parse_ini_file() to initially parse the file. Most likely will be using sections, but need the ability parse w/out sections.
Filters:
I want to create functions that perform a filter, for example, I might have a function called replace_backticks_with_quotes that looks like this:
function replace_backticks_with_quotes( $value )
{
return str_replace('`', '"', $value);
}
To use the filters, I'd like to call them before I run the parser, so that when I actually parse, it returns the parsed file with all the filters already executed add_filter('replace_backticks_with_quotes')
The problem with this is I'd like some advanced functionality on my filter. I'd like to be able to filter values only if their attributes meet certain requirements. For example, I might want to pass my add_filter function an array of keys, and the filter will only affect those values that have those keys in the ini file.
So my ini file might have a part that looks like this:
special 1 = validate, Your input did not validate
special 2 = check, Your input did not check out
regular = this is the value
And I could say something like
add_filter('explode_commas', array('special 1', 'special 2'))
And it would run the function explode_commas that might look something like this
function explode_commas( $value )
{
return explode(",", $value, 2);
}
But what if I want to perform a regular expression to see if a key meets certain criteria like so
'/^(special|test|rule|etc)(\s)?([0-9a-zA-Z_-]{1,})?$/'
Or what if I want to perform a regexp on a value before I filter it. I was initially running my constructor function like this:
function parse( $file, $sections = true )
{
// Parse INI File into array
$contents = @parse_ini_file( $file, $sections );
// Run Filters
if (strtolower (get_class ($this)) == 'ini') {
$contents = $this->filter ($contents, $sections);
}
$this->contents = $contents;
return $contents;
}
and filter() would loop through $this->contents and execute all the filters ($this->_filters)
Usage Example:
$ini = new INI;
$ini->add_filter('explode_commas');
$ini->add_filter('replace_backticks_with_quotes');
$settings = $ini->ini_parse( $file );
$ini->clear_filters();
I don't need someone to write this for me, just some help with the logic as I'm completely stuck.