MenuGrinder/Visitor.pm untested

filter: Statementstmt 0.0% 0 / 52 Branchbran 0.0% 0 / 28 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 89 CC 15 SCAR 50.0
CC
15
Cov
0%
_visit
210.0
visit_menu
6.0
BEGIN
2.0
CRAP 148.0
1 package WWW::MenuGrinder::Visitor;
2 BEGIN {
3 $WWW::MenuGrinder::Visitor::VERSION = '0.06';
4 }
5  
6 # ABSTRACT: WWW::MenuGrinder plugin that allows item-by-item mogrification.
7  
8 use Moose;
9  
10 use Scalar::Util;
11  
12 # Nothing on CPAN gives me a nice simple interface as well as post-order
13 # traversal so here's one we prepared earlier.
14  
15 # Traverse a tree-like data structure, making a copy of it and modifying it
16 # along the way.
17 sub _visit {
18 my ( $obj, $cb ) = @_;
19  
20 my $reftype = Scalar::Util::reftype($obj);
21  
22 if ( defined $reftype ) {
23 # Don't bother with any fancy inheritance checks, just mostly leave objects
24 # alone.
25 if (Scalar::Util::blessed($obj)) {
26 return $cb->{OBJECT}->($obj) if defined $cb->{OBJECT};
27 return $obj;
28 }
29 if ( $reftype eq 'HASH' ) {
30 my $tmp = {};
31 for my $key ( keys %{$obj} ) {
32 my @ret = _visit( $_[0]{$key}, $cb );
33 $tmp->{$key} = $ret[0] if @ret;
34 }
35  
36 return $cb->{HASH}->($tmp) if exists $cb->{HASH};
37 return $tmp;
38 } elsif ( $reftype eq 'ARRAY' ) {
39 my $tmp = [];
40 for my $val ( @{$obj} ) {
41 push @$tmp, _visit( $val, $cb );
42 }
43  
44 return $cb->{ARRAY}->($tmp) if exists $cb->{ARRAY};
45 return $tmp;
46 } elsif ( $reftype eq 'SCALAR' ) {
47 my $tmp = \( _visit( $$obj, $cb ) );
48  
49 return $cb->{SCALARREF}->($tmp) if exists $cb->{SCALARREF};
50 return $tmp;
51 } elsif ( $reftype eq 'GLOB' ) {
52 my $tmp = $obj;
53 return $cb->{GLOB}->($tmp) if exists $cb->{GLOB};
54 return $tmp;
55 } else {
56 warn "Ignoring a $reftype-reference I don't know how to handle.";
57 return $obj;
58 }
59 } else { # Not a reference
60 return $cb->{SCALAR}->($obj) if defined $cb->{SCALAR};
61 return $obj;
62 }
63 }
64  
65 sub visit_menu {
66 my ( $self, $menu, $actions ) = @_;
67  
68 # warn "Doing at once: ", (join ", ", map { $_->{plugin} } @$actions), "\n";
69  
70 $menu = _visit($menu, {
71 HASH => sub {
72 my ( $item ) = @_;
73 for my $action (@$actions) {
74 my $plugin = $action->{plugin};
75 my $method = $action->{method};
76 $item = $plugin->$method($item);
77 return () unless defined $item;
78 }
79 return $item;
80 },
81 }
82 );
83  
84 return $menu;
85 }
86  
87 __PACKAGE__->meta->make_immutable;
88  
89 no Moose;
90 1;
91  
92  
93 __END__