File Coverage

blib/lib/Perl/Lint/Policy/ControlStructures/ProhibitCascadingIfElse.pm
Criterion Covered Total %
statement 44 44 100.0
branch 11 12 91.6
condition 7 8 87.5
subroutine 7 7 100.0
pod 0 1 0.0
total 69 72 95.8


line stmt bran cond sub pod time code
1             package Perl::Lint::Policy::ControlStructures::ProhibitCascadingIfElse;
2 133     133   95125 use strict;
  133         269  
  133         4710  
3 133     133   4623 use warnings;
  133         247  
  133         3841  
4 133     133   9044 use Perl::Lint::Constants::Type;
  133         243  
  133         82290  
5 133     133   1698 use Perl::Lint::Constants::Kind;
  133         230  
  133         9066  
6 133     133   696 use parent "Perl::Lint::Policy";
  133         225  
  133         743  
7              
8             use constant {
9 133         38857 DESC => 'Cascading if-elsif chain',
10             EXPL => [117, 118],
11 133     133   9399 };
  133         244  
12              
13             sub evaluate {
14 4     4 0 10 my ($class, $file, $tokens, $src, $args) = @_;
15              
16 4   100     20 my $max_elsif = $args->{prohibit_cascading_if_else}->{max_elsif} || 2;
17              
18 4         5 my @violations;
19 4         5 my $is_chained = 0;
20 4         4 my $cascading_num = 0;
21 4         7 my $top_of_conditional_branch_line_num = 0;
22 4         18 for (my $i = 0; my $token = $tokens->[$i]; $i++) {
23 159         136 my $token_type = $token->{type};
24              
25 159 100 66     395 if ($token_type == IF_STATEMENT || $token_type == UNLESS_STATEMENT) {
26 10         9 $top_of_conditional_branch_line_num = $token->{line};
27 10         24 next;
28             }
29              
30 149 100       166 if ($token_type == ELSIF_STATEMENT) {
31 22         16 $cascading_num++;
32              
33 22 100 100     59 if ($is_chained && $cascading_num > $max_elsif) {
34 7         29 push @violations, {
35             filename => $file,
36             line => $top_of_conditional_branch_line_num,
37             description => DESC,
38             explanation => EXPL,
39             policy => __PACKAGE__,
40             };
41             }
42              
43 22         16 my $left_brace_num = 0;
44 22         37 for ($i++; my $token = $tokens->[$i]; $i++) {
45 154         103 my $token_type = $token->{type};
46 154 100       334 if ($token_type == LEFT_BRACE) {
    100          
47 22         46 $left_brace_num++;
48             }
49             elsif ($token_type == RIGHT_BRACE) {
50 22 50       42 last if --$left_brace_num <= 0;
51             }
52             }
53 22         16 $is_chained = 1;
54 22         35 next;
55             }
56              
57 127         94 $cascading_num = 0;
58 127         194 $is_chained = 0;
59             }
60              
61 4         20 return \@violations;
62             }
63              
64             1;
65              
66