I am writing a configuration schema system, in which developers write small txt files which define what a configuration option is, what type it is, and a variety of useful runtime info and documentation.
My system, then, parses the txt file into a "universal" interchange schema object, which then can be translated into a runtime ConfigSchema class, which the configuration object uses to validate configuration directives, or DOM/XML/HTML, for the purpose of generating documentation.
There are some constraints on what the values of the txt file can be. For example, configuration directives names must be alphanumeric, there are only a specific set of allowed types, the default value must be parseable PHP code, etc. Thus, some sort of validation is necessary.
I'm trying to figure out how I should implement validation. One method that popped to mind was this:
Code: Select all
// using procedural for clarity; actual system is OO
function parseSchemaFile(&$schema, $file) {
// parsing code
$contents = file($file);
$values = array();
foreach ($contents as $keypair) {
list($k, $v) = explode(': ', $keypair, 2);
$values[$k] = $v;
}
// now, performing some evaluation
if (isset($values['php'])) {
$r = eval('$values["php"] = ' . $values['php'] . ';return true');
if (!$r) throw new Exception('Evaluation of php failed');
}
// now, performing some validation
if (!isset($values['id'])) {
throw new Exception('Id must exist');
}
if (!ctype_alnum($values['id'])) {
throw new Exception('Id must be alphanumeric');
}
if ($schema->idExists($values['id'])) {
throw new Exception('Id must be unique');
}
// now, put it into an object
$item = new SchemaItem($values['id']);
if (isset($values['php'])) $item->setPHP($values['php']);
// now, put it into the full schema
$schema->add($item);
}