blib/lib/Sub/Methodical.pm untested

filter: Statementstmt 0.0% 0 / 101 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 157 CC 7 SCAR 19.8
CC
7
Cov
0%
_wrap
20.0
_build_MODIFY
12.0
_build_AUTOLOAD
6.0
CRAP 7.2
1 use strict;
2 use warnings;
3  
4 package Sub::Methodical;
5  
6 our $VERSION = '0.002';
7  
8 my %methodical;
9 my %wrapped;
10 my %auto_methodical;
11  
12 use B;
13 use PadWalker;
14 use Filter::EOF;
15 use Sub::Install ();
16 use Sub::Exporter -setup => {
17 exports => [
18 MODIFY_CODE_ATTRIBUTES => \&_build_MODIFY,
19 AUTOLOAD => \&_build_AUTOLOAD,
20 ],
21 groups => {
22 default => [qw(MODIFY_CODE_ATTRIBUTES)],
23 inherit => [qw(AUTOLOAD)],
24 },
25 collectors => {
26 -auto => sub {
27 my ($col, $arg) = @_;
28 $auto_methodical{$arg->{into}} = 1;
29 push @{ $arg->{import_args} }, (
30 [ 'MODIFY_CODE_ATTRIBUTES', undef ],
31 );
32 },
33 },
34 };
35  
36 sub _build_MODIFY {
37 Filter::EOF->on_eof_call(sub {
38 for my $pkg (keys %methodical) {
39 for my $sub (@{ $methodical{$pkg} }) {
40 _wrap($pkg, $sub);
41 }
42 }
43 for my $pkg (keys %auto_methodical) {
44 no strict 'refs';
45 for my $subname (grep {
46 !/^MODIFY_.+_ATTRIBUTES$/ &&
47 $_ ne 'AUTOLOAD' &&
48 !/^_/ &&
49 *{$pkg . '::' . $_}{CODE}
50 } keys %{$pkg . '::'}) {
51 my $sub = \&{$pkg . '::' . $subname};
52 next unless B::svref_2object($sub)->STASH->NAME eq $pkg;
53 _wrap($pkg, $sub);
54 }
55 }
56 });
57 return sub {
58 my ($pkg, $ref, @attrs) = @_;
59  
60 if (ref $ref eq 'CODE' and grep { $_ eq 'Methodical' } @attrs) {
61 push @{ $methodical{$pkg} ||= [] }, $ref;
62 @attrs = grep { $_ ne 'Methodical' } @attrs;
63 }
64 return @attrs;
65 };
66 }
67  
68 sub _build_AUTOLOAD {
69 return sub {
70 our $AUTOLOAD;
71 my ($pkg, $method) = $AUTOLOAD =~ /^(.+)::(.+)$/;
72 my ($wrap_pkg) = grep { $pkg->isa($_) && $wrapped{$_}{$method} }
73 keys %wrapped;
74 if ($wrap_pkg) {
75 no strict 'refs';
76 goto &{$wrap_pkg . '::' . $method};
77 }
78 require Carp;
79 Carp::croak "Undefined subroutine &$AUTOLOAD called";
80 };
81 }
82  
83 sub _wrap {
84 my ($pkg, $sub) = @_;
85 require B;
86 my $name = B::svref_2object($sub)->GV->NAME;
87 (my $as = $name) =~ s/.*:://;
88 #warn "wrapping $name ($pkg\::$as)\n";
89 $wrapped{$pkg}{$as} = $sub;
90 Sub::Install::reinstall_sub({
91 into => $pkg,
92 as => $as,
93 code => sub {
94 if (eval { $_[0]->isa($pkg) }) {
95 #warn "calling $name directly: @_\n";
96 return $sub->(@_);
97 }
98 my $pad = PadWalker::peek_my(1);
99 my $self = $pad->{'$self'};
100 unless ($self) {
101 die "can't find \$self!";
102 }
103 unless (eval { $$self->isa($pkg) }) {
104 require Carp;
105 Carp::croak sprintf
106 "Methodical '%s' called with incorrect invocant '%s' (wanted '%s')",
107 $as, $$self, $pkg;
108 }
109 #warn "calling $name with self = $$self, @_\n";
110 $$self->$as(@_);
111 },
112 });
113 }
114  
115 1;
116 __END__