File Coverage

lib/App/PRT/Command/AddMethod.pm
Criterion Covered Total %
statement 35 35 100.0
branch 1 2 50.0
condition 4 6 66.6
subroutine 7 7 100.0
pod 0 4 0.0
total 47 54 87.0


line stmt bran cond sub pod time code
1             package App::PRT::Command::AddMethod;
2 2     2   1194 use strict;
  2         3  
  2         43  
3 2     2   4 use warnings;
  2         2  
  2         35  
4 2     2   453 use PPI;
  2         83431  
  2         445  
5              
6             # Internal command to add method to file
7              
8             sub new {
9 8     8 0 14807 my ($class) = @_;
10 8         28 bless {
11             code => undef,
12             }, $class;
13             }
14              
15             # register a method
16             # arguments:
17             # $code: Source code string of method to add
18             sub register {
19 7     7 0 904 my ($self, $code) = @_;
20              
21 7         24 $self->{code} = $code;
22             }
23              
24             sub code {
25 7     7 0 14 my ($self) = @_;
26              
27 7         28 $self->{code};
28             }
29              
30             # refactor a file
31             # argumensts:
32             # $file: filename for refactoring
33             sub execute {
34 6     6 0 784 my ($self, $file) = @_;
35              
36 6         26 my $document = PPI::Document->new($file);
37              
38 6         23767 my $statements = $document->find('PPI::Statement');
39 6 50       8062 die 'statement not found' unless $statements;
40 6         12 my $after = $statements->[-1];
41              
42 6         18 my $code_document = PPI::Document->new(\$self->code);
43 6         11598 my $code_statement = $code_document->find_first('PPI::Statement::Sub');
44              
45 6         1010 my @comments;
46 6         29 my $cursor = $code_statement->first_token->previous_token;
47 6   100     438 while (defined $cursor && (ref $cursor eq 'PPI::Token::Comment' || ref $cursor eq 'PPI::Token::Whitespace')) {
      33        
48 5         51 unshift @comments, $cursor;
49 5         18 $cursor = $cursor->previous_token;
50             }
51              
52 6         66 while (ref $comments[0] eq 'PPI::Token::Whitespace') {
53 1         3 shift @comments;
54             }
55              
56 6         22 $after->insert_before($_) for @comments;
57              
58 6         132 $after->insert_before($code_statement);
59              
60 6         220 my $whitespaces_document = PPI::Document->new(\"\n\n");
61 6         1276 $after->insert_before($_) for @{ $whitespaces_document->find('PPI::Token') };
  6         25  
62              
63 6         1370 $document->save($file);
64             }
65              
66             1;