blib/lib/OODoc/Template.pm untested

filter: Statementstmt 0.0% 0 / 241 Branchbran 0.0% 0 / 132 Conditioncond 0.0% 0 / 81 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 490 CC 67 SCAR 49.3
CC
67
Cov
0%
process
420.0
valueFor
132.0
pushValues
72.0
CRAP 138.1
1 # Copyrights 2003,2007-2021 by [Mark Overmeer].
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 perl distribution OODoc-Template. It is licensed under
6 # the same terms as Perl itself: https://spdx.org/licenses/Artistic-2.0.html
7  
8 use strict;
9 use warnings;
10  
11 package OODoc::Template;
12 use vars '$VERSION';
13 $VERSION = '0.17';
14  
15  
16 use Log::Report 'oodoc-template';
17  
18 use IO::File ();
19 use File::Spec ();
20 use Data::Dumper qw(Dumper);
21 use Scalar::Util qw(weaken);
22  
23 my @default_markers = ('<!--{', '}-->', '<!--{/', '}-->');
24  
25  
26 sub new(@)
27 { my ($class, %args) = @_;
28 (bless {}, $class)->init(\%args);
29 }
30  
31 sub init($)
32 { my ($self, $args) = @_;
33  
34 $self->{cached} = {};
35 $self->{macros} = {};
36  
37 my $s = $self; weaken $s; # avoid circular ref
38 $args->{template} ||= sub { $s->includeTemplate(@_) };
39 $args->{macro} ||= sub { $s->defineMacro(@_) };
40  
41 $args->{search} ||= '.';
42 $args->{markers} ||= \@default_markers;
43 $args->{define} ||= sub { shift; (1, @_) };
44  
45 $self->pushValues($args);
46 $self;
47 }
48  
49  
50 sub process($)
51 { my ($self, $templ) = (shift, shift);
52  
53 my $values = @_==1 ? shift : @_ ? {@_} : {};
54  
55 my $tree # parse with real copy
56 = ref $templ eq 'SCALAR' ? $self->parseTemplate($$templ)
57 : ref $templ eq 'ARRAY' ? $templ
58 : $self->parseTemplate("$templ");
59  
60 defined $tree
61 or return ();
62  
63 $self->pushValues($values)
64 if keys %$values;
65  
66 my @output;
67 foreach my $node (@$tree)
68 { unless(ref $node)
69 { push @output, $node;
70 next;
71 }
72
73 my ($tag, $attr, $then, $else) = @$node;
74  
75 my %attrs;
76 while(my($k, $v) = each %$attr)
77 { $attrs{$k} = ref $v ne 'ARRAY' ? $v
78 : @$v==1 ? scalar $self->valueFor(@{$v->[0]})
79 : join '',
80 map {ref $_ eq 'ARRAY' ? scalar $self->valueFor(@$_) : $_}
81 @$v;
82 }
83  
84 (my $value, my $attrs, $then, $else)
85 = $self->valueFor($tag, \%attrs, $then, $else);
86  
87 unless(defined $then || defined $else)
88 { defined $value
89 or next;
90  
91 ref $value ne 'ARRAY' && ref $value ne 'HASH'
92 or error __x"value for {tag} is {value}, must be single"
93 , tag => $tag, value => $value;
94  
95 push @output, $value;
96 next;
97 }
98  
99 my $take_else
100 = !defined $value || (ref $value eq 'ARRAY' && @$value==0);
101  
102 my $container = $take_else ? $else : $then;
103  
104 defined $container
105 or next;
106  
107 $self->pushValues($attrs) if keys %$attrs;
108  
109 if($take_else)
110 { my ($nest_out, $nest_tree) = $self->process($container);
111 push @output, $nest_out;
112 $node->[3] = $nest_tree;
113 }
114 elsif(ref $value eq 'HASH')
115 { my ($nest_out, $nest_tree) = $self->process($container, $value);
116 push @output, $nest_out;
117 $node->[2] = $nest_tree;
118 }
119 elsif(ref $value eq 'ARRAY')
120 { foreach my $data (@$value)
121 { my ($nest_out, $nest_tree) = $self->process($container, $data);
122 push @output, $nest_out;
123 $node->[2] = $nest_tree;
124 }
125 }
126 else
127 { my ($nest_out, $nest_tree) = $self->process($container);
128 push @output, $nest_out;
129 $node->[2] = $nest_tree;
130 }
131  
132 $self->popValues if keys %$attrs;
133 }
134
135 $self->popValues if keys %$values;
136  
137 wantarray ? (join('', @output), $tree) # LIST context
138 : defined wantarray ? join('', @output) # SCALAR context
139 : print @output; # VOID context
140 }
141  
142  
143 sub processFile($;@)
144 { my ($self, $filename) = (shift, shift);
145  
146 my $values = @_==1 ? shift : {@_};
147 $values->{source} ||= $filename;
148  
149 my $cache = $self->{cached};
150  
151 my ($output, $tree, $template);
152 if(exists $cache->{$filename})
153 { $tree = $cache->{$filename};
154 $output = $self->process($tree, $values)
155 if defined $tree;
156 }
157 elsif($template = $self->loadFile($filename))
158 { ($output, $tree) = $self->process($template, $values);
159 $cache->{$filename} = $tree;
160 }
161 else
162 { $tree = $cache->{$filename} = undef;
163 }
164  
165 defined $tree || defined wantarray
166 or error __x"cannot find template file {fn}", fn => $filename;
167  
168 wantarray ? ($output, $tree) # LIST context
169 : defined wantarray ? $output # SCALAR context
170 : print $output; # VOID context
171 }
172  
173  
174 sub defineMacro($$$$)
175 { my ($self, $tag, $attrs, $then, $else) = @_;
176 my $name = delete $attrs->{name}
177 or error __x"macro requires a name";
178  
179 defined $else
180 and error __x"macros cannot have an else part ({macro})",macro => $name;
181  
182 my %attrs = %$attrs; # for closure
183 $attrs{markers} = $self->valueFor('markers');
184  
185 $self->{macros}{$name} =
186 sub { my ($tag, $at) = @_;
187 $self->process($then, +{%attrs, %$at});
188 };
189  
190 ();
191
192 }
193  
194  
195 sub valueFor($;$$$)
196 { my ($self, $tag, $attrs, $then, $else) = @_;
197  
198 #warn "Looking for $tag";
199 #warn Dumper $self->{values};
200 for(my $set = $self->{values}; defined $set; $set = $set->{NEXT})
201 { my $v = $set->{$tag};
202  
203 if(defined $v)
204 { # HASH defines container
205 # ARRAY defines container loop
206 # object or other things can be stored as well, but may get
207 # stringified.
208 return wantarray ? ($v, $attrs, $then, $else) : $v
209 if ref $v ne 'CODE';
210  
211 return wantarray
212 ? $v->($tag, $attrs, $then, $else)
213 : ($v->($tag, $attrs, $then, $else))[0]
214 }
215  
216 return wantarray ? (undef, $attrs, $then, $else) : undef
217 if exists $set->{$tag};
218  
219 my $code = $set->{DYNAMIC};
220 if(defined $code)
221 { my ($value, @other) = $code->($tag, $attrs, $then, $else);
222 return wantarray ? ($value, @other) : $value
223 if defined $value;
224 # and continue the search otherwise
225 }
226 }
227  
228 wantarray ? (undef, $attrs, $then, $else) : undef;
229 }
230  
231  
232 sub allValuesFor($;$$$)
233 { my ($self, $tag, $attrs, $then, $else) = @_;
234 my @values;
235  
236 for(my $set = $self->{values}; defined $set; $set = $set->{NEXT})
237 {
238 if(defined(my $v = $set->{$tag}))
239 { my $t = ref $v eq 'CODE' ? $v->($tag, $attrs, $then, $else) : $v;
240 push @values, $t if defined $t;
241 }
242  
243 if(defined(my $code = $set->{DYNAMIC}))
244 { my $t = $code->($tag, $attrs, $then, $else);
245 push @values, $t if defined $t;
246 }
247 }
248  
249 @values;
250 }
251  
252  
253 sub pushValues($)
254 { my ($self, $attrs) = @_;
255  
256 if(my $markers = $attrs->{markers})
257 { my @markers = ref $markers eq 'ARRAY' ? @$markers
258 : map {s/\\\,//g; $_} split /(?!<\\)\,\s*/, $markers;
259  
260 push @markers, $markers[0] . '/'
261 if @markers==2;
262  
263 push @markers, $markers[1]
264 if @markers==3;
265  
266 $attrs->{markers}
267 = [ map { ref $_ eq 'Regexp' ? $_ : qr/\Q$_/ } @markers ];
268 }
269  
270 if(my $search = $attrs->{search})
271 { $attrs->{search} = [ split /\:/, $search ]
272 if ref $search ne 'ARRAY';
273 }
274  
275 $self->{values} = { %$attrs, NEXT => $self->{values} };
276 }
277  
278  
279 sub popValues()
280 { my $self = shift;
281 $self->{values} = $self->{values}{NEXT};
282 }
283  
284  
285 sub includeTemplate($$$)
286 { my ($self, $tag, $attrs, $then, $else) = @_;
287  
288 defined $then || defined $else
289 and error __x"template is not a container";
290  
291 if(my $fn = $attrs->{file})
292 { my $output = $self->processFile($fn, $attrs);
293 $output = $self->processFile($attrs->{alt}, $attrs)
294 if !defined $output && $attrs->{alt};
295  
296 defined $output
297 or error __x"cannot find template file {fn}", fn => $fn;
298  
299 return ($output);
300 }
301  
302 if(my $name = $attrs->{macro})
303 { my $macro = $self->{macros}{$name}
304 or error __x"cannot find macro {name}", name => $name;
305  
306 return $macro->($tag, $attrs, $then, $else);
307 }
308  
309 error __x"file or macro attribute required for template in {source}"
310 , source => $self->valueFor('source') || '??';
311 }
312  
313  
314 sub loadFile($)
315 { my ($self, $relfn) = @_;
316 my $absfn;
317  
318 if(File::Spec->file_name_is_absolute($relfn))
319 { my $fn = File::Spec->canonpath($relfn);
320 $absfn = $fn if -f $fn;
321 }
322  
323 unless($absfn)
324 { my @srcs = map { @$_ } $self->allValuesFor('search');
325 foreach my $dir (@srcs)
326 { $absfn = File::Spec->rel2abs($relfn, $dir);
327 last if -f $absfn;
328 $absfn = undef;
329 }
330 }
331  
332 defined $absfn
333 or return undef;
334  
335 my $in = IO::File->new($absfn, 'r');
336 unless(defined $in)
337 { my $source = $self->valueFor('source') || '??';
338 fault __x"Cannot read from {fn} in {file}", fn => $absfn, file=>$source;
339 }
340  
341 \(join '', $in->getlines); # auto-close in
342 }
343  
344  
345 sub parse($@)
346 { my ($self, $template) = (shift, shift);
347 $self->process(\$template, @_);
348 }
349  
350  
351 sub parseTemplate($)
352 { my ($self, $template) = @_;
353  
354 defined $template
355 or return undef;
356  
357 my $markers = $self->valueFor('markers');
358  
359 # Remove white-space escapes
360 $template =~ s! \\ (?: \s* (?: \\ \s*)? \n)+
361 (?: \s* (?= $markers->[0] | $markers->[3] ))?
362 !!mgx;
363  
364 my @frags;
365  
366 # NOT_$tag supported for backwards compat
367 while( $template =~ s!^(.*?) # text before container
368 $markers->[0] \s*
369 (?: IF \s* )?
370 (NOT (?:_|\s+) )?
371 ([\w.-]+) \s* # tag
372 (.*?) \s* # attributes
373 $markers->[1]
374 !!xs
375 )
376 { push @frags, $1;
377 my ($not, $tag, $attr) = ($2, $3, $4);
378 my ($then, $else);
379  
380 if($template =~ s! (.*?) # contained
381 ( $markers->[2]
382 \s* \Q$tag\E \s* # "our" tag
383 $markers->[3]
384 )
385 !!xs)
386 { $then = $1;
387 my $endline = $2;
388 }
389  
390 if($not) { ($then, $else) = (undef, $then) }
391 elsif(!defined $then) { }
392 elsif($then =~ s! $markers->[0]
393 \s* ELSE (?:_|\s+)
394 \Q$tag\E \s*
395 $markers->[1]
396 (.*)
397 !!xs)
398 { # ELSE_$tag for backwards compat
399 $else = $1;
400 }
401  
402 push @frags, [$tag, $self->parseAttrs($attr), $then, $else];
403 }
404  
405 push @frags, $template;
406 \@frags;
407 }
408  
409  
410 sub parseAttrs($)
411 { my ($self, $string) = @_;
412  
413 my %attrs;
414 while( $string =~
415 s!^\s* (?: '([^']+)' # attribute name (might be quoted)
416 | "([^"]+)"
417 | (\w+)
418 )
419 \s* (?: \= \>? \s* # an optional value
420 ( \"[^"]*\" # dquoted value
421 | \'[^']*\' # squoted value
422 | \$\{ [^}]+ \} # complex variable
423 | [^\s,]+ # unquoted value
424 )
425 )?
426 \s* \,? # optionally separated by commas
427 !!xs)
428 { my ($k, $v) = ($1||$2||$3, $4);
429 unless(defined $v)
430 { $attrs{$k} = 1;
431 next;
432 }
433  
434 if($v =~ m/^\'(.*)\'$/)
435 { # Single quoted parameter, no interpolation
436 $attrs{$k} = $1;
437 next;
438 }
439  
440 $v =~ s/^\"(.*)\"$/$1/;
441 my @v = split /( \$\{[^\}]+\} | \$\w+ )/x, $v;
442  
443 if(@v==1 && $v[0] !~ m/^\$/)
444 { $attrs{$k} = $v[0];
445 next;
446 }
447  
448 my @steps;
449 foreach (@v)
450 { if( m/^ (?: \$(\w+) | \$\{ (\w+) \s* \} ) $/x )
451 { push @steps, [ $+ ];
452 }
453 elsif( m/^ \$\{ (\w+) \s* ([^\}]+? \s* ) \} $/x )
454 { push @steps, [ $1, $self->parseAttrs($2) ];
455 }
456 else
457 { push @steps, $_ if length $_;
458 }
459 }
460  
461 $attrs{$k} = \@steps;
462 }
463  
464 error __x"attribute error in '{tag}'", tag => $_[1]
465 if length $string;
466  
467 \%attrs;
468 }
469  
470  
471 1;