| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 
 | package Catmandu::Validator;
use Catmandu::Sane;
our $VERSION = '1.2012';
use Catmandu::Util qw(:is);
use Moo::Role;
use namespace::clean;
requires 'validate_data';
has 'last_errors' =>
    (is => 'rwp', clearer => '_clear_last_errors', init_arg => undef,);
has 'after_callback' => (is => 'ro', clearer => 1,);
has 'error_callback' => (is => 'ro', clearer => 1,);
has 'error_field' => (is => 'ro', clearer => 1,);
has ['valid_count', 'invalid_count'] =>
    (is => 'rwp', init_arg => undef, default => sub {0},);
sub is_valid {
    my ($self, $data) = @_;
    if (!is_hash_ref($data)) {
        Catmandu::BadArg->throw('Cannot validate data of this type');
    }
    $self->_clear_last_errors;
    $self->_set_valid_count(0);
    $self->_set_invalid_count(0);
    my $errors = $self->validate_data($data);
    if ($errors) {
        $self->_set_last_errors($errors);
        $self->_set_invalid_count(1);
        return 0;
    }
    else {
        $self->_set_valid_count(1);
    }
    1;
}
sub validate {
    my ($self, $data) = @_;
    $self->_set_valid_count(0);
    $self->_set_invalid_count(0);
    # handle a single record
    if (is_hash_ref($data)) {
        return $self->_process_record($data);
    }
    # handle arrayref, returns a new arrayref
    if (is_array_ref($data)) {
        return [grep {defined} map {$self->_process_record($_)} @$data];
    }
    # handle iterators, returns a new iterator
    if (is_invocant($data)) {
        return $data->select(sub {$self->_process_record($_[0])});
    }
    Catmandu::BadArg->throw('Cannot validate data of this type');
}
sub _process_record {
    my ($self, $data) = @_;
    my $error_field
        = ($self->error_field || 0) eq '1'
        ? '_validation_errors'
        : $self->error_field;
    $self->_clear_last_errors;
    my $errors = $self->validate_data($data);
    $self->_set_last_errors($errors);
    if ($errors) {
        $self->_set_invalid_count(1 + $self->invalid_count);
    }
    else {
        $self->_set_valid_count(1 + $self->valid_count);
    }
    if ($errors && $error_field) {
        $data->{$error_field} = $errors;
    }
    if ($self->after_callback) {
        return $self->after_callback->($data, $errors);
    }
    if ($errors && $self->error_callback) {
        $self->error_callback->($data, $errors);
        return;
    }
    return if $errors && !$error_field;
    $data;
}
1;
__END__
=pod
=head1 NAME
Catmandu::Validator - Namespace for packages that can validate items in Catmandu
=head1 SYNOPSIS
    use Catmandu::Validator::Simple;
    my $validator = Catmandu::Validator::Simple->new(
        handler => sub {
            $data = shift;
            return "error" unless $data->{title} =~ m/good title/;
            return;
        }
    );
    if ( $validator->is_valid($hashref) ) {
        save_record_in_database($hashref);
    } else {
        reject_form($validator->last_errors);
    }
    my $validator = Catmandu::Validator::Simple->new(
        handler => sub { ...},
        error_callback => sub {
            my ($data, $errors) = @_;
            print "Validation errors for record $data->{_id}:\n";
            print "$_\n" for @{$errors};
        }
    };
    my $validated_arrayref = $validator->validate($arrayref);
    $validator->validate($iterator, {
        after_callback => sub {
            my ($record, $errors) = @_;
            if ($errors) {
                add_to_failure_report($rec, $errors);
                #omit the invalid record from the result
                return undef;
            }
            return $rec;
        }
    })->each( sub {
        my $record = shift;
        publish_record($record);
    });
See L<Catmandu::Fix::validate> and L<Catmandu::Fix::Condition::valid> to use validators in fixes (L<Catmandu::Fix>).
=head1 DESCRIPTION
A Catmandu::Validator is a base class for Perl packages that can validate data.
=head1 METHODS
=head2 new()
Create a new Catmandu::Validator.
=head2 new( after_callback => \&callback )
The after_callback is called after each record has been validated.
The callback function should take $hashref to each data record, and $arrayref to list of validation errors
for the record as arguments.
=head2 new( error_field => $field_name )
If the error_field parameter is set, then during validation each record that
fails validation will get an extra field added containing an
arrayref to the validation errors. The name of the key will be the
value passed or '_validation_errors' if 1 is passed. By default it is not set.
=head2 is_valid( \%hash )
Validates a single record. Returns 1 success and 0 on failure. Information about the validation errors
can be retrieved with the L</"last_errors()"> method.
=head2 validate( \%hash )
=head2 validate( $iterator )
=head2 validate( \@array )
Validates a single record or multiple records in an iterator or an array. Returns validated records in the same type of
container for multiple records or the record itself for a single record. The default behaviour is to return the records that passed validation unchanged and omit the invalid records.
This behaviour can be changed by setting the I<after_callback> or the I<error_field> in the constructor. Returns undef on validation failure for single records.
=head2 last_errors()
Returns arrayref of errors from the record that was last validated if that record failed validation
or undef if there were no errors.
=head2 valid_count()
Returns the number of valid records from last validate operation.
=head2 invalid_count()
Returns the number of invalid records from the last validate operation.
=head1 SEE ALSO
L<Catmandu::Validator::Env> and L<Catmandu::Validator::Simple>.
L<Catmandu::Iterable>
=cut
 |