Skip to content

Commit

Permalink
Add option verbose to validate Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
nichtich authored and nics committed Feb 2, 2018
1 parent ae23460 commit ab0a068
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 11 deletions.
51 changes: 40 additions & 11 deletions lib/Catmandu/Fix/validate.pm
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use Catmandu::Fix::Has;

has path => (fix_arg => 1);
has name => (fix_arg => 1);
has verbose => (fix_opt => 1);
has error_field => (fix_opt => 1, default => 'errors');
has opts => (fix_opt => 'collect');
has validator => (is => 'lazy', init_arg => undef);
Expand All @@ -20,17 +21,31 @@ with 'Catmandu::Fix::SimpleGetValue';
sub emit_value {
my ($self, $var, $fixer) = @_;
my $validator_var = $fixer->capture($self->validator);
my $verbose = $fixer->capture($self->verbose);
my $errors = $fixer->generate_var;
my $error_field = $self->error_field
? $fixer->split_path($self->error_field) : undef;

my $perl = $fixer->emit_create_path(
$fixer->var,
$error_field,
sub {
my $var = shift;
"${var} = ${validator_var}->last_errors;";
}
);
my $perl = $fixer->emit_declare_vars($errors)
. "${errors} = ${validator_var}->last_errors;"
. $fixer->emit_create_path(
$fixer->var,
$error_field,
sub {
my $var = shift;
"${var} = ${errors}";
}
)
. "if(${verbose}) {"
. $fixer->emit_foreach(
$errors,
sub {
my $v = shift;
"say STDERR is_ref(${v})"
."? Catmandu->export_to_string(${v},'JSON',array=>0) : ${v}"
}
)
. "}";

"unless (${validator_var}->is_valid(${var})) { $perl }";
}
Expand Down Expand Up @@ -64,9 +79,23 @@ Catmandu::Fix::validate - validate data and keep errors
=head1 DESCRIPTION
This L<Catmandu::Fix> validates data with a L<Catmandu::Validator> and stores
errors in field C<errors> for further inspection. The error field can be
configured with option C<error_field>. Additional options are passed to the
validator.
errors in field C<errors> for further inspection.
=head1 CONFIGURATION
=over
=item error_field
Path where to store errors. Set to C<errors> by default.
=item verbose
Print errors to STDERR. Non-scalar errors are serialized to JSON.
=back
Additional options are passed to the validator.
=head1 SEE ALSO
Expand Down
3 changes: 3 additions & 0 deletions t/Catmandu-Fix-validator.t → t/Catmandu-Fix-validate.t
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,7 @@ is_deeply $validator->fix(record),
record( warnings => [{ foo => 'bar'}] ),
"got errors with error_field";

$validator = $pkg->new( '', 'Simple', handler => sub { [{},1,{}] });
$validator->fix(record);

done_testing;

0 comments on commit ab0a068

Please sign in to comment.