MechanicalTurk/PagedResultsIterator.pm untested

filter: Statementstmt 0.0% 0 / 62 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 93 CC 9 SCAR 28.1
CC
9
Cov
0%
next
30.0
loadPage
20.0
init
6.0
CRAP 16.7
1 package Net::Amazon::MechanicalTurk::PagedResultsIterator;
2 use warnings;
3 use strict;
4 use Carp;
5 use Net::Amazon::MechanicalTurk::BaseObject;
6  
7 our $VERSION = '1.00';
8  
9 our @ISA = qw{ Net::Amazon::MechanicalTurk::BaseObject };
10 our %META_RESULT_FIELDS = (
11 NumResults => 1,
12 PageNumber => 1,
13 TotalNumResults => 1,
14 Request => 1
15 );
16  
17 Net::Amazon::MechanicalTurk::PagedResultsIterator->attributes(qw{
18 mturk
19 operation
20 params
21 pageSize
22 currentPage
23 currentResults
24 currentResultsPosition
25 });
26  
27 sub init {
28 my $self = shift;
29 $self->setAttributes(@_);
30 if (defined $self->params and $self->params->{PageSize}) {
31 $self->pageSize($self->params->{PageSize});
32 }
33 $self->setAttributesIfNotDefined(
34 params => {},
35 pageSize => 100
36 );
37 $self->assertRequiredAttributes(qw{
38 mturk
39 operation
40 });
41 $self->currentResults([]);
42 $self->currentPage(0);
43 $self->currentResultsPosition(0);
44 }
45  
46 sub next {
47 my ($self) = @_;
48
49 my $array = $self->currentResults;
50 return undef unless defined($array);
51  
52 # TODO: make sure this is right
53 # perhaps the code should continue until it gets to a page with 0
54 # results. The assumption here is that a page with less items
55 # then the requested page size is the last page.
56 if ($self->currentResultsPosition > $#{$array}) {
57 #if (($#{$array}+1) < $self->pageSize) {
58 # $self->currentResults(undef);
59 # return undef;
60 #}
61 #else {
62 $self->currentPage($self->currentPage + 1);
63 $self->loadPage;
64 #}
65 }
66
67 $array = $self->currentResults;
68 return undef unless defined($array);
69
70 if ($self->currentResultsPosition > $#{$array}) {
71 $self->currentResults(undef);
72 return undef;
73 }
74
75 my $item = $array->[$self->currentResultsPosition];
76 $self->currentResultsPosition($self->currentResultsPosition + 1);
77
78 return $item;
79 }
80  
81 sub loadPage {
82 my ($self) = @_;
83 my %params = %{$self->params};
84
85 $params{PageNumber} = $self->currentPage;
86 $params{PageSize} = $self->pageSize;
87
88 my $result = $self->mturk->call($self->operation, \%params);
89
90 if (!UNIVERSAL::isa($result, "HASH")) {
91 Carp::croak("Unexpected result type for " . $self->operation . ".");
92 }
93
94 $self->currentResults(undef);
95 $self->currentResultsPosition(0);
96
97 while (my ($k,$v) = each %$result) {
98 if (! exists $META_RESULT_FIELDS{$k}) {
99 if (UNIVERSAL::isa($v, "ARRAY")) {
100 $self->currentResults($v);
101 }
102 else {
103 $self->currentResults([$v]);
104 }
105 last;
106 }
107 }
108 }
109  
110 return 1;