Moose/Lint/Checker/RulesFile.pm untested

filter: Statementstmt 0.0% 0 / 199 Branchbran 0.0% 0 / 100 Conditioncond 0.0% 0 / 29 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 334 CC 51 SCAR 65.8
CC
51
Cov
0%
check
930.0
_set_file
506.0
BEGIN
2.0
CRAP 722.9
1 package MARC::Moose::Lint::Checker::RulesFile;
2 # ABSTRACT: A class to 'lint' biblio record based on a rules file
3 $MARC::Moose::Lint::Checker::RulesFile::VERSION = '1.0.46';
4 use Moose;
5 use Modern::Perl;
6  
7 with 'MARC::Moose::Lint::Checker';
8  
9  
10 has file => (is => 'ro', isa => 'Str', trigger => \&_set_file );
11  
12 has rules => (is => 'rw', isa => 'HashRef');
13  
14 has table => (is => 'rw', isa => 'HashRef', default => sub { {} });
15  
16 has tablecheck => (is => 'rw', isa => 'HashRef', default => sub { {} });
17  
18  
19 sub _set_file {
20 my $self = shift;
21  
22 my $file = $self->file;
23 unless (-f $file) {
24 say "$file: isn't a file";
25 exit;
26 }
27 open my $fh, "<", $file;
28 my @rules;
29 my @parts;
30 my $linenumber = 0;
31 my %rules;
32 my $analyze = sub {
33 #say;
34 my $tag = shift @parts;
35 if ( $tag !~ /^([0-9]{3})[_|\+]*/ ) {
36 say;
37 say "Line $linenumber: Invalid tag portion";
38 exit;
39 }
40 my $tag_digit = $1;
41 my $is_control_field = $tag_digit lt '010';
42 if ( (!$is_control_field && @parts < 3) || ($is_control_field && @parts > 1) ) {
43 say;
44 say "Line $linenumber: Invalid rule: wrong number of parts";
45 exit;
46 }
47 my @rule = (
48 $tag_digit,
49 $tag =~ /_/ ? 1 : 0,
50 $tag =~ /\+/ ? 1 : 0
51 );
52  
53 if ( $is_control_field ) {
54 push @rule, shift @parts;
55 }
56 else {
57 push @rule, [ shift @parts, shift @parts ],
58 [ map {
59 s/^ *//; s/ *$//;
60 my ($letter, $table, $regexp) =
61 /^([a-zA-Z0-9+_]+)\@([A-Z]*) *(.*)$/ ? ($1, $2, $3) :
62 /^([a-zA-Z0-9]+) +(.*)$/ ? ($1, 0, $2) : ($_, 0, '');
63 my $mandatory = $letter =~ /_/ ? 1 : 0;
64 $letter =~ s/_//g;
65 my $repeatable = $letter =~ /\+/ ? 1 : 0;
66 $letter =~ s/\+//g;
67 my @letter;
68 push @letter, $letter, $mandatory, $repeatable, $table;
69 push @letter, $regexp if $regexp;
70 \@letter;
71 } @parts ];
72 }
73 $rules{$tag_digit} = \@rule;
74  
75 @parts = ();
76 };
77 while (<$fh>) {
78 $linenumber++;
79 chop;
80 s/ *$//;
81 last if /^====/;
82  
83 if ( length($_) ) {
84 push @parts, $_;
85 next;
86 }
87 $analyze->();
88 }
89 $analyze->() if @parts;
90 $self->rules( \%rules );
91  
92 my $code;
93 if ( $_ && /^====/ ) {
94 while (1) {
95 if (/^==== *([A-Z]*) *(.*)$/) {
96 ($code) = $1;
97 for my $value ( split / +/, $2 ) {
98 say $_;
99 my $values = [ $code ];
100 my $tag = substr($value, 0, 3);
101 if ( $value = substr($value, 3) ) {
102 push @$values, substr($value, 0, 1);
103 $value = substr($value, 1);
104 }
105 if ( $value ) {
106 my ($from, $len) = split /,/, $value;
107 push @$values, $from, $len;
108 }
109 push @{ $self->tablecheck->{$tag} }, $values;
110 };
111 }
112 else {
113 $self->table->{$code}->{$_} = 1 if length($_) > 0;
114 }
115 while (<$fh>) {
116 chop;
117 last if defined $_;
118 }
119 last unless defined $_;
120 }
121 }
122 }
123  
124  
125 sub check {
126 my ($self, $record) = @_;
127  
128 my @warnings = ();
129 my $tag; # Current tag
130 my @fields; # Array of fields;
131 my $i_field; # Indice in the current array of fields
132 my $append = sub {
133 my @text = ($tag);
134 push @text, "($i_field)" if @fields > 1;
135 push @text, ": ", shift;
136 push @warnings, join('', @text);
137 };
138 my $fields_by_tag = { '000' => [ $record->leader ] };
139 for my $field ( @{$record->fields} ) {
140 $fields_by_tag->{$field->tag} ||= [];
141 push @{$fields_by_tag->{$field->tag}}, $field;
142 }
143  
144 # Find out unknown fields
145 my $rules = $self->rules;
146 {
147 my @unknown;
148 for $tag ( keys %$fields_by_tag ) {
149 push @unknown, $tag unless $rules->{$tag};
150 }
151 for (@unknown) {
152 $tag = $_;
153 $append->('Unknown tag');
154 }
155 }
156  
157 for my $rule ( values %$rules ) {
158 # Test if a mandatory field is missing, and if a non-repeatable field
159 # is repeated
160 my ($mandatory, $repeatable);
161 ($tag, $mandatory, $repeatable) = @$rule;
162 my $fields = $fields_by_tag->{$tag};
163 unless ($fields) {
164 @fields = ();
165 $append->("missing mandatory field") if $mandatory;
166 next;
167 }
168 @fields = @$fields;
169 $append->("non-repeatable field") if !$repeatable && @fields > 1;
170  
171 # Test tables
172 if ( my $checks = $self->tablecheck->{$tag} ) {
173 for my $check ( @$checks ) {
174 my ($code, $check_letter, $from, $len) = @$check;
175 my $table = $self->table->{$code};
176 unless ($table) {
177 say "Unknown table specified in rules file: $table";
178 exit;
179 }
180 $i_field = 1;
181 for my $field ( @fields ) {
182 for ( @{$field->subf} ) {
183 my ($letter, $value ) = @$_;
184 next if $letter ne $check_letter;
185 if ( length($from) > 0 ) {
186 my $val = substr($value, $from);
187 next unless $val;
188 $val = substr($val, 0, $len);
189 unless ( exists $table->{$val} ) {
190 $append->("subfield \$$letter, position $from,$len, invalid coded value: '$val'");
191 }
192 }
193 else {
194 unless ( exists $table->{$value} ) {
195 $append->("subfield \$$letter, invalid coded value (without from): '$value'");
196 }
197 }
198 }
199 }
200 }
201 }
202  
203 $i_field = 1;
204  
205 # Control field & leader
206 if ( $tag lt '010' ) {
207 my $regexp;
208 (undef, undef, undef, $regexp) = @$rule;
209 if ( $regexp ) {
210 if ( $tag eq '000') {
211 $append->("invalid leader, doesn't match /$regexp/")
212 if $record->leader !~ /$regexp/;
213 }
214 else {
215 for my $field (@fields) {
216 $append->("invalid value, doesn't match /$regexp/")
217 if $field->value !~ /$regexp/;
218 $i_field++;
219 }
220 }
221 }
222 next;
223 }
224  
225 # Standard field
226 my ($ind, $subf);
227 (undef, undef, undef, $ind, $subf) = @$rule;
228 for my $field (@fields) {
229 next if ref($field) ne 'MARC::Moose::Field::Std';
230 for (my $i=1; $i <=2 ; $i++) {
231 my $value = $i == 1 ? $field->ind1 : $field->ind2;
232 my $regexp = $ind->[$i-1];
233 $regexp =~ s/#/ /g;
234 $regexp =~ s/,/|/g;
235 $append->("invalid indicator $i '$value' , must be " . $ind->[$i-1])
236 if $value !~ /$regexp/;
237 }
238 # Search subfields which shouldn't be there
239 my @forbidden;
240 for (@{$field->subf}) {
241 my ($letter, $value) = @$_;
242 next unless $letter;
243 next if grep { $_->[0] =~ $letter } @$subf;
244 push @forbidden, $letter;
245 }
246 $append->("forbidden subfield(s): " . join(', ', @forbidden))
247 if @forbidden;
248  
249 for (@$subf) {
250 my ($letters, $mand, $repet, $table, $regexp) = @$_;
251 for my $letter (split //, $letters) {
252 my @values = $field->subfield($letter);
253 $append->("\$$letter mandatory subfield is missing")
254 if @values == 0 && $mand;
255 $append->("\$$letter is repeated") if @values > 1 && !$repet;
256 my $i = 1;
257 my $multi = @values > 1;
258 for my $value (@values) {
259 if ( $table && ! $self->table->{$table}->{$value} ) {
260 $append->(
261 "subfield \$$letter" .
262 ($multi ? "($i)" : "") .
263 " contains '$value' not in $table table");
264 }
265 if ( $regexp && $value !~ /$regexp/ ) {
266 $append->(
267 "invalid subfield \$$letter" .
268 ($multi ? "($i)" : "") .
269 ", should be $regexp");
270 }
271 $i++;
272 }
273 }
274 }
275 $i_field++;
276 }
277 }
278  
279 sort @warnings;
280 }
281  
282  
283 __PACKAGE__->meta->make_immutable;
284  
285 1;
286  
287 __END__
288  
289 =pod
290  
291 =encoding UTF-8
292  
293 =head1 NAME
294  
295 MARC::Moose::Lint::Checker::RulesFile - A class to 'lint' biblio record based on a rules file
296  
297 =head1 VERSION
298  
299 version 1.0.46
300  
301 =head1 DESCRIPTION
302  
303 A MARC biblio record, MARC21, UNIMARC, whatever, can be validated against
304 rules. Rules check various conditions:
305  
306 =over
307  
308 =item *
309  
310 B<Unknown tag> - If a field is present in a record but is not specified by its
311 tag in a validation rule, a warning is emitted saying that this field has an
312 I<Unknown tag>. This way all tags which are not specifically defined in
313 validation rules are identified.
314  
315 B<Unknown letter> - If a subfield is present in a field but is not specified by
316 its letter in a validation rule, a warning is emitted saying that this subfield
317 has an I<Unknown letter>. This way all subfields which are not specifically
318 defined in validation rules are identified.
319  
320 =item *
321  
322 B<Mandatory field> - When a validation rule defines that a field is mandatory,
323 if this field is not found in a record, a warning is emitted saying that this
324 field is I<missing>.
325  
326 B<Mandatory subfield> - When a validation rule defines that a subfield is
327 mandatory, if this subfield is not found in a field, a warning is emitted saying
328 that this subfield is I<missing>.
329  
330 =item *
331  
332 B<Repeatable field> - When a validation rule specify that a field is not
333 repeatable, if this field is repeated in a record, a warning is emitted saying
334 that this field is L<non repeatable>.
335  
336 =item *
337  
338 B<Repeatable subfield> - When a validation rule specify that a subfield is not
339 repeatable, if this subfield is repeated in a field, a warning is emitted
340 saying that this subfield is L<non repeatable>.
341  
342 =item *
343  
344 B<Indicator values> - Authorised values for indicators 1 and 2 are specified in
345 validation rule. When a field uses another value, a warning is emitted saying
346 I<invalid indicator value>.
347  
348 =item *
349  
350 B<Field content> - The content of a field, control field value, or subfield
351 value, can be tested on a regular expression. This way it's possible to check
352 that a field comply to a specific format. C<.{3}> will accept values with 3
353 characters length. C<[0-9]{8}> will accept digit-only value with 8 digits. And
354 this regular expression will validate UNIMARC 100 code field:
355  
356 ^[0-9]{8}[a-ku][0-9 ]{8}[abcdeklu ]{3}[a-huyz][01 ][a-z]{3}[a-cy][01|02|03|04|05|06|07|08|09|10|11|50]{2}
357  
358 =item *
359  
360 B<Validation tables> - Validation tables can be specified. For example, table
361 of ISO language codes. Field/subfield content can be validated against a table
362 in order to identify unauthorised values. When such a value is found, a warning
363 is emitted saying that I<this value> is not in I<this table>.
364  
365 =back
366  
367 =head1 ATTRIBUTES
368  
369 =head2 file
370  
371 Name of the file containing validation rules based on which a biblio record can
372 be validated.
373  
374 =head1 METHODS
375  
376 =head2 check( I<record> )
377  
378 This method checks a biblio record, based on the current 'lint' object. The
379 biblio record is a L<MARC::Moose::Record> object. An array of validation
380 errors/warnings is returned. Those errors are just plain text explanation on
381 the reasons why the record doesn't comply with validation rules.
382  
383 =head1 SYNOPSYS
384  
385 use MARC::Moose::Record;
386 use MARC::Moose::Reader::File::Iso2709;
387 use MARC::Moose::Lint::Checker::RulesFile;
388  
389 # Read an ISO2709 file, and dump found errors
390 my $reader = MARC::Moose::Reader::File::Iso2709->new(
391 file => 'biblio.mrc' );
392 my $lint = MARC::Moose::Lint::Checker::RulesFile->new(
393 file => 'unimarc.rules' );
394 while ( my $record = $reader->read() ) {
395 if ( my @result = $lint->check($record) ) {
396 say "Biblio record #", $record->field('001')->value;
397 say join("\n", @result), "\n";
398 }
399 }
400  
401 =head1 VALIDATION RULES
402  
403 Validation rules are defined in a textual form. The file is composed of two
404 parts: (1) B<field rules>, (2) B<validation tables>.
405  
406 =over
407  
408 =item B<(1) Field rules>
409  
410 Define validation rules for each tag. A blank line separates tags. For
411 example:
412  
413 102+
414 #
415 #
416 abc+i@CTRY ^[a-z]{3}$
417 2+
418  
419 Line 1 contains the field tag. If a + is present, the field is repeatable. If a
420 _ is present, the field is mandatory. For I<control fields> (tag under 010), an
421 optional second line can contain a regular expression on which validating field
422 content. For <standard fields>, line 2 and 3 contains a regular expression on
423 which indicators 1 and 2 are validated. # means a blank indicator. Line 4 and
424 the following define rules for validating subfields. A first part contains
425 subfield's letters, and + (repeatable) and/or _ (mandatory), followed by an
426 optional validation table name begining with @. A blank separates the first
427 part from the second part. The second part contains a regular expression on
428 which subfield content is validated.
429  
430 =item B<(2) Validation tables>
431  
432 This part of the file allows to define several validation tables. The table
433 name begins with C<==== TABLE NAME> in uppercase. Then each line is a code in
434 the validation table.
435  
436 This could be:
437  
438 ==== LANG 100a22,3 101a
439  
440 In this case, the table will be used to validate coded values in coded fields.
441 In this example, the language table will check 100$a subfield, position 22,
442 length 3, and 101$a. A table must contain all possible values. It not possible
443 to use regular expressions. If you can have a blank value, you need a line
444 containing juste a blank.
445  
446 =back
447  
448 This is for example, a simplified standard UNIMARC validation rules file:
449  
450 000
451 .{5}[cdnop][abcdefgijklmr][aimsc][ 012]
452  
453 001_
454  
455 005
456 \d{14}\.\d
457  
458 100_
459 #
460 #
461 a ^[0-9]{8}[a-ku][0-9 ]{8}[abcdeklu ]{3}[a-huyz][01 ][a-z]{3}[a-cy][01|02|03|04|05|06|07|08|09|10|11|50]{2}
462  
463 101_
464 0|1|2
465 #
466 abcdfghij+@LANG ^[a-z]{3}$
467  
468 200_
469 0|1
470 #
471 a_+
472 bcdefghi+
473 v
474 z5+
475  
476 ==== CTRY
477 AF
478 AL
479 DZ
480 GG
481 GN
482 GW
483 GY
484 HT
485 HM
486 VE
487 VN
488 VG
489 VI
490 ZM
491 ZW
492  
493 ==== LANG 100a22,3 101a
494 aar
495 afh
496 afr
497 afa
498 ain
499 aka
500 akk
501  
502 =head1 SEE ALSO
503  
504 =over 4
505  
506 =item *
507  
508 L<MARC::Moose>
509  
510 =item *
511  
512 L<MARC::Moose::Lint::Processor>
513  
514 =back
515  
516 =head1 AUTHOR
517  
518 Frédéric Demians <f.demians@tamil.fr>
519  
520 =head1 COPYRIGHT AND LICENSE
521  
522 This software is copyright (c) 2022 by Frédéric Demians.
523  
524 This is free software; you can redistribute it and/or modify it under
525 the same terms as the Perl 5 programming language system itself.
526  
527 =cut