App/Chart/Glib/Ex/EmissionHook.pm untested

filter: Statementstmt 0.0% 0 / 32 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 4 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 52 CC 2 SCAR 10.6
CC
2
Cov
0%
_handler
6.0
new
2.0
DESTROY
2.0
CRAP 2.9
1 # Copyright 2009, 2010, 2011, 2016 Kevin Ryde
2  
3 # This file is part of Chart.
4 #
5 # Chart is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3, or (at your option) any later version.
8 #
9 # Chart is distributed in the hope that it will be useful, but WITHOUT ANY
10 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Chart. If not, see <http://www.gnu.org/licenses/>.
16  
17 package App::Chart::Glib::Ex::EmissionHook;
18 use 5.008;
19 use strict;
20 use warnings;
21 use Scalar::Util;
22  
23 sub new {
24 my ($class, $target_class, $signal_name, $handler, @userdata) = @_;
25 my $self = bless { target_class => $target_class,
26 signal_name => $signal_name,
27 handler => $handler,
28 userdata => \@userdata,
29 }, $class;
30 my $weak_self = $self;
31 Scalar::Util::weaken ($weak_self);
32 $self->{'hook_id'} = $target_class->signal_add_emission_hook
33 ($signal_name, \&_handler, \$weak_self);
34 return $self;
35 }
36  
37 sub _handler {
38 my ($invocation_hint, $parameters, $ref_weak_self) = @_;
39 my $self = $$ref_weak_self || return 0; # disconnect
40 my $stay_connected = &{$self->{'handler'}}
41 ($invocation_hint, $parameters, @{$self->{'userdata'}});
42 if (! $stay_connected) {
43 delete $self->{'hook_id'};
44 }
45 return $stay_connected;
46 }
47  
48 # Had some trouble in the past removing an emission hook under global
49 # destruction when the class had already removed all hooks, or something
50 # like that.
51 #
52 sub DESTROY {
53 my ($self) = @_;
54 $self->remove;
55 }
56  
57 sub remove {
58 my ($self) = @_;
59 my $hook_id = delete $self->{'hook_id'} || return; # already removed
60 $self->{'target_class'}->signal_remove_emission_hook
61 ($self->{'signal_name'}, $hook_id);
62 }
63  
64 1;
65 __END__