NAME

Method::ParamValidator - Configurable method parameter validator.

VERSION

Version 0.10

DESCRIPTION

It provides easy way to configure and validate method parameters. It is going to help configure and validate all my packages WWW::Google::*.It is just a prototype as of now but will be extended as per the requirements.

SYNOPSIS

Setting up method validator manually.

use strict; use warnings;
use Test::More;
use Method::ParamValidator;

my $validator = Method::ParamValidator->new;
$validator->add_field({ name => 'firstname', format => 's' });
$validator->add_field({ name => 'lastname',  format => 's' });
$validator->add_field({ name => 'age',       format => 'd' });
$validator->add_field({ name => 'sex',       format => 's' });

$validator->add_method({ name   => 'add_user',
                         fields => { firstname => 1, lastname => 1, age => 1, sex => 0 }});

eval { $validator->validate('get_xyz'); };
like($@, qr/Invalid method name received/);

eval { $validator->validate('add_user'); };
like($@, qr/Missing parameters/);

eval { $validator->validate('add_user', []); };
like($@, qr/Invalid parameters data structure/);

eval { $validator->validate('add_user', { firstname => 'F', lastname => 'L', age => 'A' }); };
like($@, qr/Parameter failed check constraint/);

eval { $validator->validate('add_user', { firstname => 'F', lastname => 'L' }); };
like($@, qr/Missing required parameter/);

eval { $validator->validate('add_user', { firstname => 'F', lastname => undef, age => 10 }); };
like($@, qr/Undefined required parameter/);

eval { $validator->validate('add_user', { firstname => 'F' }); };
like($@, qr/Missing required parameter/);

done_testing();

Setting up method validator using configuration file.

Sample configuration file in JSON format.

{ "fields"  : [ { "name" : "firstname", "format" : "s" },
                { "name" : "lastname",  "format" : "s" },
                { "name" : "age",       "format" : "d" },
                { "name" : "sex",       "format" : "s" }
              ],
  "methods" : [ { "name"  : "add_user",
                  "fields": { "firstname" : "1",
                              "lastname"  : "1",
                              "age"       : "1",
                              "sex"       : "0"
                            }
                }
              ]
}

Then you just need one line to get everything setup using the above configuration file (config.json).

use strict; use warnings;
use Test::More;
use Method::ParamValidator;

my $validator = Method::ParamValidator->new({ config => "config.json" });

eval { $validator->validate('get_xyz'); };
like($@, qr/Invalid method name received/);

eval { $validator->validate('add_user'); };
like($@, qr/Missing parameters/);

eval { $validator->validate('add_user', []); };
like($@, qr/Invalid parameters data structure/);

eval { $validator->validate('add_user', { firstname => 'F', lastname => 'L', age => 'A' }); };
like($@, qr/Parameter failed check constraint/);

eval { $validator->validate('add_user', { firstname => 'F', lastname => 'L' }); };
like($@, qr/Missing required parameter/);

eval { $validator->validate('add_user', { firstname => 'F', lastname => undef, age => 10 }); };
like($@, qr/Undefined required parameter/);

eval { $validator->validate('add_user', { firstname => 'F' }); };
like($@, qr/Missing required parameter/);

done_testing();

Hooking your own check method

It allows you to provide your own method for validating a field as shown below:

use strict; use warnings;
use Test::More;
use Method::ParamValidator;

my $validator = Method::ParamValidator->new;

my $LOCATION = { 'USA' => 1, 'UK' => 1 };
sub lookup { exists $LOCATION->{uc($_[0])} };

$validator->add_field({ name => 'location', format => 's', check => \&lookup });
$validator->add_method({ name => 'check_location', fields => { location => 1 }});

eval { $validator->validate('check_location', { location => 'X' }); };
like($@, qr/Parameter failed check constraint/);

done_testing();

The above can be achieved using the configuration file as shown below:

{ "fields"  : [
                 { "name" : "location", "format" : "s", "source": [ "USA", "UK" ] }
              ],
  "methods" : [
                 { "name"  : "check_location", "fields": { "location" : "1" } }
              ]
}

Using the above configuration file test the code as below:

use strict; use warnings;
use Test::More;
use Method::ParamValidator;

my $validator = Method::ParamValidator->new({ config => "config.json" });

eval { $validator->validate('check_location', { location => 'X' }); };
like($@, qr/Parameter failed check constraint/);

done_testing();

Plug-n-Play with Moo package

Lets start with a basic Moo package PlayMath.

package PlayMath;

