Categorizer/Collection/SingleFile.pm untested

filter: Statementstmt 0.0% 0 / 65 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 98 CC 9 SCAR 22.4
CC
9
Cov
0%
next
20.0
count_documents
12.0
new
6.0
CRAP 9.4
1 package AI::Categorizer::Collection::SingleFile;
2 use strict;
3  
4 use AI::Categorizer::Collection;
5 use base qw(AI::Categorizer::Collection);
6  
7 use Params::Validate qw(:types);
8  
9 __PACKAGE__->valid_params
10 (
11 path => { type => SCALAR|ARRAYREF },
12 categories => { type => HASHREF|UNDEF, default => undef },
13 delimiter => { type => SCALAR },
14 );
15  
16 __PACKAGE__->contained_objects
17 (
18 document => { class => 'AI::Categorizer::Document::Text',
19 delayed => 1 },
20 );
21  
22 sub new {
23 my $class = shift;
24 my $self = $class->SUPER::new(@_);
25
26 $self->{fh} = do {local *FH; *FH}; # double *FH avoids a warning
27  
28 # Documents are contained in a file, or list of files
29 $self->{path} = [$self->{path}] unless ref $self->{path};
30 $self->{used} = [];
31  
32 $self->_next_path;
33 return $self;
34 }
35  
36 sub _next_path {
37 my $self = shift;
38 close $self->{fh} if $self->{cur_file};
39  
40 push @{$self->{used}}, shift @{$self->{path}};
41 $self->{cur_file} = $self->{used}[-1];
42 open $self->{fh}, "< $self->{cur_file}" or die "$self->{cur_file}: $!";
43 }
44  
45 sub next {
46 my $self = shift;
47  
48 my $fh = $self->{fh}; # Must put in a simple scalar
49 my $content = do {local $/ = $self->{delimiter}; <$fh>};
50  
51 if (!defined $content) { # File has been exhausted
52 unless (@{$self->{path}}) { # All files have been exhausted
53 $self->{fh} = undef;
54 return undef;
55 }
56 $self->_next_path;
57 return $self->next;
58 } elsif ($content =~ /^\s*$self->{delimiter}$/) { # Skip empty docs
59 return $self->next;
60 }
61 #warn "doc is $content";
62 #warn "creating document=>@{[ %{$self->{container}{delayed}{document}} ]}";
63  
64 return $self->create_delayed_object('document', content => $content);
65 }
66  
67 sub count_documents {
68 my ($self) = @_;
69 return $self->{document_count} if defined $self->{document_count};
70
71 $self->rewind;
72  
73 my $count = 0;
74 local $/ = $self->{delimiter};
75 my $fh = $self->{fh};
76 while (1) {
77 $count++ while <$fh>;
78 last unless @{$self->{path}};
79 $self->_next_path;
80 }
81
82 $self->rewind;
83  
84 return $self->{document_count} = $count;
85 }
86  
87 sub rewind {
88 my ($self) = @_;
89  
90 close $self->{fh} if $self->{cur_file};
91 unshift @{$self->{path}}, @{$self->{used}};
92 $self->{used} = [];
93 $self->_next_path;
94 }
95  
96 1;