blib/lib/XML/Compile/Schema.pm untested

filter: Statementstmt 0.0% 0 / 283 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 110 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 574 CC 61 SCAR 45.7
CC
61
Cov
0%
compile
342.0
template
132.0
init
72.0
CRAP 96.5
1 # Copyrights 2006-2018 by [Mark Overmeer <markov@cpan.org>].
2 # For other contributors see ChangeLog.
3 # See the manual pages for details on the licensing terms.
4 # Pod stripped from pm file by OODoc 2.02.
5 # This code is part of distribution XML-Compile. Meta-POD processed with
6 # OODoc into POD and HTML manual-pages. See README.md
7 # Copyright Mark Overmeer. Licensed under the same terms as Perl itself.
8  
9 package XML::Compile::Schema;
10 use vars '$VERSION';
11 $VERSION = '1.61';
12  
13 use base 'XML::Compile';
14  
15 use warnings;
16 use strict;
17  
18 use Log::Report 'xml-compile';
19  
20 use List::Util qw/first/;
21 use XML::LibXML ();
22 use File::Spec ();
23 use File::Basename qw/basename/;
24 use Digest::MD5 qw/md5_hex/;
25  
26 use XML::Compile::Schema::Specs;
27 use XML::Compile::Schema::Instance;
28 use XML::Compile::Schema::NameSpaces;
29 use XML::Compile::Util qw/SCHEMA2001 SCHEMA2001i unpack_type/;
30  
31 use XML::Compile::Translate ();
32  
33  
34 sub init($)
35 { my ($self, $args) = @_;
36 $self->{namespaces} = XML::Compile::Schema::NameSpaces->new;
37 $self->SUPER::init($args);
38  
39 $self->importDefinitions($args->{top}, %$args)
40 if $args->{top};
41  
42 $self->{hooks} = [];
43 if(my $h1 = $args->{hook})
44 { $self->addHook(ref $h1 eq 'ARRAY' ? @$h1 : $h1);
45 }
46 if(my $h2 = $args->{hooks})
47 { $self->addHook($_) for ref $h2 eq 'ARRAY' ? @$h2 : $h2;
48 }
49
50 $self->{key_rewrite} = [];
51 if(my $kr = $args->{key_rewrite})
52 { $self->addKeyRewrite(ref $kr eq 'ARRAY' ? @$kr : $kr);
53 }
54  
55 $self->{block_nss} = [];
56 $self->blockNamespace($args->{block_namespace});
57  
58 $self->{typemap} = $args->{typemap} || {};
59 $self->{unused_tags} = $args->{ignore_unused_tags};
60  
61 $self;
62 }
63  
64 #--------------------------------------
65  
66  
67 sub addHook(@)
68 { my $self = shift;
69 push @{$self->{hooks}}, @_>1 ? {@_} : defined $_[0] ? shift : ();
70 $self;
71 }
72  
73  
74 sub addHooks(@)
75 { my $self = shift;
76 $self->addHook($_) for @_;
77 $self;
78 }
79  
80  
81 sub hooks(;$)
82 { my $hooks = shift->{hooks};
83 my $dir = shift or return @$hooks;
84 grep +(!$_->{action} || $_->{action} eq $dir), @$hooks;
85 }
86  
87  
88 sub addTypemaps(@)
89 { my $map = shift->{typemap};
90 while(@_ > 1)
91 { my $k = shift;
92 $map->{$k} = shift;
93 }
94 $map;
95 }
96 *addTypemap = \&addTypemaps;
97  
98  
99 sub addSchemas($@)
100 { my ($self, $node, %opts) = @_;
101 defined $node or return ();
102  
103 my @nsopts;
104 foreach my $o (qw/source filename target_namespace
105 element_form_default attribute_form_default/)
106 { push @nsopts, $o => delete $opts{$o} if exists $opts{$o};
107 }
108  
109 UNIVERSAL::isa($node, __PACKAGE__)
110 and error __x"use useSchema(), not addSchemas() for a {got} object"
111 , got => ref $node;
112  
113 UNIVERSAL::isa($node, 'XML::LibXML::Node')
114 or error __x"addSchema() requires an XML::LibXML::Node";
115  
116 $node = $node->documentElement
117 if $node->isa('XML::LibXML::Document');
118  
119 my $nss = $self->namespaces;
120 my @schemas;
121  
122 $self->walkTree
123 ( $node,
124 sub { my $this = shift;
125 return 1 unless $this->isa('XML::LibXML::Element')
126 && $this->localName eq 'schema';
127  
128 my $schema = XML::Compile::Schema::Instance->new($this, @nsopts)
129 or next;
130  
131 $nss->add($schema);
132 push @schemas, $schema;
133 return 0;
134 }
135 );
136 @schemas;
137 }
138  
139  
140 sub useSchema(@)
141 { my $self = shift;
142 foreach my $schema (@_)
143 { error __x"useSchema() accepts only {pkg} extensions, not {got}"
144 , pkg => __PACKAGE__, got => (ref $schema || $schema);
145 $self->namespaces->use($schema);
146 }
147 $self;
148 }
149  
150  
151 sub addKeyRewrite(@)
152 { my $self = shift;
153 unshift @{$self->{key_rewrite}}, @_;
154 defined wantarray ? $self->_key_rewrite(undef) : ();
155 }
156  
157 sub _key_rewrite($)
158 { my $self = shift;
159 my @more = map { ref $_ eq 'ARRAY' ? @$_ : defined $_ ? $_ : () } @_;
160  
161 my ($pref_all, %pref, @other);
162 foreach my $rule (@more, @{$self->{key_rewrite}})
163 { if($rule eq 'PREFIXED') { $pref_all++ }
164 elsif($rule =~ m/^PREFIXED\((.*)\)/) { $pref{$_}++ for split /\,/, $1 }
165 else { push @other, $rule }
166 }
167  
168 ( ( $pref_all ? 'PREFIXED'
169 : keys %pref ? 'PREFIXED('.join(',', sort keys %pref).')'
170 : ()), @other );
171 }
172  
173  
174 sub blockNamespace(@)
175 { my $self = shift;
176 push @{$self->{block_nss}}, @_;
177 }
178  
179 sub _block_nss(@)
180 { my $self = shift;
181 grep defined, map {ref $_ eq 'ARRAY' ? @$_ : $_}
182 @_, @{$self->{block_nss}};
183 }
184  
185 #--------------------------------------
186  
187  
188 sub compile($$@)
189 { my ($self, $action, $type, %args) = @_;
190 defined $type or return ();
191  
192 if(exists $args{validation})
193 { $args{check_values} = $args{validation};
194 $args{check_occurs} = $args{validation};
195 $args{ignore_facets} = ! $args{validation};
196 }
197 else
198 { exists $args{check_values} or $args{check_values} = 1;
199 exists $args{check_occurs} or $args{check_occurs} = 1;
200 }
201  
202 my $iut = exists $args{ignore_unused_tags}
203 ? $args{ignore_unused_tags} : $self->{unused_tags};
204  
205 $args{ignore_unused_tags}
206 = !defined $iut ? undef : ref $iut eq 'Regexp' ? $iut : qr/^/;
207  
208 exists $args{include_namespaces}
209 or $args{include_namespaces} = 1;
210  
211 if($args{sloppy_integers} ||= 0)
212 { eval "require Math::BigInt";
213 panic "require Math::BigInt or sloppy_integers:\n$@"
214 if $@;
215 }
216  
217 if($args{sloppy_floats} ||= 0)
218 { eval "require Math::BigFloat";
219 panic "require Math::BigFloat by sloppy_floats:\n$@" if $@;
220 }
221  
222 if($args{json_friendly} ||= 0)
223 { eval "require Types::Serialiser";
224 panic "require Types::Serialiser by json_friendly:\n$@" if $@;
225 }
226  
227 $args{prefixes} = $self->_namespaceTable
228 (($args{prefixes} || $args{output_namespaces})
229 , $args{namespace_reset}
230 , !($args{use_default_namespace} || $args{use_default_prefix})
231 # use_default_prefix renamed in 0.90
232 );
233  
234 my $nss = $self->namespaces;
235  
236 my ($h1, $h2) = (delete $args{hook}, delete $args{hooks});
237 my @hooks = $self->hooks($action);
238 push @hooks, ref $h1 eq 'ARRAY' ? @$h1 : $h1 if $h1;
239 push @hooks, ref $h2 eq 'ARRAY' ? @$h2 : $h2 if $h2;
240  
241 my %map = ( %{$self->{typemap}}, %{$args{typemap} || {}} );
242 trace "schema compile $action for $type";
243  
244 my @rewrite = $self->_key_rewrite(delete $args{key_rewrite});
245 my @blocked = $self->_block_nss(delete $args{block_namespace});
246  
247 $args{abstract_types} ||= 'ERROR';
248 $args{mixed_elements} ||= 'ATTRIBUTES';
249 $args{default_values} ||= $action eq 'READER' ? 'EXTEND' : 'IGNORE';
250  
251 # Option rename in 0.88
252 $args{any_element} ||= delete $args{anyElement};
253 $args{any_attribute} ||= delete $args{anyAttribute};
254  
255 if(my $xi = $args{xsi_type})
256 { my $nss = $self->namespaces;
257 foreach (keys %$xi)
258 { $xi->{$_} = $nss->autoexpand_xsi_type($_) if $xi->{$_} eq 'AUTO';
259 }
260 }
261  
262 my $transl = XML::Compile::Translate->new
263 ( $action
264 , nss => $self->namespaces
265 );
266  
267 $transl->compile
268 ( $type, %args
269 , hooks => \@hooks
270 , typemap => \%map
271 , rewrite => \@rewrite
272 , block_namespace => \@blocked
273 );
274 }
275  
276 # also used in ::Cache init()
277 sub _namespaceTable($;$$)
278 { my ($self, $table, $reset_count, $block_default) = @_;
279 $table = { reverse @$table }
280 if ref $table eq 'ARRAY';
281  
282 $table->{$_} = { uri => $_, prefix => $table->{$_} }
283 for grep ref $table->{$_} ne 'HASH', keys %$table;
284  
285 if($reset_count)
286 { $_->{used} = 0 for values %$table;
287 }
288  
289 $table->{''} = {uri => '', prefix => '', used => 0}
290 if $block_default && !grep $_->{prefix} eq '', values %$table;
291  
292 # very strong preference for 'xsi'
293 $table->{&SCHEMA2001i} = {uri => SCHEMA2001i, prefix => 'xsi', used => 0};
294  
295 $table;
296 }
297  
298  
299 sub compileType($$@)
300 { my ($self, $action, $type, %args) = @_;
301  
302 # translator can only create elements, not types.
303 my $elem = delete $args{element} || $type;
304 my ($ens, $elocal) = unpack_type $elem;
305 my ($ns, $local) = unpack_type $type;
306  
307 my $SchemaNS = SCHEMA2001;
308  
309 my $defs = $ns ? <<_DIRTY_TRICK1 : <<_DIRTY_TRICK2;
310 <schema xmlns="$SchemaNS"
311 targetNamespace="$ens"
312 xmlns:tns="$ns">
313 <element name="$elocal" type="tns:$local" />
314 </schema>
315 _DIRTY_TRICK1
316 <schema xmlns="$SchemaNS"
317 targetNamespace="$ens"
318 elementFormDefault="unqualified"
319 >
320 <element name="$elocal" type="$local" />
321 </schema>
322 _DIRTY_TRICK2
323  
324 $self->importDefinitions($defs);
325 $self->compile($action, $elem, %args);
326 }
327  
328  
329 sub template($@)
330 { my ($self, $action, $type, %args) = @_;
331  
332 my ($to_perl, $to_xml)
333 = $action eq 'PERL' ? (1, 0)
334 : $action eq 'XML' ? (0, 1)
335 : $action eq 'TREE' ? (0, 0)
336 : error __x"template output is either in XML or PERL layout, not '{action}'"
337 , action => $action;
338  
339 my $show
340 = exists $args{show_comments} ? $args{show_comments}
341 : exists $args{show} ? $args{show} # pre-0.79 option name
342 : 'ALL';
343  
344 $show = 'struct,type,occur,facets' if $show eq 'ALL';
345 $show = '' if $show eq 'NONE';
346 my %show = map {("show_$_" => 1)} split m/\,/, $show;
347 my $nss = $self->namespaces;
348  
349 my $indent = $args{indent} || " ";
350 $args{check_occurs} = 1;
351 $args{mixed_elements} ||= 'ATTRIBUTES';
352 $args{default_values} ||= 'EXTEND';
353 $args{abstract_types} ||= 'ERROR';
354  
355 exists $args{include_namespaces}
356 or $args{include_namespaces} = 1;
357  
358 # it could be used to add extra comment lines
359 error __x"typemaps not implemented for XML template examples"
360 if $to_xml && defined $args{typemap} && keys %{$args{typemap}};
361  
362 my @rewrite = $self->_key_rewrite(delete $args{key_rewrite});
363 my @blocked = $self->_block_nss(delete $args{block_namespace});
364  
365 my $table = $args{prefixes} = $self->_namespaceTable
366 (($args{prefixes} || $args{output_namespaces})
367 , $args{namespace_reset}
368 , !$args{use_default_namespace}
369 );
370  
371 my $used = $to_xml && $show{show_type};
372 $table->{&SCHEMA2001}
373 ||= +{prefix => 'xs', uri => SCHEMA2001, used => $used};
374 $table->{&SCHEMA2001i}
375 ||= +{prefix => 'xsi', uri => SCHEMA2001i, used => $used};
376  
377 my $transl = XML::Compile::Translate->new
378 ( 'TEMPLATE'
379 , nss => $self->namespaces
380 );
381  
382 my $compiled = $transl->compile
383 ( $type
384 , %args
385 , rewrite => \@rewrite
386 , block_namespace => \@blocked # not yet supported
387 , output => $action
388 );
389 $compiled or return;
390  
391 my $ast = $compiled->();
392 #use Data::Dumper; $Data::Dumper::Indent = 1; warn Dumper $ast;
393  
394 if($to_perl)
395 { return $transl->toPerl($ast, %show, indent => $indent
396 , skip_header => $args{skip_header})
397 }
398  
399 if($to_xml)
400 { my $doc = XML::LibXML::Document->new('1.1', 'UTF-8');
401 my $node = $transl->toXML($doc, $ast, %show
402 , indent => $indent, skip_header => $args{skip_header});
403 return $node->toString(1);
404 }
405  
406 # return tree
407 $ast;
408 }
409  
410 #------------------------------------------
411  
412  
413 sub namespaces() { shift->{namespaces} }
414  
415  
416 # The cache will certainly avoid penalties by the average module user,
417 # which does not understand the sharing schema definitions between objects
418 # especially in SOAP implementations.
419 my (%schemaByFilestamp, %schemaByChecksum);
420  
421 sub importDefinitions($@)
422 { my ($self, $frags, %options) = @_;
423 my @data = ref $frags eq 'ARRAY' ? @$frags : $frags;
424  
425 # this is a horrible hack, but by far the simpelest solution to
426 # avoid dataToXML process the same info twice.
427 local $self->{_use_cache} = 1;
428  
429 my @schemas;
430 foreach my $data (@data)
431 { defined $data or next;
432 my ($xml, %details) = $self->dataToXML($data);
433 %details = %{delete $options{details}} if $options{details};
434  
435 if(defined $xml)
436 { my @added = $self->addSchemas($xml, %details, %options);
437 if(my $checksum = $details{checksum})
438 { $self->{_cache_checksum}{$checksum} = \@added;
439 }
440 elsif(my $filestamp = $details{filestamp})
441 { $self->{_cache_file}{$filestamp} = \@added;
442 }
443 push @schemas, @added;
444 }
445 elsif(my $filestamp = $details{filestamp})
446 { my $cached = $self->{_cache_file}{$filestamp};
447 $self->namespaces->add(@$cached);
448 }
449 elsif(my $checksum = $details{checksum})
450 { my $cached = $self->{_cache_checksum}{$checksum};
451 $self->namespaces->add(@$cached);
452 }
453 }
454 @schemas;
455 }
456  
457 sub _parseScalar($)
458 { my ($thing, $data) = @_;
459  
460 ref $thing && $thing->{_use_cache}
461 or return $thing->SUPER::_parseScalar($data);
462  
463 my $self = $thing;
464 my $checksum = md5_hex $$data;
465 if($self->{_cache_checksum}{$checksum})
466 { trace "reusing string data with checksum $checksum";
467 return (undef, checksum => $checksum);
468 }
469  
470 trace "cache parsed scalar with checksum $checksum";
471  
472 ( $self->SUPER::_parseScalar($data)
473 , checksum => $checksum
474 );
475 }
476  
477 sub _parseFile($)
478 { my ($thing, $fn) = @_;
479  
480 ref $thing && $thing->{_use_cache}
481 or return $thing->SUPER::_parseFile($fn);
482 my $self = $thing;
483  
484 my ($mtime, $size) = (stat $fn)[9,7];
485 my $filestamp = File::Spec->rel2abs($fn) . '-'. $mtime . '-' . $size;
486  
487 if($self->{_cache_file}{$filestamp})
488 { trace "reusing schemas from file $filestamp";
489 return (undef, filestamp => $filestamp);
490 }
491  
492 trace "cache parsed file $filestamp";
493  
494 ( $self->SUPER::_parseFile($fn)
495 , filestamp => $filestamp
496 );
497 }
498  
499  
500 sub types()
501 { my $nss = shift->namespaces;
502 sort map {$_->types}
503 map {$nss->schemas($_)}
504 $nss->list;
505 }
506  
507  
508 sub elements()
509 { my $nss = shift->namespaces;
510 sort map {$_->elements}
511 map {$nss->schemas($_)}
512 $nss->list;
513 }
514  
515  
516 sub printIndex(@)
517 { my $self = shift;
518 $self->namespaces->printIndex(@_);
519 }
520  
521  
522 sub doesExtend($$)
523 { my $self = shift;
524 $self->namespaces->doesExtend(@_);
525 }
526  
527  
528 1;