Pure/ParseUtils.pm

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