File Coverage

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


line stmt bran cond sub pod time code
1             package App::PRT::Command::AddMethod;
2 2     2   2788 use strict;
  2         4  
  2         63  
3 2     2   10 use warnings;
  2         3  
  2         50  
4 2     2   548 use PPI;
  2         107538  
  2         687  
5              
6             # Internal command to add method to file
7              
8             sub new {
9 8     8 0 27449 my ($class) = @_;
10 8         49 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 1642 my ($self, $code) = @_;
20              
21 7         37 $self->{code} = $code;
22             }
23              
24             sub code {
25 7     7 0 21 my ($self) = @_;
26              
27 7         32 $self->{code};
28             }
29              
30             # refactor a file
31             # argumensts:
32             # $file: filename for refactoring
33             sub execute {
34 6     6 0 1895 my ($self, $file) = @_;
35              
36 6         42 my $document = PPI::Document->new($file);
37              
38 6         48633 my $statements = $document->find('PPI::Statement');
39 6 50       10948 die 'statement not found' unless $statements;
40 6         19 my $after = $statements->[-1];
41              
42 6         22 my $code_document = PPI::Document->new(\$self->code);
43 6         23084 my $code_statement = $code_document->find_first('PPI::Statement::Sub');
44              
45 6         1589 my @comments;
46 6         42 my $cursor = $code_statement->first_token->previous_token;
47 6   100     646 while (defined $cursor && (ref $cursor eq 'PPI::Token::Comment' || ref $cursor eq 'PPI::Token::Whitespace')) {
      66        
48 5         95 unshift @comments, $cursor;
49 5         21 $cursor = $cursor->previous_token;
50             }
51              
52 6         108 while (ref $comments[0] eq 'PPI::Token::Whitespace') {
53 1         3 shift @comments;
54             }
55              
56 6         30 $after->insert_before($_) for @comments;
57              
58 6         250 $after->insert_before($code_statement);
59              
60 6         360 my $whitespaces_document = PPI::Document->new(\"\n\n");
61 6         2453 $after->insert_before($_) for @{ $whitespaces_document->find('PPI::Token') };
  6         41  
62              
63 6         1956 $document->save($file);
64             }
65              
66             1;