App/Role/HasHooks.pm untested

filter: Statementstmt 0.0% 0 / 35 Branchbran 0.0% 0 / 10 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 56 CC 6 SCAR 19.8
CC
6
Cov
0%
call_hook
12.0
register_hook
12.0
hook
6.0
CRAP 7.2
1 package Gapp::App::Role::HasHooks;
2 {
3 $Gapp::App::Role::HasHooks::VERSION = '0.007';
4 }
5  
6 use Moose::Role;
7 use MooseX::SemiAffordanceAccessor;
8 use MooseX::StrictConstructor;
9  
10 use Gapp::App::Hook;
11  
12 use MooseX::Types::Moose qw( Str Object );
13  
14 has '_hooks' => (
15 is => 'ro',
16 isa => 'HashRef',
17 default => sub { { } },
18 lazy => 1,
19 );
20  
21 # call a hook
22 sub call_hook {
23 my ( $self, $hook_name, @params ) = @_;
24 return if ! $self->_hooks->{$hook_name};
25
26 my $hook = $self->_hooks->{$hook_name};
27 return if ! $hook;
28
29 $hook->call( $self, @params );
30 }
31  
32  
33 # register a callback to a hook
34 sub hook {
35 my ( $self, $hook_name, $plugin, $function, $data ) = @_;
36
37 # create a hook if it does not exist already
38 $self->_hooks->{$hook_name} = $self->register_hook( $hook_name ) if ! $self->_hooks->{$hook_name};
39
40 my $hook = $self->_hooks->{$hook_name};
41 $hook->push( $plugin, $function, $data );
42 }
43  
44 # define behavior of a hook
45 sub register_hook {
46 my ( $self, $hook, %opts ) = @_;
47
48 # if is a string, create a new hook
49 if ( is_Str( $hook ) ) {
50 $hook = $self->_hooks->{$hook} = Gapp::App::Hook->new( name => $hook, %opts );
51 }
52 # if is a hook object, just add it to the registry
53 elsif ( is_Object( $hook ) ) {
54 $self->_hooks->{$hook->name} = $hook;
55 }
56 # if not a string or hook, die
57 else {
58 $self->meta->throw_error( qq[could not register hook $hook, not a string or Gapp::App::Plugin::Hook] );
59 }
60
61 return $hook;
62 }
63  
64  
65  
66 1;
67  
68  
69 __END__