diff --git a/lib/Catmandu/Fix/validate.pm b/lib/Catmandu/Fix/validate.pm index 8e465db45..9eb81a858 100644 --- a/lib/Catmandu/Fix/validate.pm +++ b/lib/Catmandu/Fix/validate.pm @@ -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); @@ -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 }"; } @@ -64,9 +79,23 @@ Catmandu::Fix::validate - validate data and keep errors =head1 DESCRIPTION This L validates data with a L and stores -errors in field C for further inspection. The error field can be -configured with option C. Additional options are passed to the -validator. +errors in field C for further inspection. + +=head1 CONFIGURATION + +=over + +=item error_field + +Path where to store errors. Set to C 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 diff --git a/t/Catmandu-Fix-validator.t b/t/Catmandu-Fix-validate.t similarity index 88% rename from t/Catmandu-Fix-validator.t rename to t/Catmandu-Fix-validate.t index 75491f34e..02f547a29 100644 --- a/t/Catmandu-Fix-validator.t +++ b/t/Catmandu-Fix-validate.t @@ -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;