ResultSet/SetControl.pm

filter: Statementstmt 90.3% 56 / 62 Branchbran 65.3% 17 / 26 Conditioncond 58.3% 7 / 12 MC/DCmcdc 28.5% 2 / 7 Subroutinesub 100% 10 / 10 Podpod 100% 5 / 5 totaltotal 79.5% 97 / 122 CC 19 SCAR 17.6
CC
19
Cov
80%
map
10.0
each
8.1
once
3.4
CRAP 5.8
↑ Summary Util/ResultSet/Iterator.pm »
1 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 package DBIx::Class::ResultSet::SetControl;
5 1 ▶use DBIx::Class::Util::ResultSet::Iterator;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 our $VERSION='0.002';
8  
9 1 ▶my $_itr = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
10 1 my $self = shift;
11 1 return my $itr = DBIx::Class::Util::ResultSet::Iterator->new(resultset=>$self);
12 1 };
13  
14 1 ▶sub map {
Subroutine map: called CC=7 SCAR=23.0
Pod documented
15 1 my ($self, $target, $sub, $fail) = @_;
16  
17 1 my $itr = $self->$_itr;
18 1 ▶ while(my $row = $itr->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $itr->next) 5 1 6
19 {
20 5 local $_ = $row;
21 5 my ($return, @err) = $sub->($itr, $row);
22 5 ▶ $self->throw_exception("'->map' must return a scalar") if @err;
Branch: 1 branch
BranchTrueFalseTotal
if @err 0 5 5
23 5 push @$target, $return;
24 };
25 5 ▶ if($itr->has_escaped) {
Branch: 1 branch
BranchTrueFalseTotal
if ($itr->has_escaped) 0 5 5
26 0 return $itr->resultset;
27 }
28 }
29  
30 1 ▶ if($fail && $itr->has_not_been_used) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fail and $itr->has_not_been_used) 0 1 1
Condition33%1/3
$fail and $itr->has_not_been_used
!ll&&!rl&&r
100
MC/DC0%0/2
$fail and $itr->has_not_been_used
$fail $itr->has_not_been_used
Truth table33%1/3
A and B
A= $failB= $itr->has_not_been_used
ABresult
0X0
100
111
31 0 my ($return, @err) = $fail->($self);
32 0 ▶ $self->throw_exception("'->map' must return a scalar") if @err;
Branch: 1 branch
BranchTrueFalseTotal
if @err 0 0 0
33 0 push @$target, $return;
34 }
35  
36 1 return $self;
37 }
38  
39 8 ▶sub each {
Subroutine each: called CC=8 SCAR=21.0
Pod documented
40 8 my($self, $func_proto, $fail) = @_;
41  
42 ## validate and normalize the function prototype
43 8 ▶ unless(
Branch: 1 branch
BranchTrueFalseTotal
unless ($func_proto and ref $func_proto eq "CODE" || ref $func_proto eq "ARRAY") 0 8 8
Condition50%3/6
$func_proto and ref $func_proto eq "CODE" || ref $func_proto eq "ARRAY"
!ll&&!rl&&r
008
ref $func_proto eq "CODE" or ref $func_proto eq "ARRAY"
l!l&&r!l&&!r
530
MC/DC0%0/3
$func_proto and ref $func_proto eq "CODE" || ref $func_proto eq "ARRAY"
$func_proto ref $func_proto eq "CODE" ref $func_proto eq "ARRAY"
Truth table50%2/4
A and B or C
A= $func_protoB= ref $func_proto eq "CODE"C= ref $func_proto eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
44 $func_proto and (
45 ref($func_proto) eq 'CODE' or
46 ref($func_proto) eq 'ARRAY' )
47 ) {
48 0 $self->throw_exception('Argument must be a CODEREF or ARRAYREF')
49 }
50  
51 ## create a local iterator for the each function
52 8 my @funcs;
53 25 ▶ my $func_itr = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
54 25 ▶ @funcs = ref($func_proto) eq 'ARRAY' ? @$func_proto : $func_proto unless @funcs;
Branch: 2 branches
BranchTrueFalseTotal
unless @funcs 21 4 25
ref $func_proto eq 'ARRAY' ? : 6 15 21
55 25 return shift @funcs;
56 8 };
57  
58 ## Iterate over the resultset
59 8 my $itr = DBIx::Class::Util::ResultSet::Iterator->new(resultset=>$self);
60 8 ▶ while(my $row = $itr->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $itr->next) 25 7 32
61 25 { local $_ = $row; $func_itr->()->($itr, $row) };
62 25 ▶ if($itr->has_escaped) {
Branch: 1 branch
BranchTrueFalseTotal
if ($itr->has_escaped) 1 24 25
63 1 return $itr->resultset;
64 }
65 }
66  
67 ## Handle fails
68 7 ▶ if($fail && $itr->has_not_been_used) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fail and $itr->has_not_been_used) 2 5 7
Condition100%3/3
$fail and $itr->has_not_been_used
!ll&&!rl&&r
322
MC/DC100%2/2
$fail and $itr->has_not_been_used
$fail $itr->has_not_been_used
Truth table100%3/3
A and B
A= $failB= $itr->has_not_been_used
ABresult
0X0
100
111
69 2 $fail->($self);
70 }
71  
72 ## Allow chaining methods
73 7 return $self;
74 }
75  
76 2 ▶sub once {
Subroutine once: called CC=3 SCAR=12.3
Pod documented
77 2 my($self, $func, $fail) = @_;
78 2 ▶ if(my $row = $self->next) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $row = $self->next) { } 2 0 2
elsif ($fail) { } 0 0 0
79 2 { local $_ = $row; $func->($row) };
80 } elsif($fail) {
81 0 $fail->();
82 }
83 2 return $self;
84 }
85  
86 4 ▶sub tap {
Subroutine tap: called CC=1 SCAR=0.0
Pod documented
87 4 my($self, $func, @args) = @_;
88 4 my $new_rs = $self->search_rs;
89 4 { local $_ = $new_rs; $func->($func, $new_rs, @args) };
90 4 return $self;
91 }
92  
93 1 ▶sub times {
Subroutine times: called CC=2 SCAR=6.9
Pod documented
94 1 my($self, $times, $func, @args) = @_;
95 1 $self->tap($func, @args) for 1.. $times;
96 1 return $self;
97 }
98  
99 1 1;
100  
101 =head1 NAME
102  
103 DBIx::Class::ResultSet::SetControl - Easier Looping over resultsets
104  
105 =head1 SYNOPSIS
106  
107 Given a L<DBIx::Class::ResultSet> that consumes this component, such as the
108 following:
109  
110 package MySchema::ResultSet::Bar;
111  
112 use strict;
113 use warnings;
114 use parent 'DBIx::Class::ResultSet';
115  
116 __PACKAGE__->load_components('ResultSet::SetControl');
117  
118 ## Additional custom resultset methods, if any
119  
120 1;
121  
122 Then later when you have a resultset of that class:
123  
124 my $rs = $schema->resultset('Bar');
125  
126 You can call methods directly on your object which are related to control flow
127 and looping over the items in you resultset.
128  
129 $rs->tap(sub {
130 print shift->find({id=>1} ? 'found one' : 'nope';
131 })->each(sub {
132 my ($each, $row) = @_;
133 print $each->is_odd ? $row->name . ' is odd' : 'nope, not odd';
134 });
135  
136 B<NOTE> If you intend to use this component in many of your resultsets, its best
137 practice to write a 'base' resultset that loads this (and any other) components
138 from which all your custom resultset classes inherit.
139  
140 =head1 DESCRIPTION
141  
142 There are times where Perl's procedural syntax for control flow and looping
143 leads to excessively verbose code. For those times we present this helper
144 which is designed to encapsulate some very common control flow and loop patterns
145 for L<DBIx::Class> users.
146  
147 The methods are OO in nature and designed to be compact and concise.
148  
149 Additionally, we have tried to write these methods to allow for a 'chaining'
150 approach that you can't replicate with traditional Perl control and looping
151 structures. Each control flow method returns the original resultset so you
152 can proceed as though it is unaltered (unless of course you alter it somehow
153 like with an insert or update).
154  
155 The goal it to help avoid excessive conditional logic and to allow one to write
156 more compact and neat code. For example, you could replace:
157  
158 my $has_rows;
159 while(my $row = $rs->next) {
160 $has_rows = 1;
161 ## Do something
162 }
163 unless($has_rows) {
164 warn 'no rows!';
165 }
166  
167 With something like
168  
169 $rs->each(sub {
170 my ($each, $row) = @_;
171 ## Do Something
172 }, sub {
173 warn 'no rows!';
174 });
175  
176 The second version has less overall lines and characters, and it also carefully
177 encapsulates a very common pattern, which is to loop over all the rows in a
178 resultset and do something should no rows exist. Also, the L</each> method
179 returns the original C<$rs> so you could chain commands:
180  
181 $rs->each(sub {
182 my ($each, $row) = @_;
183 ## Do Something
184 }, sub {
185 warn 'no rows!';
186 })->tap(sub {
187 my $rs = shift;
188 ## Do something else
189 });
190  
191 There may be cases in your logical flow where this type of programming is more
192 clear and simple; in other cases traditional Perl control and looping might be
193 better. These methods give you an option. On the other hand you might think
194 this is all pointless line noise. As you wish :)
195  
196 =head1 METHODS
197  
198 This component defines the following methods.
199  
200 =head2 map
201  
202 Arguments: $rs->map(\my @mapped_to, $coderef, ?$if_empty_coderef)
203 Returns: Original Resultset OR partly iterated Resultset
204  
205 Example:
206  
207 $schema
208 ->resultset('Person')
209 ->map(\my @list, sub {
210 my ($i, $row) = @_;
211 return +{ id => $row->id };
212 });
213  
214 Where @list will be an array of hashes in the form +{ id => 111 }.
215  
216 Basically this is like:
217  
218 my @list = map { ${ id => $_->id } } $person_rs->all;
219  
220 The two main advantages are that the method returns the resultset so you can chain it
221 and the $i iterator has some ability to control and escape the loop. Also ->all will
222 inflate the entire set whereas map will inflate one at a time (possible memory savings.)
223  
224 $i has some nice 'status of the loop' features such as if the current $row is the first
225 one, or if its odd/even. Be sure to check L<DBIx::Class::Util::ResultSet::Iterator>.
226  
227 It also has an optional third argument that only runs if the set is empty. It runs once
228 and can be used to provide a default value to the target array:
229  
230 $schema
231 ->resultset('Person')
232 ->map(\my @list, sub {
233 my ($i, $row) = @_;
234 return +{ id => $row->id };
235 }, sub {
236 return 'empty list';
237 });
238  
239  
240 Its not amazingly useful standalone but if you are using the other stuff its a nice to
241 have to make the API more complete.
242  
243 =head2 each
244  
245 Arguments: $rs->each($coderef|\@$coderef, ?$if_empty_coderef)
246 Returns: Original Resultset OR partly iterated Resultset
247  
248 Where C<$coderef> is an anonymous subroutine or closure that will get the
249 instantiated L<DBIx::Class::Helpers::Util::ResultSet::Iterator> object and the
250 current C<$row> from the set returned. For example C<$row> in the ResultSet
251 the $coderef will be executed once.
252  
253 C<$if_empty_coderef> is an anonymous subroutine or closure that gets
254 executed ONLY if there were no rows in the set. It gets the C<$resultset>
255 as an argument (this might change later if we discover a better thing to do
256 here).
257  
258 In the case where the first argument is an arrayref of coderefs, we automatically
259 iterate over each coderef for each result in the set in turn and reset the
260 coderef iterator as needed to make sure we hit every item in the set. Please
261 be aware that in the case where the arrayref of coderefs is longer than the
262 available results in the set, this means that not all coderefs will be invoked
263 and this happens without an exception being thrown.
264  
265 Example: For the given L<DBIx::Class::ResultSet>, iterator over each result.
266  
267 $rs->each(sub {
268 my ($each, $row) = @_;
269 ...
270 });
271  
272 This is functionally similar to something like:
273  
274 my $itr = DBIx::Class::Util::ResultSet::Iterator->new(resultset=>$rs);
275 while(my $row = $itr->next) {
276 ...
277 }
278  
279 However the method will return the original $resultset used to initialize it
280 so that you can continue chaining or building off it. Of course you will need
281 to issue a c<ResultSet->reset> for this to be useful.
282  
283 Here's a more detailed example.
284  
285 $rs->each(sub {
286 my ($each, $row) = @_;
287  
288 $each->first(sub {
289 print "Hey, this is the first row!";
290 });
291  
292 if($each->is_odd) {
293 print $row->columnname;
294 } else {
295 return $each->escape;
296 }
297 }, sub {
298 my ($rs) = @_;
299 warn "The resultset was empty, nothing done...";
300 });
301  
302 Finally one example using an arrayref as the first argument:
303  
304 $rs->each(
305 [
306 sub { ... },
307 sub { ... },
308 sub { ... },
309 ], sub {
310 my ($rs) = @_;
311 warn "The resultset was empty, nothing done...";
312 }
313 );
314  
315 You may find this helper leads you to writing more concise and compact code.
316 Additionally having an iterator object available can be helpful, particularly
317 when you are in a template and need to display things differently based on if
318 the row is even/odd, first/last, etc.
319  
320 You should see the documentation for L<DBIx::Class::Util::ResultSet::Iterator>
321 for the methods this object exposes for use.
322  
323 B<NOTE> For conciseness in simple cases, we overload C<$_> to equal the value of
324 C<$row> as described above.
325  
326 =head2 once
327  
328 Arguments: $rs->once($coderef, ?$if_empty_coderef)
329 Returns: Partly iterated Resultset
330  
331 Works just like L</each> expect instead of iterating over the entire resultset
332 we just take the first C<$row>.
333  
334 Example
335  
336 $rs->once( sub {
337 my ($row) = @_;
338 }, sub {
339 warn 'no rows left!';
340 })->each( ... );
341  
342 Useful to isolate the logic for the first row in a resultset.
343  
344 B<NOTE> For conciseness in simple cases, we overload C<$_> to equal the value of
345 C<$row> as described above.
346  
347 =head2 tap
348  
349 Arguments: $coderef, ?@args
350 Returns: Original Resultset
351  
352 Do a coderef with the resultset passed as an argument.
353  
354 $rs->tap(sub {
355 my ($func, $rs, $arg) = @_;
356 $rs->find({id=>$arg});
357 }, 100);
358  
359 If you pass more than one argument, all the extra arguments will be send to the
360 anonymous coderef.
361  
362 B<NOTE> The resultset passed is cloned from the original and it returns the original
363 resultset so you can chain.
364  
365 B<NOTE> the first argument passed to the coderef is the orginal coderef so that you can
366 call recursively.
367  
368 B<NOTE> For conciseness in simple cases, we overload C<$_> to equal the value of
369 C<$rs> as described above.
370  
371 =head2 times
372  
373 Arguments: $integer, $coderef, ?@args
374 Returns: Original Resultset
375  
376 Basically this calls L</tap> a number of times equal to the first argument.
377  
378 $rs->times(3, sub {
379 my $rs = shift;
380 ...
381 });
382  
383 B<NOTE> For conciseness in simple cases, we overload C<$_> to equal the value of
384 C<$rs> as described above.
385  
386 =head1 AUTHOR
387  
388 John Napiorkowski L<email:jjnapiork@cpan.org>
389  
390 =head1 SEE ALSO
391  
392 L<DBIx::Class>
393  
394 =head1 COPYRIGHT & LICENSE
395  
396 Copyright 2017, John Napiorkowski L<email:jjnapiork@cpan.org>
397  
398 This library is free software; you can redistribute it and/or modify it under
399 the same terms as Perl itself.
400  
401 =cut
↑ Summary Util/ResultSet/Iterator.pm »