Courriel/Headers.pm

filter: Statementstmt 72.6% 154 / 212 Branchbran 51.8% 28 / 54 Conditioncond 30.0% 6 / 20 MC/DCmcdc 18.1% 2 / 11 Subroutinesub 81.2% 26 / 32 Podpod 100% 9 / 9 totaltotal 66.5% 225 / 338 CC 40 SCAR 26.1
CC
40
Cov
66%
_mime_decode
60.9
parse
13.9
__ANON__
13.0
CRAP 13.5
« Courriel/Header.pm ↑ Summary Courriel/Helpers.pm »
1 package Courriel::Headers;
2  
3 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 8 our $VERSION = '0.49';
8  
9 8 ▶use Courriel::Header;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use Courriel::Header::ContentType;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use Courriel::Header::Disposition;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 use Courriel::Types
13 8 ▶ qw( ArrayRef Defined HashRef HeaderArray NonEmptyStr Str Streamable StringRef );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 8 ▶use Encode qw( decode );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 8 ▶use MIME::Base64 qw( decode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 8 ▶use MIME::QuotedPrint qw( decode_qp );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 8 ▶use Params::ValidationCompiler qw( validation_for );
Subroutine BEGIN: called CC=1 SCAR=0.0
18 8 ▶use Scalar::Util qw( blessed reftype );
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 8 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 8 ▶use MooseX::StrictConstructor;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 8 with 'Courriel::Role::Streams' => { -exclude => ['stream_to'] };
24  
25 has _headers => (
26 traits => ['Array'],
27 is => 'ro',
28 isa => HeaderArray,
29 13 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
30 8 init_arg => 'headers',
31 handles => {
32 headers => 'elements',
33 },
34 );
35  
36 # The _key_indices field, along with all the complicated code to
37 # get/add/remove headers below, is necessary because RFC 5322 says:
38 #
39 # However, for the purposes of this specification, header fields SHOULD NOT
40 # be reordered when a message is transported or transformed. More
41 # importantly, the trace header fields and resent header fields MUST NOT be
42 # reordered, and SHOULD be kept in blocks prepended to the message.
43 #
44 # So we store headers as an array ref. When we add additional values for a
45 # header, we will put them after the last header of the same name in the array
46 # ref. If no such header exists yet, then we just put them at the end of the
47 # arrayref.
48  
49 8 has _key_indices => (
50 traits => ['Hash'],
51 isa => HashRef [ ArrayRef [NonEmptyStr] ],
52 init_arg => undef,
53 lazy => 1,
54 builder => '_build_key_indices',
55 clearer => '_clear_key_indices',
56 handles => {
57 __key_indices_for => 'get',
58 },
59 );
60  
61 159 ▶override BUILDARGS => sub {
Subroutine __ANON__: called CC=9 SCAR=25.6
62 159 my $class = shift;
63  
64 159 my $p = super();
65  
66 159 ▶ return $p unless $p->{headers};
Branch: 1 branch
BranchTrueFalseTotal
unless $p->{"headers"} 13 146 159
67  
68 # Could this be done as a coercion for the HeaderArray type? Maybe, but
69 # it'd probably need structured types, which seems like as much of a
70 # hassle as just doing this.
71 146 ▶ if ( reftype( $p->{headers} ) eq 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::reftype($p->{'headers'}) eq 'ARRAY') { } 146 0 146
elsif (builtin::reftype($p->{'headers'}) eq 'HASH') { } 0 0 0
72 146 my $headers = $p->{headers};
73  
74 ## no critic (ControlStructures::ProhibitCStyleForLoops)
75 146 ▶ for ( my $i = 1; $i < @{$headers}; $i += 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @{$headers;}) 2091 146 2237
76 2091 ▶ next if blessed( $headers->[ $i - 1 ] );
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($$headers[$i - 1]) 0 2091 2091
77  
78 2091 my $name = $headers->[ $i - 1 ];
79  
80 2091 ▶ next unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 2091 2091
81  
82 2091 $headers->[$i] = $class->_inflate_header( $name, $headers->[$i] );
83 }
84 }
85 elsif ( reftype( $p->{headers} ) eq 'HASH' ) {
86 0 for my $name ( keys %{ $p->{headers} } ) {
87 0 ▶ next if blessed( $p->{headers}{$name} );
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($p->{"headers"}{$name}) 0 0 0
88  
89 $p->{headers}{$name}
90 0 = $class->_inflate_header( $name, $p->{headers}{$name} );
91 }
92 }
93  
94 146 return $p;
95 8 };
96  
97 2210 ▶sub _inflate_header {
Subroutine _inflate_header: called CC=3 SCAR=11.0
98 2210 my $class = shift;
99 2210 my $name = shift;
100 2210 my $value = shift;
101  
102 2210 ▶ my ( $header_class, $method )
Branch: 2 branches
BranchTrueFalseTotal
lc $name eq 'content-type' ? : 132 2078 2210
lc $name eq 'content-disposition' ? : 53 2025 2078
103 = lc $name eq 'content-type'
104 ? ( 'Courriel::Header::ContentType', 'new_from_value' )
105 : lc $name eq 'content-disposition'
106 ? ( 'Courriel::Header::Disposition', 'new_from_value' )
107 : ( 'Courriel::Header', 'new' );
108  
109 2210 return $header_class->$method(
110 name => $name,
111 value => $value,
112 );
113 }
114  
115 356 ▶sub _build_key_indices {
Subroutine _build_key_indices: called CC=2 SCAR=6.9
116 356 my $self = shift;
117  
118 356 my $headers = $self->_headers;
119  
120 356 my %indices;
121 ## no critic (ControlStructures::ProhibitCStyleForLoops)
122 356 ▶ for ( my $i = 0; $i < @{$headers}; $i += 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @{$headers;}) 4197 356 4553
123 4197 push @{ $indices{ lc $headers->[$i] } }, $i + 1;
124 }
125  
126 356 return \%indices;
127 }
128  
129 {
130 8 my $validator = validation_for(
131 params => [ { type => NonEmptyStr } ],
132 );
133  
134 309 ▶ sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
135 309 my $self = shift;
136 309 my ($name) = $validator->(@_);
137  
138 309 return @{ $self->_headers }[ $self->_key_indices_for($name) ];
139 }
140 }
141  
142 {
143 8 my $validator = validation_for(
144 params => [ { type => NonEmptyStr } ],
145 );
146  
147 0 ▶ sub get_values {
Subroutine get_values: not called CC=1 SCAR=6.9
Pod documented
148 0 my $self = shift;
149 0 my ($name) = $validator->(@_);
150  
151 return
152 0 map { $_->value }
153 0 @{ $self->_headers }[ $self->_key_indices_for($name) ];
154 }
155 }
156  
157 8 ▶sub _key_indices_for {
Subroutine _key_indices_for: called CC=2 SCAR=6.9
158 655 my $self = shift;
159 655 my $name = shift;
160  
161 655 ▶ return @{ $self->__key_indices_for( lc $name ) || [] };
Condition100%2/2
$self->__key_indices_for(lc $name) || []
l!l
358297
MC/DC100%1/1
$self->__key_indices_for(lc $name) || []
$self->__key_indices_for(lc $name)
Truth table100%2/2
A
A= $self->__key_indices_for(lc $name)
Aresult
11
00
162 }
163  
164 {
165 8 my $validator = validation_for(
166 params => [
167 { type => NonEmptyStr },
168 { type => Defined },
169 ],
170 );
171  
172 173 ▶ sub add {
Subroutine add: called CC=4 SCAR=14.2
Pod documented
173 173 my $self = shift;
174 173 my ( $name, $value ) = $validator->(@_);
175  
176 173 my $headers = $self->_headers;
177  
178 173 my $last_index = ( $self->_key_indices_for($name) )[-1];
179  
180 173 ▶ my $header
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($value) && $value->isa('Courriel::Header') ? : 54 119 173
Condition66%2/3
builtin::blessed($value) and $value->isa("Courriel::Header")
!ll&&!rl&&r
119054
MC/DC50%1/2
builtin::blessed($value) and $value->isa("Courriel::Header")
builtin::blessed($value) $value->isa("Courriel::Header")
Truth table66%2/3
A and B
A= builtin::blessed($value)B= $value->isa("Courriel::Header")
ABresult
0X0
100
111
181 = blessed($value)
182 && $value->isa('Courriel::Header')
183 ? $value
184 : $self->_inflate_header( $name, $value );
185  
186 173 ▶ if ($last_index) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last_index) { } 0 173 173
187 0 splice @{$headers}, $last_index + 1, 0, ( $name => $header );
188 }
189 else {
190 173 push @{$headers}, ( $name => $header );
191 }
192  
193 173 $self->_clear_key_indices;
194  
195 173 return;
196 }
197 }
198  
199 {
200 8 my $validator = validation_for(
201 params => [
202 { type => NonEmptyStr },
203 { type => Defined },
204 ],
205 );
206  
207 # Used to add things like Resent or Received headers
208  
209 ## no critic (Subroutines::ProhibitBuiltinHomonyms)
210 0 ▶ sub unshift {
Subroutine unshift: not called CC=3 SCAR=24.8
Pod documented
211 0 my $self = shift;
212 0 my ( $name, $value ) = $validator->(@_);
213  
214 0 my $headers = $self->_headers;
215  
216 0 ▶ my $header
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($value) && $value->isa('Courriel::Header') ? : 0 0 0
Condition0%0/3
builtin::blessed($value) and $value->isa("Courriel::Header")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($value) and $value->isa("Courriel::Header")
builtin::blessed($value) $value->isa("Courriel::Header")
Truth table0%0/3
A and B
A= builtin::blessed($value)B= $value->isa("Courriel::Header")
ABresult
0X0
100
111
217 = blessed($value)
218 && $value->isa('Courriel::Header')
219 ? $value
220 : $self->_inflate_header( $name, $value );
221  
222 0 unshift @{$headers}, ( $name => $header );
223  
224 0 return;
225 }
226 }
227  
228 {
229 8 my $validator = validation_for(
230 params => [
231 { type => NonEmptyStr },
232 ],
233 );
234  
235 173 ▶ sub remove {
Subroutine remove: called CC=2 SCAR=6.9
Pod documented
236 173 my $self = shift;
237 173 my ($name) = $validator->(@_);
238  
239 173 my $headers = $self->_headers;
240  
241 173 for my $idx ( reverse $self->_key_indices_for($name) ) {
242 107 splice @{$headers}, $idx - 1, 2;
243 }
244  
245 173 $self->_clear_key_indices;
246  
247 173 return;
248 }
249 }
250  
251 {
252 8 my $validator = validation_for(
253 params => [
254 { type => NonEmptyStr },
255 { type => Defined },
256 ],
257 );
258  
259 173 ▶ sub replace {
Subroutine replace: called CC=1 SCAR=0.0
Pod documented
260 173 my $self = shift;
261 173 my ( $name, $value ) = $validator->(@_);
262  
263 173 $self->remove($name);
264 173 $self->add( $name => $value );
265  
266 173 return;
267 }
268 }
269  
270 {
271 8 my $horiz_text = qr/[^\x0a\x0d]/;
272 8 my $horiz_ws = qr/[ \t]/;
273 8 my $line_re = qr/
274 (?:
275 ([^\s:][^:\n\r]*) # a header name
276 : # followed by a colon
277 $horiz_ws*
278 ($horiz_text*) # header value - can be empty
279 )
280 |
281 $horiz_ws+(\S$horiz_text*)? # continuation line
282 /x;
283  
284 8 my $validator = validation_for(
285 params => [ text => { type => StringRef } ],
286 named_to_list => 1,
287 );
288  
289 142 ▶ sub parse {
Subroutine parse: called CC=11 SCAR=26.3
Pod documented
290 142 my $class = shift;
291 142 my ($text) = $validator->(@_);
292  
293 142 my @headers;
294  
295 142 $class->_maybe_fix_broken_headers($text);
296  
297 142 ▶ while ( ${$text} =~ /\G${line_re}$Courriel::Helpers::LINE_SEP_RE/gc )
Branch: 1 branch
BranchTrueFalseTotal
if (${$text;} =~ /\G$line_re$Courriel::Helpers::LINE_SEP_RE/cg) 2702 142 2844
298 {
299 2702 ▶ if ( defined $1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) { } 2091 611 2702
300 2091 push @headers, $1, $2;
301 }
302 else {
303 611 ▶ die
Branch: 1 branch
BranchTrueFalseTotal
unless @headers 0 611 611
304 'Header text contains a continuation line before a header name has been seen.'
305 unless @headers;
306  
307 611 ▶ $headers[-1] //= q{};
Condition50%1/2
$headers[-1] //= ""
l!l
6110
MC/DC0%0/1
$headers[-1] //= ""
$headers[-1]
Truth table50%1/2
A
A= $headers[-1]
Aresult
11
00
308  
309 # RFC 5322 says:
310 #
311 # Runs of FWS, comment, or CFWS that occur between lexical tokens in a
312 # structured header field are semantically interpreted as a single
313 # space character.
314 611 ▶ $headers[-1] .= q{ } if length $headers[-1];
Branch: 1 branch
BranchTrueFalseTotal
if length $headers[-1] 611 0 611
315 611 ▶ $headers[-1] .= $3 if defined $3;
Branch: 1 branch
BranchTrueFalseTotal
if defined $3 609 2 611
316 }
317 }
318  
319 142 ▶ my $pos = pos ${$text} // 0;
Condition50%1/2
pos ${$text;} // 0
l!l
1420
MC/DC0%0/1
pos ${$text;} // 0
pos ${$text;}
Truth table50%1/2
A
A= pos ${$text;}
Aresult
11
00
320 142 ▶ if ( $pos != length ${$text} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos != length ${$text;}) 0 142 142
321 my @lines = split $Courriel::Helpers::LINE_SEP_RE,
322 0 substr( ${$text}, 0, $pos );
323 0 my $count = ( scalar @lines ) + 1;
324  
325 0 my $line = ( split $Courriel::Helpers::LINE_SEP_RE, ${$text} )
326 [ $count - 1 ];
327  
328 0 ▶ die defined $line
Branch: 1 branch
BranchTrueFalseTotal
defined $line ? : 0 0 0
329 ? "Found an unparseable chunk in the header text starting at line $count:\n $line"
330 : 'Could not parse headers at all';
331 }
332  
333 ## no critic (ControlStructures::ProhibitCStyleForLoops)
334 142 ▶ for ( my $i = 1; $i < @headers; $i += 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @headers) 2091 142 2233
335 2091 $headers[$i] = $class->_mime_decode( $headers[$i] );
336 }
337  
338 142 return $class->new( headers => \@headers );
339 }
340 }
341  
342 8 ▶sub _maybe_fix_broken_headers {
Subroutine _maybe_fix_broken_headers: called CC=1 SCAR=0.0
343 142 my $class = shift;
344 142 my $text = shift;
345  
346 # Some broken email messages have a newline in the headers that isn't
347 # acting as a continuation, it's just an arbitrary line break. See
348 # t/data/stress-test/mbox_mime_applemail_1xb.txt
349 142 ${$text}
350 =~ s/$Courriel::Helpers::LINE_SEP_RE([^\s:][^:]+$Courriel::Helpers::LINE_SEP_RE)/$1/g;
351  
352 142 return;
353 }
354  
355 {
356 my $validator = validation_for(
357 params => [
358 output => { type => Streamable },
359 skip => {
360 0 ▶ type => ArrayRef [NonEmptyStr], default => sub { [] }
Subroutine __ANON__: not called CC=1 SCAR=6.9
361 },
362 8 charset => { type => NonEmptyStr, default => 'utf8' },
363 ],
364 named_to_list => 1,
365 );
366  
367 0 ▶ sub stream_to {
Subroutine stream_to: not called CC=3 SCAR=24.8
Pod documented
368 0 my $self = shift;
369 0 my ( $output, $skip, $charset ) = $validator->(@_);
370  
371 0 my %skip = map { lc $_ => 1 } @{$skip};
372  
373 0 for my $header ( grep { blessed($_) } @{ $self->_headers } ) {
374 0 ▶ next if $skip{ lc $header->name };
Branch: 1 branch
BranchTrueFalseTotal
if $skip{lc $header->name} 0 0 0
375  
376 0 $header->stream_to( charset => $charset, output => $output );
377 }
378  
379 0 return;
380 }
381 }
382  
383 8 ▶sub as_string {
Subroutine as_string: not called CC=1 SCAR=4.1
Pod documented
384 0 my $self = shift;
385  
386 0 my $string = q{};
387  
388 0 $self->stream_to( output => $self->_string_output( \$string ), @_ );
389  
390 0 return $string;
391 }
392  
393 {
394 8 my $mime_word = qr/
395 (?:
396 =\? # begin encoded word
397 (?<charset>[-0-9A-Za-z_]+) # charset (encoding)
398 (?:\*[A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*)? # language (RFC 2231)
399 \?
400 (?<encoding>[QqBb]) # encoding type
401 \?
402 (?<content>.*?) # Base64-encoded contents
403 \?= # end encoded word
404 |
405 (?<unencoded>\S+?)
406 )
407 (?<ws>[ \t]+)?
408 /x;
409  
410 2091 ▶ sub _mime_decode {
Subroutine _mime_decode: called CC=9 SCAR=41.1
411 2091 my $self = shift;
412 2091 my $text = shift;
413  
414 2091 ▶ return $text unless $text =~ /=\?[\w-]+\?[BQ]\?/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $text =~ /=\?[\w-]+\?[BQ]\?/i 2091 0 2091
415  
416 0 my @chunks;
417  
418 # If a MIME encoded word is followed by _another_ such word, we ignore any
419 # intervening whitespace, otherwise we preserve the whitespace between a
420 # MIME encoded word and an unencoded word. See RFC 2047 for details on
421 # this.
422 0 ▶ while ( $text =~ /\G$mime_word/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /\G$mime_word/g) 0 0 0
423 0 ▶ if ( defined $+{charset} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $+{'charset'}) { } 0 0 0
424 push @chunks, {
425 content => $self->_decode_one_word(
426 @+{ 'charset', 'encoding', 'content' }
427 ),
428 ws => $+{ws},
429 0 is_mime => 1,
430 };
431 }
432 else {
433 push @chunks, {
434 content => $+{unencoded},
435 ws => $+{ws},
436 0 is_mime => 0,
437 };
438 }
439 }
440  
441 0 my $result = q{};
442  
443 0 for my $i ( 0 .. $#chunks ) {
444 0 $result .= $chunks[$i]{content};
445 $result .= ( $chunks[$i]{ws} // q{} )
446 unless $chunks[$i]{is_mime}
447 && $chunks[ $i + 1 ]
448 0 ▶ && $chunks[ $i + 1 ]{is_mime};
Branch: 1 branch
BranchTrueFalseTotal
unless $chunks[$i]{"is_mime"} and $chunks[$i + 1] and $chunks[$i + 1]{"is_mime"} 0 0 0
Condition0%0/8
$chunks[$i]{"is_mime"} and $chunks[$i + 1] and $chunks[$i + 1]{"is_mime"}
!ll&&!rl&&r
000
$chunks[$i]{"is_mime"} and $chunks[$i + 1]
!ll&&!rl&&r
000
$chunks[$i]{"ws"} // ""
l!l
00
MC/DC0%0/3
$chunks[$i]{"is_mime"} and $chunks[$i + 1] and $chunks[$i + 1]{"is_mime"}
$chunks[$i]{"is_mime"} $chunks[$i + 1] $chunks[$i + 1]{"is_mime"}
MC/DC0%0/1
$chunks[$i]{"ws"} // ""
$chunks[$i]{"ws"}
Truth table0%0/4
A and B and C
A= $chunks[$i]{"is_mime"}B= $chunks[$i + 1]C= $chunks[$i + 1]{"is_mime"}
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/2
A
A= $chunks[$i]{"ws"}
Aresult
11
00
449 }
450  
451 0 return $result;
452 }
453 }
454  
455 8 ▶sub _decode_one_word {
Subroutine _decode_one_word: not called CC=2 SCAR=16.1
456 0 my $self = shift;
457 0 my $charset = shift;
458 0 my $encoding = shift;
459 0 my $content = shift;
460  
461 0 ▶ if ( uc $encoding eq 'B' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (uc $encoding eq 'B') { } 0 0 0
462 0 return decode( $charset, decode_base64($content) );
463 }
464 else {
465 0 $content =~ tr/_/ /;
466 0 return decode( $charset, decode_qp($content) );
467 }
468 }
469  
470 8 __PACKAGE__->meta->make_immutable;
471  
472 8 1;
473  
474 # ABSTRACT: The headers for an email part
475  
476 __END__
« Courriel/Header.pm ↑ Summary Courriel/Helpers.pm »