NAME

Config::Strict - Add strict name- and type-checking to configuration data

VERSION

0.04 (alpha release)

SYNOPSIS

use Config::Strict;
use Declare::Constraints::Simple -All;               # For custom checks

# A comprehensive example
my $config = Config::Strict->new( {
    params => {                                      # Parameter types & names
        Bool     => [ qw( my_bool1 my_bool2 ) ],     # Multiple parameters
        Int      => 'my_i',                          # Single parameter
        Num      => 'my_n',
        Str      => [ qw( my_str1 my_str2 ) ],
        Regexp   => 'my_re',
        ArrayRef => 'my_aref',
        HashRef  => 'my_href',
        CodeRef  => 'my_cref',
        Enum     => { my_enum => [ qw( v1 v2 ), undef ] },
        Custom   => {                                # Custom profiles
            my_pos2 =>                               # Positive number
                And( IsNumber, Matches( qr/^[^-]+$/ ) ),
            my_nest => IsA( 'Config::Strict' ),      # Nested configuration
        }
    },
    required => [ qw( my_bool1 my_n ) ],             # Required parameters
    defaults => {                                    # Default values
        my_bool1    => 1,
        my_str2     => 'str',
        my_enum     => 'e2',
        my_n        => -1.1,
        my_pos2     => 1_000,
    },
} );

# Access and change the data

# Retrieve a single value
$config->get_param( 'my_n' );                       # -1.1

# Retrieve a list of values
$config->get_param( qw( my_bool1 my_str2 ) );       # ( 1, 'str' )

# Set multiple parameters
$config->set_param( my_bool1 => 1, 'my_pos2' => 2 );   

# Unset parameters
$config->unset_param( 'my_n' );
$config->param_is_set( 'my_n' );                    # false

# The following will die:
$config->get_param( 'bad_name' );           # bad_name doesn't exist in the configuration
$config->set_param( 'my_i' => 2.2 );        # my_i must be an integer
$config->set_param( 'my_pos2' => -5 );      # my_pos2 must be positive

DESCRIPTION

Config::Strict utilizes Declare::Constraints::Simple to enable strict parameter name- and type-checking on configuration data. Both built-in and custom types can be used to build a validation profile for the entire configuration.

A typical workflow might be:

1. Use some configuration module to parse a configuration file and load its data.
2. Construct a Config::Strict type system for your configuration data.
3. Load the parsed configuration hash into the Config::Strict object using set_param.
4. Use get_param in your program to access configuration values.
5. Write any changes back to disk using some module.

See Declare::Constraints::Simple::Library for an index to available constraints and the parent documentation for defining your own constraints and scoping.

CONSTRUCTING A TYPE SYSTEM

Declare the type system during construction:

Config::Strict->new( \%config_profile )

%config_profile is a multi-level hash with the following top-level keys:

params (Required)

Points to the hash of parameter types and names, where the keys are the built-in Config::Strict types (more below).

The values are either a single parameter name or an arrayref of parameter names, with the exception of the special types Enum and Custom which point to a uniquely defined hashref.

Any parameter not named here cannot be added later - any attempt to access a parameter that is not provided in the constructor will result in an error.

Parameter Types And Values:

Bool

Parameters taking the value 0 or 1.

Int

Integer parameters.

Num

Generic number parameters.

Str

Generic string parameters.

Enum

Enumerated parameters. The Enum key points to a hashref with $parameter_name => $values pairs, where $values is an arrayref of valid values for the enum $parameter_name.

Regexp

Compiled regexp parameters (with qr//).

ArrayRef

Generic list parameters.

HashRef

Generic hash parameters.

CodeRef

Generic code parameters.

Custom

Custom validation code. The Custom key points to a hashref with $parameter_name => $coderef pairs, where $coderef is a routine that validates a single argument and returns true or false (1 or 0) if the given value is a valid one for that parameter.

As of version 0.03, $coderef must be a Declare::Constraints::Simple "profile." These code profiles will in fact return a Declare::Constraints::Simple::Result which evaluate properly in boolean context and give more information (see their documentation for details).

Future versions may have the option of literal routines (sub { my $val = $_[0]; ... }) which will be wrapped automatically in a profile.

required (Optional)

Points to a arrayref of parameter names that must have valid values at all times. These parameters must also be given a default value.

The special value '_all' in the first location is a shortcut to specify that all parameters are to be required.

defaults (Optional)

Points to a hashref of default values to any number of parameters. Those parameters listed in required must be present in this section.

METHODS

GETTING AND SETTING PARAMETER VALUES

These methods will die with a stack trace if a given parameter doesn't exist in the configuration profile, or if an attempt is made to set a parameter with an invalid value.

$obj->get_param( $param1, $param2, ... )

Returns the list of values corresponding to each parameter.

$obj->set_param( $param1 => $value1, $param2 => $value2, ... )

Sets each parameter-value configuration pair.

$obj->unset_param( $param1, $param2, ... )

Unsets each parameter; internally deletes the parameter-value pair from the underlying parameter hash.

Required parameters cannot be unset.

PARAMETER CHECKING

The following methods can be used to check conditions on parameters without killing the program.

$obj->validate( $param1 => $value1, $param2 => $value2, ... )

Returns true if all parameter-value pairs are valid; false otherwise.

$obj->param_exists( $param )

Returns true if $param can be get/set; false otherwise.

$obj->param_is_set( $param )

Returns true if $param has been set; false otherwise.

$obj->param_is_required( $param )

Returns true if $param is a required parameter; false otherwise.

OTHER METHODS

$obj->all_params()

Returns the list of all parameters in the configuration.

$obj->all_set_params()

Returns the list of all set parameters in the configuration.

$obj->param_hash()

Returns a copy of the underlying configuration data as a list of key-value pairs.

$obj->param_array()

Returns a copy of the underlying configuration data as an array of array references.

$obj->get_profile( $param )

Returns the Declare::Constraints::Simple "profile" used to validate $param; it takes a single argument and returns true if the passed argument would be a valid value for $param. If it's a profile (true for all cases except custom bare coderefs) it will more specifically return a Declare::Constraints::Simple::Result.

EXTENDING THE DEFAULT TYPES

There are several ways to make your type system even more strict than the provided parameter types:

1. Using the Custom key and combining any number of Declare::Constraints::Simple routines, and/or your own.
2. Using the Custom key and defining your own validation coderefs. (TODO)
3. Subclassing Config::Strict and overloading any of the _get_check, _set_check, and _unset_check validation methods to add your own general validation semantics. These methods are executed before get_param, set_param, and unset_param, respectively.

TODO: - Document more code examples - Custom type class registration - DCS profile wrapper mechanism

SEE ALSO

Declare::Constraints::Simple

CAVEATS

This is an alpha release - the API is subject to change.

AUTHOR

Blake Willmarth

bwillmarth at gmail.com

BUGS

Please report any bugs or feature requests to bug-config-strict at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Config-Strict. I will be notified, and then you'll automatically be notified of progress on your bug as changes are made.

LICENSE AND COPYRIGHT

Copyright 2010 Blake Willmarth.

This program is free software; you can redistribute it and/or modify it under the terms of either:

  • the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or

  • the Artistic License version 2.0.