2010-03-22 08:33:44 +01:00
|
|
|
# File: Registerable.pm
|
|
|
|
# Author: pragma_
|
|
|
|
#
|
|
|
|
# Purpose: Provides functionality to register and execute one or more subroutines.
|
|
|
|
|
2017-03-05 22:33:31 +01:00
|
|
|
# This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
|
|
|
2010-03-22 08:33:44 +01:00
|
|
|
package PBot::Registerable;
|
|
|
|
|
|
|
|
use warnings;
|
|
|
|
use strict;
|
|
|
|
|
2019-07-11 03:40:53 +02:00
|
|
|
use feature 'unicode_strings';
|
|
|
|
|
2010-03-22 08:33:44 +01:00
|
|
|
use Carp ();
|
|
|
|
|
|
|
|
sub new {
|
2019-05-28 18:19:42 +02:00
|
|
|
if (ref($_[1]) eq 'HASH') {
|
2010-03-22 08:33:44 +01:00
|
|
|
Carp::croak("Options to Registerable should be key/value pairs, not hash reference");
|
|
|
|
}
|
|
|
|
|
|
|
|
my ($class, %conf) = @_;
|
|
|
|
my $self = bless {}, $class;
|
|
|
|
$self->initialize(%conf);
|
|
|
|
return $self;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub initialize {
|
|
|
|
my $self = shift;
|
|
|
|
$self->{handlers} = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
sub execute_all {
|
|
|
|
my $self = shift;
|
|
|
|
|
2011-01-29 00:16:50 +01:00
|
|
|
foreach my $func (@{ $self->{handlers} }) {
|
|
|
|
my $result = &{ $func->{subref} }(@_);
|
|
|
|
return $result if defined $result;
|
2010-03-22 08:33:44 +01:00
|
|
|
}
|
|
|
|
return undef;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub execute {
|
|
|
|
my $self = shift;
|
|
|
|
my $ref = shift;
|
|
|
|
|
2019-05-28 18:19:42 +02:00
|
|
|
if (not defined $ref) {
|
2010-03-22 08:33:44 +01:00
|
|
|
Carp::croak("Missing reference parameter to Registerable::execute");
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach my $func (@{ $self->{handlers} }) {
|
2019-05-28 18:19:42 +02:00
|
|
|
if ($ref == $func || $ref == $func->{subref}) {
|
2010-03-22 08:33:44 +01:00
|
|
|
return &{ $func->{subref} }(@_);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return undef;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub register {
|
|
|
|
my $self = shift;
|
|
|
|
my $subref;
|
|
|
|
|
2019-05-28 18:19:42 +02:00
|
|
|
if (@_) {
|
2010-03-22 08:33:44 +01:00
|
|
|
$subref = shift;
|
|
|
|
} else {
|
|
|
|
Carp::croak("Must pass subroutine reference to register()");
|
|
|
|
}
|
|
|
|
|
|
|
|
my $ref = { subref => $subref };
|
|
|
|
push @{ $self->{handlers} }, $ref;
|
|
|
|
|
|
|
|
return $ref;
|
|
|
|
}
|
|
|
|
|
|
|
|
sub unregister {
|
|
|
|
my $self = shift;
|
|
|
|
my $ref;
|
|
|
|
|
2019-05-28 18:19:42 +02:00
|
|
|
if (@_) {
|
2010-03-22 08:33:44 +01:00
|
|
|
$ref = shift;
|
|
|
|
} else {
|
|
|
|
Carp::croak("Must pass subroutine reference to unregister()");
|
|
|
|
}
|
|
|
|
|
|
|
|
@{ $self->{handlers} } = grep { $_ != $ref && $_->{subref} != $ref } @{ $self->{handlers} };
|
|
|
|
}
|
|
|
|
|
|
|
|
1;
|