File Coverage

blib/lib/Catmandu/Fix/xml_write.pm
Criterion Covered Total %
statement 7 9 77.7
branch n/a
condition n/a
subroutine 3 3 100.0
pod n/a
total 10 12 83.3


line stmt bran cond sub pod time code
1             package Catmandu::Fix::xml_write;
2              
3             our $VERSION = '0.16';
4              
5 1     1   15487 use Catmandu::Sane;
  1         73562  
  1         11  
6 1     1   274 use Moo;
  1         1  
  1         5  
7 1     1   1318 use XML::Struct::Writer;
  0            
  0            
8             use XML::LibXML::Reader;
9             use Catmandu::Fix::Has;
10              
11             with 'Catmandu::Fix::Base';
12              
13             has field => (fix_arg => 1);
14             has attributes => (fix_opt => 1);
15             has pretty => (fix_opt => 1);
16             has encoding => (fix_opt => 1, default => sub { 'UTF-8' });
17             has version => (fix_opt => 1);
18             has standalone => (fix_opt => 1);
19             has xmldecl => (fix_opt => 1, default => sub { 1 });
20              
21             has _writer => (
22             is => 'ro',
23             lazy => 1,
24             builder => sub {
25             XML::Struct::Writer->new(
26             map { $_ => $_[0]->$_ } grep { defined $_[0]->$_ }
27             qw(attributes pretty encoding version standalone xmldecl)
28             );
29             }
30             );
31              
32             sub emit {
33             my ($self,$fixer) = @_;
34              
35             my $path = $fixer->split_path($self->field);
36             my $key = pop @$path;
37            
38             my $writer = $fixer->capture($self->_writer);
39             my $pretty = $fixer->capture($self->pretty);
40              
41             return $fixer->emit_walk_path($fixer->var,$path,sub{
42             my $var = $_[0];
43             $fixer->emit_get_key($var,$key,sub{
44             my $var = $_[0];
45             return "${var} = (ref(${var}) =~ 'XML::LibXML::Document=')" .
46             "? ${var}->serialize(${pretty}) : do {".
47             "my \$s=''; ${writer}->to(\\\$s); ${writer}->write(${var}); \$s" .
48             "}";
49             });
50             });
51             }
52              
53             1;
54             __END__