Subject: | bug at '0' val of param |
Date: | Wed, 15 May 2013 15:19:04 +0600 |
To: | <bug-Mojolicious-Plugin-ParamCondition [...] rt.cpan.org> |
From: | Кузнецов Сергей Владимирович <s.kuznetsov [...] sngb.ru> |
I found a bug with a value of '0 'request parameter in Mojo, apart from that, I corrected a little plugin to work with undef values of the parameters (their absence).
The source code is shown below in the letter.
package Mojolicious::Plugin::ParamCondition;
use Mojo::Base 'Mojolicious::Plugin';
sub register {
my ($self, $app) = @_;
$app->routes->add_condition(params => \&_params);
}
sub _check {
my ($value, $pattern) = @_;
if (!defined $pattern) {
return defined $value ? undef : 1;
}
return undef unless defined $value;
if (ref $pattern eq 'Regexp') {
return 1 if $value =~ $pattern;
}
return $pattern eq $value ? 1 : undef;
}
sub _params {
my ($r, $c, $captures, $params) = @_;
unless ($params && (ref $params eq 'ARRAY' || ref $params eq 'HASH')) {
return;
}
# All parameters need to exist
my $p = $c->req->params;
if (ref $params eq 'ARRAY') {
foreach my $name (@{ $params }) {
return if _check(scalar $p->param($name), undef);
}
}
elsif (ref $params eq 'HASH') {
keys %$params;
while (my ($name, $pattern) = each %$params) {
return unless _check(scalar $p->param($name), $pattern);
}
}
return 1;
}
1;