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   69137 use strict;
  133         205  
  133         3332  
3 133     133   3673 use warnings;
  133         177  
  133         3036  
4 133     133   6448 use Perl::Lint::Constants::Type;
  133         215  
  133         61270  
5 133     133   953 use Perl::Lint::Constants::Kind;
  133         229  
  133         6566  
6 133     133   475 use parent "Perl::Lint::Policy";
  133         217  
  133         567  
7              
8             use constant {
9 133         29852 DESC => 'Cascading if-elsif chain',
10             EXPL => [117, 118],
11 133     133   6594 };
  133         181  
12              
13             sub evaluate {
14 4     4 0 8 my ($class, $file, $tokens, $src, $args) = @_;
15              
16 4   100     21 my $max_elsif = $args->{prohibit_cascading_if_else}->{max_elsif} || 2;
17              
18 4         6 my @violations;
19 4         7 my $is_chained = 0;
20 4         4 my $cascading_num = 0;
21 4         5 my $top_of_conditional_branch_line_num = 0;
22 4         17 for (my $i = 0; my $token = $tokens->[$i]; $i++) {
23 159         107 my $token_type = $token->{type};
24              
25 159 100 66     413 if ($token_type == IF_STATEMENT || $token_type == UNLESS_STATEMENT) {
26 10         7 $top_of_conditional_branch_line_num = $token->{line};
27 10         20 next;
28             }
29              
30 149 100       173 if ($token_type == ELSIF_STATEMENT) {
31 22         12 $cascading_num++;
32              
33 22 100 100     52 if ($is_chained && $cascading_num > $max_elsif) {
34 7         26 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         15 my $left_brace_num = 0;
44 22         36 for ($i++; my $token = $tokens->[$i]; $i++) {
45 154         101 my $token_type = $token->{type};
46 154 100       297 if ($token_type == LEFT_BRACE) {
    100          
47 22         28 $left_brace_num++;
48             }
49             elsif ($token_type == RIGHT_BRACE) {
50 22 50       40 last if --$left_brace_num <= 0;
51             }
52             }
53 22         14 $is_chained = 1;
54 22         30 next;
55             }
56              
57 127         79 $cascading_num = 0;
58 127         174 $is_chained = 0;
59             }
60              
61 4         18 return \@violations;
62             }
63              
64             1;
65              
66