blib/lib/App/Netdisco/Template/Plugin/CSV.pm untested

filter: Statementstmt 0.0% 0 / 27 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 49 CC 4 SCAR 17.6
CC
4
Cov
0%
_neutralize
12.0
_flatten
6.0
dump
2.0
CRAP 5.8
1 package App::Netdisco::Template::Plugin::CSV;
2  
3 use strict;
4 use warnings;
5  
6 use base 'Template::Plugin::CSV';
7  
8 =head1 NAME
9  
10 App::Netdisco::Template::Plugin::CSV
11  
12 =head1 DESCRIPTION
13  
14 Registered in place of L<Template::Plugin::CSV> as the C<csv> plugin (see
15 C<engines.netdisco_template_toolkit.PLUGINS> in F<share/config.yml>), so
16 every C<*_csv.tt> template's C<[% USE CSV %]> picks this up with no
17 per-template change. A cell whose first character is C<=>, C<+>, C<->,
18 C<@> or a tab is prefixed with a single quote before
19 being written, unless the whole cell is already a plain number with an
20 optional leading minus sign. Line feeds and carriage returns at either end of
21 a cell are removed first, and each run of them inside it is written as a
22 single space, so every row stays on one line.
23  
24 =cut
25  
26 # A leading plus is deliberately not exempted.
27 my $VALID_NUMBER = qr/\A-?[0-9]+(?:\.[0-9]+)?\z/;
28  
29 sub _neutralize {
30 my $value = shift;
31 return $value if !defined($value) || $value =~ $VALID_NUMBER;
32 return $value =~ m/\A[=+\-\@\t\r]/ ? ("'" . $value) : $value;
33 }
34  
35 # Text::CSV without binary refuses a control character by dropping the whole
36 # row, and line breaks are the ones real values carry.
37 sub _flatten {
38 my $value = shift;
39 return $value if !defined($value);
40 # Trimmed rather than spaced at the ends, so a leading break cannot put a
41 # space in front of a formula trigger and hide it from _neutralize.
42 $value =~ s/\A[\r\n]+//;
43 $value =~ s/[\r\n]+\z//;
44 $value =~ s/[\r\n]+/ /g;
45 return $value;
46 }
47  
48 sub dump {
49 my ($self, $array) = @_;
50 $self->{csv}->combine(map { _neutralize(_flatten($_)) } @$array);
51 return $self->{csv}->string;
52 }
53  
54 sub dump_values {
55 my ($self, $h) = @_;
56 $self->{csv}->combine(map { _neutralize(_flatten($_)) } values %$h);
57 return $self->{csv}->string;
58 }
59  
60 1;