Sub.pm

filter: Statementstmt 100% 99 / 99 Branchbran 100% 24 / 24 Conditioncond 66.6% 2 / 3 MC/DCmcdc 50.0% 1 / 2 Subroutinesub 93.7% 15 / 16 Podpod 100% 7 / 7 totaltotal 98.0% 148 / 151 CC 18 SCAR 18.2
CC
18
Cov
99%
wrap
13.0
wrapped_subs
3.0
is_wrapped
3.0
CRAP 6.2
↑ Summary Sub/Child.pm »
1 package Wrap::Sub;
2 18 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 18 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 18 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 18 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 18 ▶use Devel::Examine::Subs;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 18 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 18 ▶use Wrap::Sub::Child;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 18 our $VERSION = '0.06';
12  
13 47 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
14 47 my $self = bless {}, shift;
15 47 %{ $self } = @_;
16 47 return $self;
17 }
18 55 ▶sub wrap {
Subroutine wrap: called CC=13 SCAR=25.6
Pod documented
19 55 my $self = shift;
20 55 my $sub = shift;
21  
22 55 ▶ if (ref $self ne 'Wrap::Sub'){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self ne "Wrap::Sub") 2 53 55
23 2 croak "\ncan't call wrap() directly from the class. Create an object ".
24 "with new() first.\n";
25 }
26 53 ▶ if (! defined wantarray){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 1 52 53
27 1 croak "\n\ncalling wrap() in void context isn't allowed. ";
28 }
29  
30 52 my %p = @_;
31 52 for (keys %p){
32 11 $self->{$_} = $p{$_};
33 }
34  
35 52 my ($symtab, $module, $is_module);
36  
37 52 ▶ if (! defined &$sub){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined &$sub) 22 30 52
38 18 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 22 $module = $sub;
41 22 $symtab = $module;
42 22 $symtab .= "::";
43 22 ▶ $is_module = 1 if keys %$symtab;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$symtab 5 17 22
44 }
45  
46 52 my @subs;
47  
48 52 ▶ if ($is_module){
Branch: 1 branch
BranchTrueFalseTotal
if ($is_module) { } 5 47 52
49  
50 5 ( my $module_file = $module ) =~ s|::|/|g;
51 5 $module_file .= '.pm';
52 5 my $backup_file = $module_file;
53 5 $backup_file =~ s|.*/||;
54 5 $backup_file .= '.bak';
55  
56 5 my $des = Devel::Examine::Subs->new(file => $INC{$module_file});
57  
58 5 my $all = $des->all;
59 5 @subs = map { "$module\::$_" } @$all;
60 }
61 else {
62 47 push @subs, $sub;
63 }
64  
65 52 my @children;
66  
67 52 for my $sub (@subs) {
68 76 my $child = Wrap::Sub::Child->new;
69  
70 # allow parent capture of child sta
71 76 $child->{wrapper} = $self;
72  
73 76 ▶ $child->pre($self->{pre}) if $self->{pre};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pre"} 9 67 76
74  
75 75 ▶ if (defined $self->{post_return} && $self->{post}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->{'post_return'} and $self->{'post'}) { } 9 66 75
elsif ($self->{'post'}) { } 7 59 66
Condition66%2/3
defined $self->{"post_return"} and $self->{"post"}
!ll&&!rl&&r
6609
MC/DC50%1/2
defined $self->{"post_return"} and $self->{"post"}
defined $self->{"post_return"} $self->{"post"}
Truth table66%2/3
A and B
A= defined $self->{"post_return"}B= $self->{"post"}
ABresult
0X0
100
111
76 9 $child->post($self->{post}, post_return => $self->{post_return});
77 }
78 elsif ($self->{post}) {
79 7 $child->post($self->{post});
80 }
81  
82 75 $self->{objects}{$sub}{obj} = $child;
83 75 $child->_wrap($sub);
84  
85 # remove the REFCNT to the child, or else DESTROY won't be called
86 72 weaken $self->{objects}{$sub}{obj};
87  
88 72 push @children, $child;
89 }
90  
91 48 ▶ if (! $is_module) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_module) { } 44 4 48
92 44 return $children[0];
93 }
94 else {
95 4 my %child_hash = map { $_->name => $_ } @children;
96 4 return \%child_hash;
97 }
98 }
99 1 ▶sub pre_results {
Subroutine pre_results: called CC=1 SCAR=0.0
Pod documented
100 1 return @{ $_[0]->{pre_returns} };
101 }
102 1 ▶sub post_results {
Subroutine post_results: called CC=1 SCAR=0.0
Pod documented
103 1 return @{ $_[0]->{post_returns} };
104 }
105 3 ▶sub wrapped_subs {
Subroutine wrapped_subs: called CC=3 SCAR=11.0
Pod documented
106 3 my $self = shift;
107  
108 3 my @names;
109  
110 3 for (keys %{ $self->{objects} }) {
111 9 ▶ if ($self->is_wrapped($_)){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_wrapped($_)) 8 1 9
112 8 push @names, $_;
113 }
114 }
115 3 return @names;
116 }
117 2 ▶sub wrapped_objects {
Subroutine wrapped_objects: called CC=2 SCAR=6.9
Pod documented
118 2 my $self = shift;
119  
120 2 my @wrapped;
121 2 for (keys %{ $self->{objects} }){
122 6 push @wrapped, $self->{objects}{$_}{obj};
123 }
124 2 return @wrapped;
125 }
126 13 ▶sub is_wrapped {
Subroutine is_wrapped: called CC=3 SCAR=11.0
Pod documented
127 13 my ($self, $sub) = @_;
128  
129 13 ▶ if (! $sub){
Branch: 1 branch
BranchTrueFalseTotal
unless ($sub) 1 12 13
130 1 croak "calling is_wrapped() on a Wrap::Sub object requires a sub " .
131 "name to be passed in as its only parameter. ";
132 }
133  
134 12 eval {
135 12 my $test = $self->{objects}{$sub}{obj}->is_wrapped;
136 };
137 12 ▶ if ($@){
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 11 12
138 1 croak "can't call is_wrapped() on the class if the sub hasn't yet " .
139 "been wrapped. ";
140 }
141 11 return $self->{objects}{$sub}{obj}->is_wrapped;
142 }
143 0 ▶sub __end {}; # vim fold placeholder
Subroutine __end: not called CC=1 SCAR=0.0
144  
145 18 1;
146 =head1 NAME
147  
148 Wrap::Sub - Object Oriented subroutine wrapper with pre and post hooks, and more.
149  
150 =for html
151 <a href="http://travis-ci.org/stevieb9/wrap-sub"><img src="https://secure.travis-ci.org/stevieb9/wrap-sub.png"/>
152 <a href='https://coveralls.io/github/stevieb9/wrap-sub?branch=master'><img src='https://coveralls.io/repos/stevieb9/wrap-sub/badge.svg?branch=master&service=github' alt='Coverage Status' /></a>
153  
154 =head1 SYNOPSIS
155  
156 use Wrap::Sub;
157  
158 Basic functionality example
159  
160 my $wrapper = Wrap::Sub->new;
161  
162 # create the wrapped sub object
163  
164 my $foo_obj = $wrapper->wrap(
165 'My::Module::foo',
166 pre => sub { print "$Wrap::Sub::name in pre\n"; },
167 post => sub { print "$Wrap::Sub::name in post\n"; },
168 );
169  
170 # add/change/remove a routine via a method call (send in undef to remove)
171  
172 $foo_obj->pre(sub { print "changed pre\n"; } );
173 $foo_obj->post(sub { print "changed post\n"; } );
174  
175 # name of sub
176  
177 $foo_obj->name;
178  
179 # unwrap and rewrap
180  
181 $foo_obj->unwrap;
182 $foo_obj->rewrap;
183  
184 # wrapped or not?
185  
186 my $is_wrapped = $foo_obj->is_wrapped;
187  
188 # list all subs wrapped under the current wrap object
189  
190 my @wrapped_subs = $wrapper->wrapped_subs;
191  
192 # retrieve all wrapped sub objects
193  
194 my @sub_objects = $wrapper->wrapped_objects;
195  
196 Here's an example that shows how you can get elapsed time of a sub (this
197 example requires L<Time::HiRes>)
198  
199 my $pre_cref = sub {
200 return gettimeofday();
201 };
202  
203 my $post_cref = sub {
204 my $pre_return = shift;
205 my $time = gettimeofday() - $pre_return->[0];
206 print "$Wrap::Sub::name finished in $time seconds\n";
207 };
208  
209 $foo_obj->pre($pre_cref);
210 $foo_obj->post($post_cref);
211  
212 Manipulate the return from the original subroutine, take action, then return
213 the modified results
214  
215 my $post_cref = sub {
216 my ($pre_return, $sub_return) = @_;
217  
218 if ($sub_return->[0] != 1){
219 die "$Wrap::Sub::name returned an error\n";
220 }
221 else {
222 $sub_return->[0] = 100;
223 return $sub_return->[0];
224 }
225 };
226  
227 $foo_obj->post($post_cref, post_return => 1);
228  
229 Get an ordered list (array of array references) of the last expression
230 evaluated in all sub object C<pre()> and C<post()> functions
231  
232 my @pre_results = $wrapper->pre_results;
233 my @post_results = $wrapper->post_results;
234  
235 for my $sub_post_result (@post_results){
236 print "$sub_post_result->[0]\n";
237 }
238  
239 Wrap all subs in a module (does not include imported subs), and have them all
240 perform the same actions
241  
242 my $wrapper = Wrap::Sub->new(
243 pre => sub { print "start $Wrap::Sub::name\n"; },
244 post => sub { print "finish $Wrap::Sub::name\n"; },
245 );
246  
247 # wrapping a module returns an href with the sub name as the key,
248 # and the value being the wrapped sub object
249  
250 my $module_subs = $wrapper->wrap('My::Module');
251  
252 # unwrap them all, and confirm
253  
254 for my $sub_name (keys %$module_subs){
255 my $sub_obj = $module_subs->{$sub_name};
256  
257 print "$sub_name is wrapped\n" if $sub_obj->is_wrapped;
258  
259 $sub_obj->unwrap;
260  
261 if ($sub_obj->is_wrapped) {
262 die "$sub_name not unwrapped!"
263 }
264 }
265  
266 =head1 DESCRIPTION
267  
268 This module allows you to wrap subroutines with pre and post hooks while
269 keeping track of your wrapped subs. It also allows you to easily wrap all subs
270 within a module (while filtering out the subs that are imported).
271  
272 Thanks to code taken out of L<Hook::LexWrap>, C<caller()> works properly within
273 the wrapped subs.
274  
275 There are other modules that do this, see L<SEE ALSO>. I wrote it out of sheer
276 curiosity and experience, not because I didn't check the CPAN for existing
277 modules that do the same thing.
278  
279 =head1 WRAP OBJECT METHODS
280  
281 =head2 C<new(%opts)>
282  
283 Instantiates and returns a new C<Wrap::Sub> object, ready to be used to start
284 creating wrapped sub objects.
285  
286 Options (note that if these are set in C<new()>, all subs wrapped with this
287 object will exhibit the same behaviour. Set in C<wrap()> or use C<pre()> and
288 C<post()> methods to individualize wrapped subroutine behaviour).
289  
290 =over 4
291  
292 =item C<pre =E<gt> $cref>
293  
294 A code reference containing actions that will be executed prior to executing
295 the sub that's wrapped. Receives the parameters that are sent into the wrapped
296 sub (C<@_>). Has access to C<$Wrap::Sub::name> parameter, which holds the name
297 of the original wrapped sub.
298  
299 =item C<post =E<gt> $cref>
300  
301 A code reference containing actions that will be executed after the wrapped
302 sub is executed. Has access to C<$Wrap::Sub::name> parameter, which holds the
303 name of the original wrapped sub.
304  
305 Receives an array reference with two elements, each another array reference.
306 The first inner reference contains the return value(s) from the C<pre> hook,
307 and the second contains the return value(s) from the wrapped sub. If neither
308 C<pre> or the actual sub have return values, the respective inner array
309 reference will be empty.
310  
311 Returns whatever you decide you want it to. See C<post_return> parameter for
312 further details on returning values.
313  
314 =item C<post_return =E<gt> Bool>
315  
316 Set this to true if you want your C<post()> hook to return its results, and
317 false if you want the return value(s) from the actual wrapped sub instead.
318 Disabled by default (ie. you'll get the return from the original sub).
319  
320 =back
321  
322 =head2 C<wrap('sub', %opts)>
323  
324 Instantiates and returns a new wrapped sub object on each call. C<sub> is the
325 name of the subroutine to wrap (requires full package name if the sub isn't in
326 C<main::>).
327  
328 Options:
329  
330 See C<new()> for a description of the parameters. Setting them here allows you
331 to individualize behaviour of the hooks for each wrapped subroutine.
332  
333 =head2 C<wrapped_subs>
334  
335 Returns a list of all the names of the subs that are currently wrapped under
336 the parent wrap object.
337  
338 =head2 C<wrapped_objects>
339  
340 Returns a list of all sub objects underneath the parent wrap object, regardless
341 if its sub is currently wrapped or not.
342  
343 =head2 C<is_wrapped('Sub::Name')>
344  
345 Returns 1 if the sub currently under the parent wrap object is wrapped or not,
346 and 0 if not. Croaks if there hasn't been a child sub object created with this
347 sub name.
348  
349 =head2 C<pre_results>
350  
351 As each wrapped sub is called where a C<pre()> method is set, we'll stash the
352 last expression evaluated in it, and push the results to an array. This method
353 will fetch that array.
354  
355 Each entry is an array reference per C<pre()> call, containing the returned data.
356  
357 =head2 C<post_results>
358  
359 As each wrapped sub is called where a C<post()> method is set, we'll stash the
360 last expression evaluated in it, and push the results to an array. This method
361 will fetch that array.
362  
363 Each entry is an array reference per C<post()> call, containing the returned data.
364  
365 =head1 WRAPPED SUB OBJECT METHODS
366  
367 These methods are for the children wrapped sub objects returned from the
368 parent wrap object. See L<WRAP OBJECT METHODS> for methods related
369 to the parent wrap object.
370  
371 =head2 C<name>
372  
373 Returns the name of the sub represented by this sub object.
374  
375 =head2 C<pre($cref)>
376  
377 Send in a code reference containing actions that you want to have performed
378 prior to the wrapped sub being executed. Has access to C<$Wrap::Sub::name>
379 parameter, which holds the name of the original wrapped sub.
380  
381 =head2 C<post($cref, post_return =E<gt> Bool)>
382  
383 A code reference containing actions that will be executed after the wrapped
384 sub is executed. Has access to C<$Wrap::Sub::name> parameter, which holds the
385 name of the original wrapped sub.
386  
387 The code supplied receives an array reference containing an array reference
388 holding the return values from C<pre()> and a second array reference containing
389 the return values from the actual wrapped sub. If neither C<pre> or the actual
390 sub have return values, the respective array reference will be empty.
391  
392 The optional parameter C<post_return> specifies that you want the return
393 value(s) from this function instead of the return value(s) generated by the
394 wrapped sub. Disabled by default.
395  
396 =head2 C<unwrap>
397  
398 Restores the original functionality back to the sub, and runs C<reset()> on
399 the object.
400  
401 =head2 C<rewrap>
402  
403 Re-wraps the sub within the object after calling C<unwrap> on it.
404  
405 =head2 C<reset>
406  
407 Resets the functional parameters (C<pre>, C<post> and C<post_return>), along
408 with C<called()> and C<called_with> back to undef/false. Does not restore
409 the sub back to its original state.
410  
411 =head2 C<is_wrapped>
412  
413 Returns true (1) if the sub the object refers to is currently wrapped, and
414 false (0) if not.
415  
416 =head2 C<called>
417  
418 Returns true (1) if the sub being wrapped has been called, and false (0) if
419 not.
420  
421 =head2 C<called_with>
422  
423 Returns an array of the parameters sent to the subroutine. C<croak()s> if
424 we're called before the wrapped sub has been called.
425  
426 =head1 NOTES
427  
428 This module has a backwards parent-child relationship. To use, you create a
429 wrap object using L<WRAP OBJECT METHODS> C<new> and C<wrap> methods,
430 thereafter, you use the returned wrapped sub object L<WRAPPED SUB OBJECT METHODS>
431 to perform the work.
432  
433 =head1 SEE ALSO
434  
435 This module was created for my own sheer curiosity and experience. There are
436 quite a few like it. I've never used any of them (this list was taken from
437 L<Hook::WrapSub>):
438  
439 L<Hook::LexWrap> provides a similar capability to C<Hook::WrapSub>,
440 but has the benefit that the C<caller()> function works correctly
441 within the wrapped subroutine.
442  
443 L<Sub::Prepend> lets you provide a sub that will be called before
444 a named sub. The C<caller()> function works correctly in the
445 wrapped sub.
446  
447 L<Sub::Mage> provides a number of related functions.
448 You can provide pre- and post-call hooks,
449 you can temporarily override a function and then restore it later,
450 and more.
451  
452 L<Class::Hook> lets you add pre- and post-call hooks around any
453 methods called by your code. It doesn't support functions.
454  
455 L<Hook::Scope> lets you register callbacks that will be invoked
456 when execution leaves the scope they were registered in.
457  
458 L<Hook::PrePostCall> provides an OO interface for wrapping
459 a function with pre- and post-call hook functions.
460 Last updated in 1997, and marked as alpha.
461  
462 L<Hook::Heckle> provides an OO interface for wrapping pre- and post-call
463 hooks around functions or methods in a package. Not updated sinc 2003,
464 and has a 20% failed rate on CPAN Testers.
465  
466 L<Class::Wrap> provides the C<wrap()> function, which takes a coderef
467 and a package name. The coderef is invoked every time a method in
468 the package is called.
469  
470 L<Sub::Versive> lets you stack pre- and post-call hooks.
471 Last updated in 2001.
472  
473 =head1 AUTHOR
474  
475 Steve Bertrand, C<< <steveb at cpan.org> >>
476  
477 =head1 BUGS
478  
479 Please report any bugs or requests at
480 L<https://github.com/stevieb9/wrap-sub/issues>
481  
482 =head1 REPOSITORY
483  
484 L<https://github.com/stevieb9/wrap-sub>
485  
486 =head1 BUILD RESULTS
487  
488 CPAN Testers: L<http://matrix.cpantesters.org/?dist=Wrap-Sub>
489  
490 =head1 SUPPORT
491  
492 You can find documentation for this module with the perldoc command.
493  
494 perldoc Wrap::Sub
495  
496 =head1 LICENSE AND COPYRIGHT
497  
498 Copyright 2016 Steve Bertrand.
499  
500 This program is free software; you can redistribute it and/or modify it
501 under the terms of either: the GNU General Public License as published
502 by the Free Software Foundation; or the Artistic License.
503  
504 See L<http://dev.perl.org/licenses/> for more information.
505  
506  
507 =cut
508  
509 18 1; # End of Wrap::Sub
510  
↑ Summary Sub/Child.pm »