use Moo;
use namespace::clean;

sub do {
    my ($self, $param) = @_;

    if ($param->{op} eq 'add') {
       return ($param->{a} + $param->{b});
    }
    elsif ($param->{op} eq 'sub') {
       return ($param->{a} - $param->{b});
    }
    elsif ($param->{op} eq 'mul') {
       return ($param->{a} * $param->{b});
    }
}

1;

Now we need to create configuration file for the package PlayMath as below:

{ "fields"  : [ { "name" : "op", "format" : "s", "source": [ "add", "sub", "mul" ] },
                { "name" : "a",  "format" : "d" },
                { "name" : "b",  "format" : "d" }
              ],
  "methods" : [ { "name"  : "do",
                  "fields": { "op" : "1",
                              "a"  : "1",
                              "b"  : "1"
                            }
                }
              ]
}

Finally plug the validator to the package PlayMath as below:

use Method::ParamValidator;

has 'validator' => (
    is      => 'ro',
    default => sub { Method::ParamValidator->new(config => "config.json") }
);

before [qw/do/] => sub {
    my ($self, $param) = @_;

    my $method = (caller(1))[3];
    $method =~ /(.*)\:\:(.*)$/;
    $self->validator->validate($2, $param);
};

Here is unit test for the package PlayMath.

use strict; use warnings;
use Test::More;
use PlayMath;

my $math = PlayMath->new;

is($math->do({ op => 'add', a => 4, b => 2 }), 6);

is($math->do({ op => 'sub', a => 4, b => 2 }), 2);

is($math->do({ op => 'mul', a => 4, b => 2 }), 8);

eval { $math->do({ op => 'add' }) };
like($@, qr/Missing required parameter. \(a\)/);

eval { $math->do({ op => 'add', a => 1 }) };
like($@, qr/Missing required parameter. \(b\)/);

eval { $math->do({ op => 'x', a => 1, b => 2 }) };
like($@, qr/Parameter failed check constraint. \(op\)/);

eval { $math->do({ op => 'add', a => 'x', b => 2 }) };
like($@, qr/Parameter failed check constraint. \(a\)/);

eval { $math->do({ op => 'add', a => 1, b => 'x' }) };
like($@, qr/Parameter failed check constraint. \(b\)/);

done_testing();

METHODS

validate($method_name, \%params)

Validates the given method $name against the given parameters \%params. Throws exception if validation fail.

query_param($method, \%values)

Returns the query param for the given method $method and \%values. Throws exception if validation fail.

add_field(\%param)

Add field to the validator. Parameters are defined as below:

+---------+-----------------------------------------------------------------+
| Key     | Description                                                     |
+---------+-----------------------------------------------------------------+
|         |                                                                 |
| name    | Unique field name. Required.                                    |
|         |                                                                 |
| format  | Field data type. Optional, default is 's', other valid value    |
|         | is 'd'.                                                         |
|         |                                                                 |
| check   | Optional code ref to validate field value.                      |
|         |                                                                 |
| source  | Optional hashref to validate field value againsts.              |
|         |                                                                 |
| message | Optional field message.                                         |
|         |                                                                 |
+---------+-----------------------------------------------------------------+

get_field($name)

Returns an object of type Method::ParamValidator::Key::Field, matching field name $name.

add_method(\%param)

Add method to the validator. Parameters are defined as below:

+---------+-----------------------------------------------------------------+
| Key     | Description                                                     |
+---------+-----------------------------------------------------------------+
|         |                                                                 |
| name    | Method name.                                                    |
|         |                                                                 |
| fields  | Hash ref to list of fields e.g { field_1 => 1, field_2 => 0 }   |
|         | field_1 is required and field_2 is optional.                    |
|         |                                                                 |
+---------+-----------------------------------------------------------------+

get_method($name)

Returns an object of type Method::ParamValidator::Key::Method, matching method name $name.

AUTHOR

Mohammad S Anwar, <mohammad.anwar at yahoo.com>

REPOSITORY

https://github.com/manwar/Method-ParamValidator

BUGS

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

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc Method::ParamValidator

You can also look for information at:

LICENSE AND COPYRIGHT

Copyright (C) 2015 Mohammad S Anwar.

This program is free software; you can redistribute it and / or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:

http://www.perlfoundation.org/artistic_license_2_0

Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License.By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.

If your Modified Version has been derived from a Modified Version made by someone other than you,you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.

This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.

This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement,then this Artistic License to you shall terminate on the date that such litigation is filed.

Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.