blib/lib/HTML/FormatText/WithLinks/AndTables.pm

filter: Statementstmt 100% 114 / 114 Branchbran 87.5% 42 / 48 Conditioncond 80.0% 8 / 10 MC/DCmcdc 66.6% 4 / 6 Subroutinesub 100% 8 / 8 Podpod 66.6% 2 / 3 totaltotal 94.1% 178 / 189 CC 34 SCAR 29.5
CC
34
Cov
95%
_format_tables
27.0
convert
6.6
parse
3.1
CRAP 19.1
↑ Summary
1 package HTML::FormatText::WithLinks::AndTables;
2  
3 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 7 our $VERSION = '0.07'; # VERSION
7  
8 7 ▶use base 'HTML::FormatText::WithLinks';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use HTML::TreeBuilder;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 ################################################################################
12 # configuration defaults
13 ################################################################################
14 7 my $cellpadding = 1; # number of horizontal spaces to pad interior of <td> cells
15 7 my $no_rowspacing = 0; # boolean, suppress space between table rows and rows with empty <td>s
16 ################################################################################
17  
18 =head1 NAME
19  
20 HTML::FormatText::WithLinks::AndTables - Converts HTML to Text with tables intact
21  
22 =head1 VERSION
23  
24 version 0.07
25  
26 =cut
27  
28 =head1 SYNOPSIS
29  
30 use HTML::FormatText::WithLinks::AndTables;
31  
32 my $text = HTML::FormatText::WithLinks::AndTables->convert($html);
33  
34 Or optionally...
35  
36 my $conf = { # same as HTML::FormatText excepting below
37 cellpadding => 2, # defaults to 1
38 no_rowspacing => 1, # bool, suppress vertical space between table rows
39 };
40  
41 my $text = HTML::FormatText::WithLinks::AndTables->convert($html, $conf);
42  
43 =head1 DESCRIPTION
44  
45 This module was inspired by HTML::FormatText::WithLinks which has proven to be a
46 useful `lynx -dump` work-alike. However one frustration was that no other HTML
47 converters I came across had the ability to deal affectively with HTML <TABLE>s.
48 This module can in a rudimentary sense do so. The aim was to provide facility to take
49 a simple HTML based email template, and to also convert it to text with the <TABLE>
50 structure intact for inclusion as "multipart/alternative" content. Further, it will
51 preserve both the formatting specified by the <TD> tag's "align" attribute, and will
52 also preserve multiline text inside of a <TD> element provided it is broken using <BR/>
53 tags.
54  
55 =head2 EXPORT
56  
57 None by default.
58  
59  
60 =head1 METHODS
61  
62 =head2 convert
63  
64 =cut
65  
66 7 my $parser_indent = 3; # HTML::FormatText::WithLinks adds this indent to <table> data
67 7 my $conf_defaults = {};
68  
69 # the one and only public interface
70 6 ▶sub convert {
Subroutine convert: called CC=6 SCAR=18.8
Pod documented
71 6 ▶ shift if $_[0] eq __PACKAGE__; # to make it function friendly
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] eq __PACKAGE__ 6 0 6
72 6 my ($html, $conf) = @_;
73  
74 # over-ride our defaults
75 6 ▶ if ($conf and ref $conf eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($conf and ref $conf eq "HASH") 6 0 6
Condition33%1/3
$conf and ref $conf eq "HASH"
!ll&&!rl&&r
006
MC/DC0%0/2
$conf and ref $conf eq "HASH"
$conf ref $conf eq "HASH"
Truth table33%1/3
A and B
A= $confB= ref $conf eq "HASH"
ABresult
0X0
100
111
76 6 ▶ $no_rowspacing = $$conf{no_rowspacing} if $$conf{no_rowspacing};
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"no_rowspacing"} 0 6 6
77 6 delete $$conf{no_rowspacing};
78 6 ▶ $cellpadding = $$conf{cellpadding} if $$conf{cellpadding};
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"cellpadding"} 5 1 6
79 6 delete $$conf{cellpadding};
80 6 %$conf_defaults = (%$conf_defaults, %$conf);
81 }
82  
83 6 return __PACKAGE__->new->parse($html);
84 }
85  
86 # sub-class configure
87 18 ▶sub configure {
Subroutine configure: called CC=1 SCAR=0.0
Pod undocumented
88 # SUPER::configure actually modifies the hash, so we need to pass a copy
89 18 my %configure = %$conf_defaults;
90  
91 18 shift()->SUPER::configure(\%configure);
92 }
93  
94 # sub-class parse
95 6 ▶sub parse {
Subroutine parse: called CC=3 SCAR=11.2
Pod documented
96  
97 6 my $self = shift;
98 6 my $html = shift;
99  
100 6 ▶ return unless defined $html;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $html 0 6 6
101 6 ▶ return '' if $html eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $html eq "" 0 6 6
102  
103 6 my $tree = HTML::TreeBuilder->new->parse( $html );
104 6 return $self->_format_tables( $tree ); # we work our magic...
105  
106 }
107  
108 # a private method
109 6 ▶sub _format_tables {
Subroutine _format_tables: called CC=27 SCAR=33.0
110 6 my $self = shift;
111 6 my $tree = shift;
112  
113 6 my $formatted_tables = []; # a nested stack for our formatted table text
114  
115 # the result of an all night programming session...
116 #
117 # essentially we take two passes over each table
118 # and modify the structure of text and html by replacing <td> content with tokens
119 # then replacing the tokens after _parse() has converted it to text
120 #
121 # for each <tr> in each <table>...
122 # we grab all it's <td> inner text (and/or parsed html), rearrange it into a
123 # single string of formatted text, and put a token into it's first <td>
124 # once we have processed the html with _parse(), we replace the tokens with the
125 # corresponding formatted text
126  
127 6 my @tables = $tree->look_down(_tag=>'table');
128 6 my $table_count = 0;
129 6 for my $table (@tables) {
130 6 $formatted_tables->[$table_count] = [];
131 6 my @trs = $table->look_down(_tag=>'tr');
132 6 my @max_col_width; # max column widths by index
133 my @max_col_heights; # max column heights (for multi-line text) by index
134 6 my @col_lines; # a stack for our redesigned rows of column (<td>) text
135 FIRST_PASS: {
136 6 my $row_count = 0; # obviously a counter...
137 6 for my $tr (@trs) { # *** 1st pass over rows
138 9 $max_col_heights[$row_count] = 0;
139 9 $col_lines[$row_count] = [];
140 9 my @cols = $tr->look_down(_tag=>qr/^(td|th)$/); # no support for <th>. sorry.
141 9 ▶ for (my $i = 0; $i < scalar @cols; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @cols) 12 9 21
142 12 my $td = $cols[$i]->clone;
143 12 my $new_tree = HTML::TreeBuilder->new;
144 12 $new_tree->{_content} = [ $td ];
145 # parse the contents of the td into text
146 # this doesn't work well with nested tables...
147 12 my $text = __PACKAGE__->new->_parse($new_tree);
148 # we don't want leading or tailing whitespace
149 12 $text =~ s/\xA0+/ /s; # &nbsp -> space
150 12 $text =~ s/^\s+//s;
151 12 $text =~ s/\s+\z//s;
152 # now we figure out the maximum widths and heights needed for each column
153 12 my $max_line_width = 0;
154 12 my @lines = split "\n", $text; # take the parsed text and break it into virtual rows
155 12 ▶ $max_col_heights[$row_count] = scalar @lines if scalar @lines > $max_col_heights[$row_count];
Branch: 1 branch
BranchTrueFalseTotal
if scalar @lines > $max_col_heights[$row_count] 6 6 12
156 12 for my $line (@lines) {
157 25 my $line_width = length $line;
158 25 ▶ $max_line_width = $line_width if $line_width > $max_line_width;
Branch: 1 branch
BranchTrueFalseTotal
if $line_width > $max_line_width 15 10 25
159 }
160 12 $cols[$i]->{_content} = [ $text ];
161 12 ▶ $max_col_width[$i] ||= 0;
Condition100%2/2
$max_col_width[$i] ||= 0
l!l
48
MC/DC100%1/1
$max_col_width[$i] ||= 0
$max_col_width[$i]
Truth table100%2/2
A
A= $max_col_width[$i]
Aresult
11
00
162 12 ▶ $max_col_width[$i] = $max_line_width if $max_line_width > $max_col_width[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $max_line_width > $max_col_width[$i] 6 6 12
163 # now put the accumulated lines onto our stack
164 12 $col_lines[$row_count]->[$i] = \@lines;
165 }
166 9 $tr->{_content} = \@cols;
167 9 $row_count++;
168 }
169 }
170  
171 SECOND_PASS: {
172 6 my $row_count = 0; # obviously, another counter...
173 6 for my $tr (@trs) { # *** 2nd pass over rows
174 9 my @cols = $tr->look_down(_tag=>qr/^(td|th)$/); # no support for <th>. sorry.
175  
176 9 my $row_text; # the final string representing each row of reformatted text
177  
178 my @col_rows; # a stack for each virtual $new_line spliced together from a group of <td>'s
179  
180 # iterate over each column of the maximum rows of parsed multiline text per <td>
181 # for each virtual row of each virtual column, concat the text with alignment spacings
182 # the final concatinated string value will be placed in column 0
183 9 ▶ for (my $j = 0; $j < $max_col_heights[$row_count]; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $max_col_heights[$row_count]) 14 9 23
184 14 my $new_line;
185 14 ▶ for (my $i = 0; $i < scalar @cols; $i++) { # here are the actual <td> elements we're iterating over...
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @cols) 26 14 40
186 26 my $width = $max_col_width[$i] + $cellpadding; # how wide is this column of text
187 26 my $line = $col_lines[$row_count]->[$i]->[$j]; # get the text to fit into it
188 26 ▶ $line = defined $line ? $line : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $line ? : 25 1 26
189  
190 # strip the whitespace from beginning and end of each line
191 26 $line =~ s/^\s+//gs;
192 26 $line =~ s/\s+\z//gs;
193 26 my $n_space = $width - length $line; # the difference between the column and text widths
194  
195 # we are creating virtual rows of text within a single <td>
196 # so we need to add an indent to all but the first row to
197 # match the indent added by _parse() for presenting table contents
198 26 ▶ $line = ((' ')x$parser_indent). $line if $j != 0 and $i == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $j != 0 and $i == 0 8 18 26
Condition100%3/3
$j != 0 and $i == 0
!ll&&!rl&&r
1088
MC/DC100%2/2
$j != 0 and $i == 0
$j != 0 $i == 0
Truth table100%3/3
A and B
A= $j != 0B= $i == 0
ABresult
0X0
100
111
199  
200 # here we adjust the text alignment by wrapping the text in occulted whitespace
201 26 ▶ my $justify = $cols[$i]->tag eq 'td' ? ( $cols[$i]->attr('align') || 'left' ) : 'center';
Branch: 1 branch
BranchTrueFalseTotal
$cols[$i]->tag eq 'td' ? : 25 1 26
Condition100%2/2
$cols[$i]->attr("align") or "left"
l!l
1015
MC/DC100%1/1
$cols[$i]->attr("align") or "left"
$cols[$i]->attr("align")
Truth table100%2/2
A
A= $cols[$i]->attr("align")
Aresult
11
00
202 26 ▶ if ($justify eq 'center') {
Branch: 2 branches
BranchTrueFalseTotal
if ($justify eq 'center') { } 1 25 26
elsif ($justify eq 'left') { } 15 10 25
203 1 my $pre = int( ($n_space + $cellpadding) / 2 ); # divide remaining space in half
204 1 my $post = $n_space - $pre; # assign any uneven remainder to the end
205 1 $new_line .= ((' ')x$pre). $line .((' ')x$post); # wrap the text in spaces
206 } elsif ($justify eq 'left') {
207 15 $new_line .= ((' ')x$cellpadding). $line .((' ')x$n_space);
208 } else {
209 10 $new_line .= ((' ')x$n_space). $line .((' ')x$cellpadding);
210 }
211 }
212 14 ▶ $new_line .= "\n" if $j != $max_col_heights[$row_count] - 1; # add a newline to all but the last text row
Branch: 1 branch
BranchTrueFalseTotal
if $j != $max_col_heights[$row_count] - 1 8 6 14
213 14 $col_rows[$j] = $new_line; # put the line into the stack for this row
214 }
215 9 $row_text .= $_ for @col_rows;
216 9 ▶ for (my $i = 1; $i < scalar @cols; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @cols) 4 9 13
217 4 $cols[$i]->delete; # get rid of unneeded <td>'s
218 }
219 # put the fully formatted text into our accumulator
220 9 $formatted_tables->[$table_count]->[$row_count] = $row_text;
221 9 ▶ if (scalar @cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @cols) 8 1 9
222 8 $cols[0]->content->[0] = "__TOKEN__${table_count}__${row_count}__"; # place a token into the row at col 0
223 }
224 9 $row_count++;
225 }
226 }
227 6 $table_count++;
228 }
229  
230 # now replace our tokens
231 6 my $text = $self->_parse( $tree );
232 6 ▶ for (my $i = 0; $i < scalar @$formatted_tables; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @$formatted_tables) 6 6 12
233 6 ▶ for (my $j = 0; $j < scalar @{ $$formatted_tables[$i] }; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < scalar @{$formatted_tables->[$i];}) 9 6 15
234 9 my $token = "__TOKEN__${i}__${j}__";
235 9 ▶ $token .= "\n?" if $no_rowspacing;
Branch: 1 branch
BranchTrueFalseTotal
if $no_rowspacing 0 9 9
236 9 my $new_text = $$formatted_tables[$i][$j];
237 9 ▶ if (defined $new_text) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $new_text) { } 6 3 9
238 6 $text =~ s/$token/$new_text/;
239 }
240 else {
241 3 $text =~ s/$token//;
242 }
243 }
244 }
245  
246 6 return $text;
247 }
248  
249 7 1;
250 __END__
↑ Summary