/[webpac2]/trunk/lib/WebPAC/Validate.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /trunk/lib/WebPAC/Validate.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 828 - (show annotations)
Sun May 20 16:19:17 2007 UTC (16 years, 11 months ago) by dpavlin
File size: 8566 byte(s)
 r1213@llin:  dpavlin | 2007-05-20 18:16:02 +0200
 and fix to actually count right templates :-)

1 package WebPAC::Validate;
2
3 use warnings;
4 use strict;
5
6 use blib;
7
8 use base 'WebPAC::Common';
9 use File::Slurp;
10 use List::Util qw/first/;
11 use Data::Dump qw/dump/;
12 use WebPAC::Normalize qw/_pack_subfields_hash/;
13 use Storable qw/dclone/;
14
15 =head1 NAME
16
17 WebPAC::Validate - provide simple validation for records
18
19 =head1 VERSION
20
21 Version 0.11
22
23 =cut
24
25 our $VERSION = '0.11';
26
27 =head1 SYNOPSIS
28
29 This module provide a simple way to validate your file against a simple
30 configuration file in following format:
31
32 # field 10 doesn't have any subfields
33 10
34 # same with 101
35 101
36 # field 200 have valid subfields a-g
37 # and field e is repeatable
38 200 a b c d e* f g
39 # field 205 can have only subfield a
40 # and must exists
41 205! a
42 # while 210 can have a c or d
43 210 a c d
44 # field which is ignored in validation
45 999-
46
47 =head1 FUNCTIONS
48
49 =head2 new
50
51 Create new validation object
52
53 my $validate = new WebPAC::Validate(
54 path => 'conf/validate/file',
55 delimiters => [ ' : ', ' / ', ' ; ', ' , ' ],
56 );
57
58 Optional parametar C<delimiters> will turn on validating of delimiters. Be
59 careful here, those delimiters are just stuck into regex, so they can
60 contain L<perlre> regexpes.
61
62 =cut
63
64 sub new {
65 my $class = shift;
66 my $self = {@_};
67 bless($self, $class);
68
69 my $log = $self->_get_logger();
70
71 foreach my $p (qw/path/) {
72 $log->logconfess("need $p") unless ($self->{$p});
73 }
74
75 my $v_file = read_file( $self->{path} ) ||
76 $log->logdie("can't open validate path $self->{path}: $!");
77
78 my $v;
79 my $curr_line = 1;
80
81 foreach my $l (split(/[\n\r]+/, $v_file)) {
82 $curr_line++;
83
84 # skip comments and whitespaces
85 next if ($l =~ /^#/ || $l =~ /^\s*$/);
86
87 $l =~ s/^\s+//;
88 $l =~ s/\s+$//;
89
90 my @d = split(/\s+/, $l);
91
92 my $fld = shift @d;
93
94 if ($fld =~ s/!$//) {
95 $self->{must_exist}->{$fld}++;
96 } elsif ($fld =~ s/-$//) {
97 $self->{dont_validate}->{$fld}++;
98 }
99
100 $log->logdie("need field name in line $curr_line: $l") unless (defined($fld));
101
102 if (@d) {
103 $v->{$fld} = [ map {
104 my $sf = $_;
105 if ( $sf =~ s/!(\*)?$/$1/ ) {
106 $self->{must_exist_sf}->{ $fld }->{ $sf }++;
107 };
108 $sf;
109 } @d ];
110 } else {
111 $v->{$fld} = 1;
112 }
113
114 }
115
116 $log->debug("current validation rules: ", dump($v));
117
118 $self->{rules} = $v;
119
120 $log->info("validation uses rules from $self->{path}");
121
122 if ( $self->{delimiters} ) {
123 $self->{delimiters_regex} = '(\^[a-z0-9]|' . join('|', @{ $self->{delimiters} }) . ')';
124 $log->info("validation check delimiters with regex $self->{delimiters_regex}");
125 }
126
127 $self ? return $self : return undef;
128 }
129
130 =head2 validate_rec
131
132 Validate record and return errors
133
134 my @errors = $validate->validate_rec( $rec, $rec_dump );
135
136 =cut
137
138 sub validate_rec {
139 my $self = shift;
140
141 my $log = $self->_get_logger();
142
143 my $rec = shift || $log->logdie("validate_rec need record");
144 my $rec_dump = shift;
145
146 $log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');
147 $log->logdie("can't find validation rules") unless (my $r = $self->{rules});
148
149 my $errors;
150
151 $log->debug("rec = ", sub { dump($rec) }, "keys = ", keys %{ $rec });
152
153 my $fields;
154
155 foreach my $f (keys %{ $rec }) {
156
157 next if (!defined($f) || $f eq '' || $f eq '000');
158
159 # first check delimiters
160 if ( my $regex = $self->{delimiters_regex} ) {
161
162 foreach my $v (@{ $rec->{$f} }) {
163 warn "## v = ", dump( $v );
164 my $l = _pack_subfields_hash( $v, 1 );
165 warn "## $l [$regex]\n";
166 my $template = '';
167 $l =~ s/$regex/$template.=$1/eg && warn "## new: $l\n";
168 warn "## template: $template\n";
169 $self->{_delimiters_templates}->{$f}->{$template}++ if ( $template );
170 }
171
172 }
173
174 next if (defined( $self->{dont_validate}->{$f} ));
175
176 # track field usage
177 $fields->{$f}++;
178
179 if ( ! defined($r->{$f}) ) {
180 $errors->{ $f }->{unexpected} = "this field is not expected";
181 next;
182 }
183
184
185 if (ref($rec->{$f}) ne 'ARRAY') {
186 $errors->{ $f }->{not_repeatable} = "probably bug in parsing input data";
187 next;
188 }
189
190 foreach my $v (@{ $rec->{$f} }) {
191 # can we have subfields?
192 if (ref($r->{$f}) eq 'ARRAY') {
193 # are values hashes? (has subfields)
194 if (! defined($v)) {
195 # $errors->{$f}->{empty} = undef;
196 # $errors->{dump} = $rec_dump if ($rec_dump);
197 } elsif (ref($v) ne 'HASH') {
198 $errors->{$f}->{missing_subfield} = join(",", @{ $r->{$f} }) . " required";
199 next;
200 } else {
201
202 my $h = dclone( $v );
203
204 my $sf_repeatable;
205
206 delete($v->{subfields}) if (defined($v->{subfields}));
207
208 my $subfields;
209
210 foreach my $sf (keys %{ $v }) {
211
212 $subfields->{ $sf }++;
213
214 # is non-repeatable but with multiple values?
215 if ( ! first { $_ eq $sf.'*' } @{$r->{$f}} ) {
216 if ( ref($v->{$sf}) eq 'ARRAY' ) {
217 $sf_repeatable->{$sf}++;
218 };
219 if (! first { $_ eq $sf } @{ $r->{$f} }) {
220 $errors->{ $f }->{subfield}->{extra}->{$sf}++;
221 }
222 }
223
224 }
225 if (my @r_sf = sort keys( %$sf_repeatable )) {
226
227 foreach my $sf (@r_sf) {
228 $errors->{$f}->{subfield}->{extra_repeatable}->{$sf}++;
229 $errors->{$f}->{dump} = _pack_subfields_hash( $h, 1 );
230 }
231
232 }
233
234 if ( defined( $self->{must_exist_sf}->{$f} ) ) {
235 foreach my $sf (sort keys %{ $self->{must_exist_sf}->{$f} }) {
236 #warn "====> $f $sf must exist\n";
237 $errors->{$f}->{subfield}->{missing}->{$sf}++
238 unless defined( $subfields->{$sf} );
239 }
240 }
241
242 }
243 } elsif (ref($v) eq 'HASH') {
244 $errors->{$f}->{unexpected_subfields}++;
245 $errors->{$f}->{dump} = _pack_subfields_hash( $v, 1 );
246 }
247 }
248 }
249
250 $log->debug("_delimiters_templates = ", dump( $self->{_delimiters_templates} ) );
251
252 foreach my $must (sort keys %{ $self->{must_exist} }) {
253 next if ($fields->{$must});
254 $errors->{$must}->{missing}++;
255 $errors->{dump} = $rec_dump if ($rec_dump);
256 }
257
258 if ($errors) {
259 $log->debug("errors: ", $self->report_error( $errors ) );
260
261 my $mfn = $rec->{'000'}->[0] || $log->logconfess("record ", dump( $rec ), " doesn't have MFN");
262 $self->{errors}->{$mfn} = $errors;
263 }
264
265 #$log->logcluck("return from this function is ARRAY") unless wantarray;
266
267 return $errors;
268 }
269
270 =head2 reset_errors
271
272 Clean all accumulated errors for this input
273
274 $validate->reset_errors;
275
276 =cut
277
278 sub reset_errors {
279 my $self = shift;
280 delete ($self->{errors});
281 }
282
283 =head2 all_errors
284
285 Return hash with all errors
286
287 print dump( $validate->all_errors );
288
289 =cut
290
291 sub all_errors {
292 my $self = shift;
293 return $self->{errors};
294 }
295
296 =head2 report_error
297
298 Produce nice humanly readable report of single error
299
300 print $validate->report_error( $error_hash );
301
302 =cut
303
304 sub report_error {
305 my $self = shift;
306
307 my $h = shift || die "no hash?";
308
309 sub _unroll {
310 my ($self, $tree, $accumulated) = @_;
311
312 my $log = $self->_get_logger();
313
314 $log->debug("# ",
315 ( $tree ? "tree: $tree " : '' ),
316 ( $accumulated ? "accumulated: $accumulated " : '' ),
317 );
318
319 my $results;
320
321 if (ref($tree) ne 'HASH') {
322 return ("$accumulated\t($tree)", undef);
323 }
324
325 my $dump;
326
327 foreach my $k (sort keys %{ $tree }) {
328
329 if ($k eq 'dump') {
330 $dump = $tree->{dump};
331 # warn "## dump: ",dump($dump),"\n";
332 next;
333 }
334
335 $log->debug("current: $k");
336
337 my ($new_results, $new_dump) = $self->_unroll($tree->{$k},
338 $accumulated ? "$accumulated\t$k" : $k
339 );
340
341 $log->debug(
342 ( $new_results ? "new_results: " . dump($new_results) ." " : '' ),
343 );
344
345 push @$results, $new_results if ($new_results);
346 $dump = $new_dump if ($new_dump);
347
348 }
349
350 $log->debug(
351 ( $results ? "results: " . dump($results) ." " : '' ),
352 );
353
354 if ($#$results == 0) {
355 return ($results->[0], $dump);
356 } else {
357 return ($results, $dump);
358 }
359 }
360
361
362 sub _reformat {
363 my $l = shift;
364 $l =~ s/\t/ /g;
365 $l =~ s/_/ /;
366 return $l;
367 }
368
369 my $out = '';
370
371 for my $f (sort keys %{ $h }) {
372 $out .= "$f: ";
373
374 my ($r, $d) = $self->_unroll( $h->{$f} );
375 my $e;
376 if (ref($r) eq 'ARRAY') {
377 $e .= join(", ", map { _reformat( $_ ) } @$r);
378 } else {
379 $e .= _reformat( $r );
380 }
381 $e .= "\n\t$d" if ($d);
382
383 $out .= $e . "\n";
384 }
385 return $out;
386 }
387
388
389 =head2 report
390
391 Produce nice humanly readable report of errors
392
393 print $validate->report;
394
395 =cut
396
397 sub report {
398 my $self = shift;
399 my $e = $self->{errors} || return;
400
401 my $out;
402 foreach my $mfn (sort { $a <=> $b } keys %$e) {
403 $out .= "MFN $mfn\n" . $self->report_error( $e->{$mfn} ) . "\n";
404 }
405
406 return $out;
407
408 }
409
410 =head1 AUTHOR
411
412 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
413
414 =head1 COPYRIGHT & LICENSE
415
416 Copyright 2006 Dobrica Pavlinusic, All Rights Reserved.
417
418 This program is free software; you can redistribute it and/or modify it
419 under the same terms as Perl itself.
420
421 =cut
422
423 1; # End of WebPAC::Validate

  ViewVC Help
Powered by ViewVC 1.1.26