File Coverage

blib/lib/DNS/NIOS/Traits/AutoPager.pm
Criterion Covered Total %
statement 17 17 100.0
branch 1 2 50.0
condition n/a
subroutine 4 4 100.0
pod n/a
total 22 23 95.6


line stmt bran cond sub pod time code
1             #
2             # This file is part of DNS-NIOS
3             #
4             # This software is Copyright (c) 2021 by Christian Segundo.
5             #
6             # This is free software, licensed under:
7             #
8             # The Artistic License 2.0 (GPL Compatible)
9             #
10             ## no critic
11             package DNS::NIOS::Traits::AutoPager;
12             $DNS::NIOS::Traits::AutoPager::VERSION = '0.003';
13              
14             # ABSTRACT: Handle pagination automatically
15             # VERSION
16             # AUTHORITY
17              
18             ## use critic
19 1     1   633 use strictures 2;
  1         8  
  1         44  
20 1     1   201 use namespace::clean;
  1         2  
  1         7  
21 1     1   187 use Role::Tiny;
  1         2  
  1         6  
22              
23             requires qw( get );
24              
25             around 'get' => sub {
26             my ( $orig, $self, %args ) = @_;
27              
28             my %params = (
29             _return_as_object => 1,
30             _max_results => 100,
31             _paging => 1
32             );
33              
34             my @responses;
35             my $max_results = $args{params}->{_max_results} // 0;
36              
37             $args{params}
38             ? %{ $args{params} } =
39             ( %{ $args{params} }, %params )
40             : $args{params} = \%params;
41              
42             my $response = $orig->( $self, %args );
43             return [$response] if !$response->is_success;
44              
45             push( @responses, $response );
46             while ( $response->content->{next_page_id} ) {
47             last if $max_results and _is_max( $max_results, \@responses );
48             %{ $args{params} } =
49             ( %{ $args{params} }, _page_id => $response->content->{next_page_id} );
50             $response = $orig->( $self, %args );
51             push( @responses, $response );
52             }
53              
54             return \@responses;
55             };
56              
57             sub _is_max {
58 200     200   449 my ( $max, $responses ) = @_;
59              
60 200         330 my $i = 0;
61 200         283 foreach ( @{$responses} ) {
  200         430  
62 20100         29999 foreach ( $_->{results} ) {
63 20100 50       31701 last if $i >= $max;
64 20100         29612 $i++;
65             }
66             }
67 200         975 return $i >= $max;
68             }
69              
70             1;
71              
72             __END__