Pure/Utils.pm

filter: Statementstmt 12.5% 10 / 80 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 37.5% 3 / 8 Podpod 80.0% 4 / 5 totaltotal 9.6% 17 / 176 CC 29 SCAR 50.6
CC
29
Cov
7%
parse_match_spec
306.0
escape_html
42.0
parse_data_spec
30.0
CRAP 158.0
↑ Summary Pure/Iterator.pm »
1 package Template::Pure::Utils;
2
3 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 sub escape_html {
8 0 ▶ my ($value) = @_;
Subroutine escape_html: not called CC=6 SCAR=37.4
Pod undocumented
9 0 my %_escape_table = (
10 '&' => '&',
11 '>' => '>',
12 '<' => '&lt;',
13 q{"} => '&quot;',
14 q{'} => '&#39;' );
15  
16 0 ▶ if(
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($value) and $value->isa('Template::Pure::EncodedString')) { } 0 0 0
Condition0%0/3
builtin::blessed($value) and $value->isa("Template::Pure::EncodedString")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($value) and $value->isa("Template::Pure::EncodedString")
builtin::blessed($value) $value->isa("Template::Pure::EncodedString")
Truth table0%0/3
A and B
A= builtin::blessed($value)B= $value->isa("Template::Pure::EncodedString")
ABresult
0X0
100
111
17 Scalar::Util::blessed($value) &&
18 $value->isa('Template::Pure::EncodedString')
19 ) {
20 0 return $value;
21 } else {
22 0 ▶ $value =~ s/([&><"'])/$_escape_table{$1}/ge unless
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $value or builtin::blessed($value) and $value->isa("Template::Pure::UndefObject") 0 0 0
Condition0%0/6
not defined $value or builtin::blessed($value) and $value->isa("Template::Pure::UndefObject")
l!l&&r!l&&!r
000
builtin::blessed($value) and $value->isa("Template::Pure::UndefObject")
!ll&&!rl&&r
000
MC/DC0%0/3
not defined $value or builtin::blessed($value) and $value->isa("Template::Pure::UndefObject")
not defined $value builtin::blessed($value) $value->isa("Template::Pure::UndefObject")
Truth table0%0/4
not(A) or B and C
A= not defined $valueB= builtin::blessed($value)C= $value->isa("Template::Pure::UndefObject")
ABCresult
1XX1
0111
00X0
0100
23 !defined($value) ||
24 (Scalar::Util::blessed($value) && $value->isa('Template::Pure::UndefObject'));
25 0 return $value;
26 }
27 }
28  
29 sub parse_itr_spec {
30 0 ▶ my ($spec) = @_;
Subroutine parse_itr_spec: not called CC=1 SCAR=6.9
Pod documented
31 0 my ($key, $data_spec) = split('<-', $spec);
32 0 return $key => +{ parse_data_spec($data_spec) };
33 }
34  
35 sub parse_data_template {
36 0 ▶ my ($spec) = @_;
Subroutine parse_data_template: not called CC=4 SCAR=30.0
Pod documented
37 0 $spec=~s/[\n\r]//gs; # cleanup newlines.
38  
39 0 my $opentag = qr/=\{/;
40 0 my $closetag = qr/\}/;
41 0 my $placeholder = qr{(
42 (?:
43 $opentag (
44 (?:
45 (?> [^\=\{\}]+ )
46 |
47 (?2)
48 )*
49 ) $closetag
50 )
51 )}x;
52  
53 0 my @parts;
54 0 ▶ while($spec =~/( [^$opentag]+ ) | $placeholder /gx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /( [^$opentag]+ ) | $placeholder /gx) 0 0 0
55 0 ▶ my $part = $1||$2;
Condition0%0/3
$1 || $2
l!l&&r!l&&!r
000
MC/DC0%0/2
$1 || $2
$1 $2
Truth table0%0/3
A || B
A= $1B= $2
ABresult
1X1
011
000
56 0 ▶ if(my ($is_data_spec) = ($part=~/^$opentag(.+?)$closetag$/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($is_data_spec) = $part =~ /^$opentag(.+?)$closetag$/) { } 0 0 0
57 0 push @parts, +{ parse_data_spec($is_data_spec) };
58 } else {
59 0 push @parts, $part;
60 }
61 }
62  
63 0 return @parts;
64 }
65  
66 sub parse_data_spec {
67 0 ▶ my $spec = shift;
Subroutine parse_data_spec: not called CC=5 SCAR=34.0
Pod documented
68 0 $spec=~s/[\n\r]//gs; # cleanup newlines.
69 0 my $absolute = ($spec=~s[^\/][]);
70  
71 0 my @parts;
72 0 ▶ push @parts, $1 while $spec =~ /
Branch: 1 branch
BranchTrueFalseTotal
$spec =~ / ((?: [^()\|]+ | ( \( (?: [^()]+ | (?2) )* \) ) )*) (?: \|\s* | $) /gx and do { push @parts, $1 } 0 0 0
73 ((?:
74 [^()\|]+ |
75 ( \(
76 (?: [^()]+ | (?2) )*
77 \) )
78 )*)
79 (?: \|\s* | $)
80 /xg;
81  
82 my ($path_proto, @filters_proto) =
83 0 grep { length($_) > 0 }
84 0 map { $_=~s/^\s+|\s+$//g; $_ } @parts;
85  
86 0 my @path_proto = split(/\.|\//, $path_proto);
87  
88 my @path = map {
89 # Not ideal regexp here but safe enough I think since ':' is never in a method...
90 # Just would croak on a hash key that is meant to mean this. I'll doc that as
91 # 'don't do that...
92 0 my $maybe = ($_=~s/(maybe:)//);
93 0 my $optional = ($_=~s/(optional:)//);
94 0 +{ key => $_, maybe => $maybe, optional => $optional };
95 } @path_proto;
96  
97 my @filters = map {
98 0 my ($filter, $arg_proto) = ($_=~m/^(.*?)(?:\(\s*(.+?)?\s*\))?$/); # Borrowed from Catalyst::Controller
99 0 my @arg_parts;
100  
101 0 ▶ if($arg_proto) {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg_proto) 0 0 0
102 0 ▶ push @arg_parts, $1 while $arg_proto =~ /
Branch: 1 branch
BranchTrueFalseTotal
$arg_proto =~ / ((?: [^(),]+ | ( \( (?: [^()]+ | (?2) )* \) ) )*) (?: ,\s* | $) /gx and do { push @arg_parts, $1 } 0 0 0
103 ((?:
104 [^(),]+ |
105 ( \(
106 (?: [^()]+ | (?2) )*
107 \) )
108 )*)
109 (?: ,\s* | $)
110 /xg;
111 }
112  
113 my @args = map {
114 0 my ($data_spec) = ($_=~/^\=\{(.+?)\}$/);
115 0 ▶ $data_spec ? +{ parse_data_spec($data_spec) } : eval $_;
Branch: 1 branch
BranchTrueFalseTotal
$data_spec ? : 0 0 0
116 } grep {
117 0 length($_) > 0;
118 } @arg_parts;
119  
120 0 +[ $filter, @args ];
121 } @filters_proto;
122  
123 return (
124 0 absolute => $absolute,
125 path => \@path,
126 filters => \@filters,
127 );
128 }
129  
130 sub parse_match_spec {
131 0 ▶ my $spec = shift;
Subroutine parse_match_spec: not called CC=17 SCAR=57.2
Pod documented
132  
133 # Look for all the possibilities, try to leave $spec in a useful state
134 0 my $maybe_target_node = ($spec=~s/^\^//);
135 0 my $maybe_filter = ($spec=~s/\|$//);
136 0 my $maybe_prepend = ($spec=~s/^(\+)//);
137 0 my $maybe_append = ($spec=~s/(\+)$//);
138 0 my $maybe_absolute = ($spec=~s[^\/][]);
139  
140 0 my ($css, $maybe_attr) = split('@', $spec);
141 0 ▶ $css = '.' if $maybe_attr && !$css; # $css unlikely to be 0
Branch: 1 branch
BranchTrueFalseTotal
if $maybe_attr and not $css 0 0 0
Condition0%0/3
$maybe_attr and not $css
!ll&&!rl&&r
000
MC/DC0%0/2
$maybe_attr and not $css
$maybe_attr not $css
Truth table0%0/3
A and not(B)
A= $maybe_attrB= not $css
ABresult
0X0
100
111
142  
143 # All the error conditions I can think of.
144 0 ▶ die "You need a CSS style match: '$spec'"
Branch: 1 branch
BranchTrueFalseTotal
unless $css 0 0 0
145 unless $css;
146  
147 0 ▶ die "Can't add a filter when appending or prepending: '$spec'"
Branch: 1 branch
BranchTrueFalseTotal
if $maybe_filter and $maybe_append || $maybe_prepend 0 0 0
Condition0%0/6
$maybe_filter and $maybe_append || $maybe_prepend
!ll&&!rl&&r
000
$maybe_append or $maybe_prepend
l!l&&r!l&&!r
000
MC/DC0%0/3
$maybe_filter and $maybe_append || $maybe_prepend
$maybe_filter $maybe_append $maybe_prepend
Truth table0%0/4
A and B or C
A= $maybe_filterB= $maybe_appendC= $maybe_prepend
ABCresult
0XX0
1000
11X1
1011
148 if $maybe_filter && ($maybe_append || $maybe_prepend);
149  
150 0 ▶ die "Can't set a target when filtering: '$spec'"
Branch: 1 branch
BranchTrueFalseTotal
if $maybe_filter and $maybe_target_node || $maybe_attr 0 0 0
Condition0%0/6
$maybe_filter and $maybe_target_node || $maybe_attr
!ll&&!rl&&r
000
$maybe_target_node or $maybe_attr
l!l&&r!l&&!r
000
MC/DC0%0/3
$maybe_filter and $maybe_target_node || $maybe_attr
$maybe_filter $maybe_target_node $maybe_attr
Truth table0%0/4
A and B or C
A= $maybe_filterB= $maybe_target_nodeC= $maybe_attr
ABCresult
0XX0
1000
11X1
1011
151 if $maybe_filter && ($maybe_target_node || $maybe_attr);
152  
153 0 ▶ die "Can't set a target attribute and target node: '$spec'"
Branch: 1 branch
BranchTrueFalseTotal
if $maybe_target_node and $maybe_attr 0 0 0
Condition0%0/3
$maybe_target_node and $maybe_attr
!ll&&!rl&&r
000
MC/DC0%0/2
$maybe_target_node and $maybe_attr
$maybe_target_node $maybe_attr
Truth table0%0/3
A and B
A= $maybe_target_nodeB= $maybe_attr
ABresult
0X0
100
111
154 if $maybe_target_node && $maybe_attr;
155  
156 0 my $target = 'content';
157 0 ▶ if($maybe_target_node) {
Branch: 2 branches
BranchTrueFalseTotal
if ($maybe_target_node) { } 0 0 0
elsif ($maybe_attr) { } 0 0 0
158 0 $target = 'node';
159 } elsif($maybe_attr) {
160 0 $target = \$maybe_attr;
161 }
162  
163 0 my $mode = 'replace';
164 0 ▶ if($maybe_append) {
Branch: 3 branches
BranchTrueFalseTotal
if ($maybe_append) { } 0 0 0
elsif ($maybe_prepend) { } 0 0 0
elsif ($maybe_filter) { } 0 0 0
165 0 $mode = 'append';
166 } elsif($maybe_prepend) {
167 0 $mode = 'prepend';
168 } elsif($maybe_filter) {
169 0 $mode = 'filter';
170 0 $target = '';
171 }
172  
173 return (
174 0 absolute => $maybe_absolute,
175 css => $css,
176 target => $target,
177 mode => $mode,
178 );
179 }
180  
181 13 1;
182  
183 =head1 NAME
184  
185 Template::Pure::Utils - Utility Functions
186  
187 =head1 SYNOPSIS
188  
189 For internal use
190  
191 =head1 DESCRIPTION
192  
193 Contains utility functions for L<Template::Pure>
194  
195 =head1 FUNCTIONS
196  
197 This package contains the following functions:
198  
199 =head2 parse_itr_spec ($spec)
200  
201 Used to parse a string when we are specifying an iterator. For example
202  
203 "user<-users"
204  
205 or:
206  
207 "friend<-user.friends"
208  
209 Returns a hashref when the key is the new data label and the value is a reference to the
210 indicated path from the current data context.
211  
212 {
213 user => {
214 absolute => '';
215 filters => [],
216 path => [
217 key => 'users',
218 maybe => '',
219 optional => ''
220 ],
221 },
222 }
223  
224 B<NOTE> you cannot use a filter on an iterator specification.
225  
226 B<NOTE> Indicated data context path must be something that can be coerced into an iterator
227 (an arrayref, a hashref, or an Object that provides the iterator interface).
228  
229 =head2 parse_data_template ($spec)
230  
231 Used to parse a string that is the target action of a match, when the string contains
232 template placeholders, for example:
233  
234 "Hello ={meta.first_name} ={meta.last_name}!"
235  
236 Which is intended to be parsed as containing a string with two placeholders, each pointing
237 to a different path on the current data context.
238  
239 When parsed returns an array, where each element is either a string (for a literal string
240 value) or a hash reference (indicates a patch to a value on the current data context).
241  
242 For example the shown string would parse in this way:
243  
244 (
245 'Hello ',
246 {
247 absolute => '',
248 filters => [],
249 path => [
250 { key => 'meta', optional => undef, maybe => undef },
251 { key => 'first_name', optional => undef, maybe => undef },
252 },
253 ' ',
254 {
255 absolute => '',
256 filters => [],
257 path => [
258 { key => 'meta', optional => undef, maybe => undef },
259 { key => 'first_name', optional => undef, maybe => undef },
260 },
261 '!',
262 );
263  
264 Information inside the placeholder may contain filters and prefixes and other markers:
265  
266 "Year of Birth: ={/maybe:meta.optional:dob | strftime(%Y)}"
267  
268 Would parse as:
269  
270 (
271 'Year of Birth: ',
272 {
273 absolute => '1',
274 filters => [
275 ['strftime', '%Y'],
276 ],
277 path => [
278 { key => 'meta', optional => undef, maybe => 1 },
279 { key => 'dob', optional => 1, maybe => undef },
280 },
281 );
282  
283  
284 =head2 parse_data_spec ($spec)
285  
286 When the action target is a string we need to inspect it to figure out what do do with it.
287 Returns a hash with keys as follows:
288  
289 =over 4
290  
291 =item absolute
292  
293 Boolean. Defaults to False. When true this means the described path should be absolute
294 from the top of the data context. Otherwise the described path is relative to the current
295 point selected in the data context.
296  
297  
298 =item path
299  
300 Example:
301  
302 path => [
303 {
304 key => 'meta',
305 optional => 0,
306 maybe => 0
307 },
308 {
309 key => 'title',
310 optional => 0,
311 maybe => 0
312 }
313 ];
314  
315 An array hashrefs that indicate path parts from the current data context to the value we
316 wish to use. Each hashref contains three keys:
317  
318 =over 4
319  
320 =item key
321  
322 The name that is a 'key' point on the path. Likely to be a key in a hash or a method on an
323 object.
324  
325 =item optional
326  
327 Boolean. Defaults to false. Generally if the key does not match a real path on the current
328 data context, this should return an error. If this value is false, that means instead of
329 throwing an error we return an 'undef'.
330  
331 Value is derived from the prefix 'optional:'. Presence of this prefix sets this to true.
332  
333 B<NOTE> since 'optional:' has special meaning here, this means that if your data context is
334 a hash, you should not have any keys that match 'optional:' for your own purposes... If you
335 really run into this you'll have to write an anonymous subroutine type action.
336  
337 =item maybe
338  
339 Boolean. Defaults to false. Generally if you have several path parts and a midpoint part
340 returns undefined, that mean we throw an exception on later parts (can't find a next path on
341 an undefined value). In some cases (like when you are chaining resultset methods in L<DBIx::Class>)
342 we might not prefer tothrow an error but just return 'undef'. When a path is 'maybe' we
343 wrap in in an object such that the next path is always found (but returns undef).
344  
345 Value is derived from the prefix 'maybe:'. Presence of this prefix sets this to true.
346  
347 B<NOTE> since 'maybe:' has special meaning here, this means that if your data context is
348 a hash, you should not have any keys that match 'maybe:' for your own purposes... If you
349 really run into this you'll have to write an anonymous subroutine type action.
350  
351 =back
352  
353 =item filters
354  
355 An Arrayref of Arrayrefs which are any filters added to the value and their arguments.
356  
357 Example:
358  
359 filters => [
360 [ 'repeat', '3'],
361 [ 'escape_html' ],
362 ];
363  
364 In some cases the arguments for a filter might itself point to a resolved data spec (which itself
365 could include filters... In this case the argument value will be a hashref that is itself the
366 result of a call to L</parse_data_spec>, example:
367  
368 (
369 path => [
370 {
371 key => 'meta', maybe => 0, optional => 0,
372 },
373 {
374 key => 'title', maybe => 0, optional => 0,
375 },
376 ],
377 filters => [
378 ['title_case'],
379 ['truncate',
380 {
381 path => [
382 { key => 'settings', maybe => 0, optional => 0 },
383 { key => 'title_length', maybe => 0, optional => 0 },
384 ],
385 filters => [],
386 },
387 '...',
388 ],
389 ],
390 );
391  
392 You'd have a string to parse like "meta.title | title_case | truncate(={settings.title_length},'...')"
393 which has a filter 'truncate' that has two args, the first being 'whatever the value is at
394 'settings.title_length'' and the second is a literal '...'.
395  
396 You could go wild here with nested values and filters but I recommend if you have such complex
397 needs it would be better to do it in Perl with an anonymous subroutine rather than over cleverness
398 in the string based DSL, which will never be as good as Perl itself. Use it for straight and simple
399 things and for when you want to let non Perl programmers work with the directives.
400  
401 B<NOTE> we run C<eval> on each argument to convert it to a Perl data value, so you could in
402 theory do fancy stuff here like "filter(1+2+3)" and get an arg of '3'. I highly recommend constraint
403 in this. Since its C<eval>'d you should be certain these values are properly cleaned and untainted.
404 For example beware of something like "filter($a)", where $a comes from uncontrolled source such as the
405 input of a HTML Form post, or from external sources like a database or file. This could be considered
406 a possible injection attack location. Because of this we might someday switch this to a non eval
407 parser such as L<Data::Pond> or similar, and if you did crazy expression stuff that don't work with
408 a more restrictive and safe expression parser, its possible your code will break. Buyer beware.
409  
410 B<NOTE> The values for the boolean keys 'maybe' and 'optional' are only specificed to return a
411 Perl value to be evaluated as a boolean. We don't specify the exact value. For example, under Perl
412 both 0 and undef are considered false in boolean context.
413  
414 =back
415  
416 =head2 parse_match_spec ($spec)
417  
418 Given a directive match specification (such as '#head', 'title', 'p.links@href', ...) parse
419 it into a hash that defines how the match is to be performed. Returns a hash with keys are
420 follows.
421  
422 =over 4
423  
424 =item css
425  
426 This is the actual CSS match component ('p', '#id', '.class') or the special match indicator of
427 '.' for the current node.
428  
429 =item target
430  
431 This is the indicator of the replacement target for the match. Can be: 'node', 'content', \'$attribute':
432  
433 =over 4
434  
435 =item content
436  
437 Example Match Specifiction: 'p.headline', 'title', '#id'
438  
439 This is the default value for target. Indicates we will update the matched nodes' content. For example the
440 content of node '<p>content</p>' is 'content'. No special symbols are needed to indicate this target type.
441  
442 =item \$attribute
443  
444 Example Match Specifiction: 'a#homepage@href', 'ul.links@class'
445  
446 When the value of 'target' is a scalar reference, this indicates the update type to be an attribute on the current
447 matched node. The dereferenced scalar is the name of the attribute. If the attribute does not exist in the current
448 node this does not raise an exception, but rather we automatically add it.
449  
450 It is an error to indicate both node and attribute targets.
451  
452 B<NOTE> Should a match specification consist only of an attribute, we presume a 'css' value of '.'
453  
454 =item node
455  
456 Example Match Specifiction: '^p.headline', '^#id'
457  
458 Indicated a target of 'node', which means we will replace the entire matched node. Indicated by a '^' appearing
459 as the first character of the match specification.
460  
461 It is an error to indicate both node and attribute targets.
462  
463 =back
464  
465 =item mode
466  
467 Defines the relationship, if any, between a new value from the data context and any existing information
468 in the template and the match location. One of 'append', 'prepend', or 'replace', with 'replace' being the default.
469  
470 =over 4
471  
472 =item replace
473  
474 Example Match Specifiction: 'title', '#id', 'p.content@class'
475  
476 The default behavior. Needs no special indicators in the match specification. Means the new value
477 completely replaces the match target.
478  
479 =item append
480  
481 Example Match Specifiction: 'title+', '#id+', 'p.content@class+'
482  
483 Match specifications that end with '+' will append to the indicated match (that is we place the
484 new value after the old value, preserving th old value.
485  
486 It is an error to try to set both append and prepend mode on the same target. It is also an error
487 to use append and prepend along with a filter indicator (see below).
488  
489 When appending to a target of attribute where the attribute is 'class', we automatically add a ' ' (space)
490 between the appending value and any existing value. This is a special case since generally a space
491 is required between classes in order for them to work as expected.
492  
493 =item prepend
494  
495 Example Match Specifiction: '+body', '+p.content@class'
496  
497 Match specifications that begin with a '+' (or '^+') indicate we expect to add the data context to the
498 front of the existing value, preserving the existing value.
499  
500 It is an error to try to set both append and prepend mode on the same target. It is also an error
501 to use append and prepend along with a filter indicator (see below).
502  
503 When prepending to a target of attribute where the attribute is 'class', we automatically add a ' ' (space)
504 between the appending value and any existing value. This is a special case since generally a space
505 is required between classes in order for them to work as expected.
506  
507 =item filter
508  
509 Example Match Specification: 'html|', 'body|'
510  
511 Means that we expect to run a filter callback on the matched node. Useful when you want to make global
512 changes across the entire template. Indicated by a '|' or pipe symbol. Cannot be used with append,
513 prepend or any special target indicators (attributes or node).
514  
515 We expect the action the be an anonymous subroutine.
516  
517 =back
518  
519 =head1 SEE ALSO
520
521 L<Template::Pure>.
522  
523 =head1 AUTHOR
524
525 John Napiorkowski L<email:jjnapiork@cpan.org>
526  
527 But lots of this code was copied from L<Template::Filters> and other prior art on CPAN. Thanks!
528
529 =head1 COPYRIGHT & LICENSE
530
531 Please see L<Template::Pure> for copyright and license information.
532  
533 =cut
↑ Summary Pure/Iterator.pm »