File Coverage

blib/lib/Waft/JSON.pm
Criterion Covered Total %
statement 26 31 83.8
branch 6 10 60.0
condition 2 3 66.6
subroutine 8 8 100.0
pod 0 2 0.0
total 42 54 77.7


line stmt bran cond sub pod time code
1             package Waft::JSON;
2              
3 2     2   96108 use 5.005;
  2         7  
  2         66  
4 2     2   11 use strict;
  2         5  
  2         56  
5              
6 2     2   11 use vars qw( $VERSION );
  2         8  
  2         109  
7 2 50   2   4 BEGIN { eval { require warnings } ? 'warnings'->import : ( $^W = 1 ) }
  2         90  
8              
9 2     2   6 use Waft 0.9907 ();
  2         33  
  2         631  
10              
11             $VERSION = '0.03';
12             $VERSION = eval $VERSION;
13              
14             sub compile_template {
15 1     1 0 6532 my ($self, $template, $template_file, $template_class) = @_;
16              
17 1 50       6 if (ref $template eq 'SCALAR') {
18 0         0 $template = $$template;
19             }
20              
21             $template
22 1         19 =~ s{<% (?! \s*[\x0A\x0D]
23             =[A-Za-z]
24             )
25             \s* json \s* = (.*?)
26             %>}{<% \$Waft::Self->output( \$Waft::Self->convert_json($1) ); %>}gxms;
27              
28 1         10 return $self->next(\$template, $template_file, $template_class);
29             }
30              
31 4     4 0 612 sub convert_json { $_[0]->_make_json(@_[1 .. $#_]) }
32              
33             sub _make_json {
34 4     4   9 my ($self, @values) = @_;
35              
36             VALUE:
37 4         9 for my $value (@values) {
38 4 50       11 if ( not defined $value ) {
39 0         0 $self->warn('Use of uninitialized value');
40              
41 0         0 next VALUE;
42             }
43              
44 4 50 66     27 unless ( ref $value eq 'ARRAY' or ref $value eq 'HASH' ) {
45 0         0 $self->warn('Use of unencodable value to JSON');
46              
47 0         0 next VALUE;
48             }
49              
50 4         41 require JSON;
51 4         99 $value = JSON->new->encode($value);
52             }
53              
54 4 100       28 return wantarray ? @values : $values[0];
55             }
56              
57             1;
58             __END__