2010-03-22 08:33:44 +01:00
|
|
|
# File: Registerable.pm
|
|
|
|
#
|
|
|
|
# Purpose: Provides functionality to register and execute one or more subroutines.
|
|
|
|
|
2023-02-21 06:31:52 +01:00
|
|
|
# SPDX-FileCopyrightText: 2010-2023 Pragmatic Software <pragma78@gmail.com>
|
2021-07-11 00:00:22 +02:00
|
|
|
# SPDX-License-Identifier: MIT
|
2017-03-05 22:33:31 +01:00
|
|
|
|
2021-07-21 07:44:51 +02:00
|
|
|
package PBot::Core::Registerable;
|
2010-03-22 08:33:44 +01:00
|
|
|
|
2021-06-19 06:23:34 +02:00
|
|
|
use PBot::Imports;
|
2019-07-11 03:40:53 +02:00
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub new($class, %args) {
|
2020-02-15 23:38:32 +01:00
|
|
|
my $self = bless {}, $class;
|
2021-06-19 06:23:34 +02:00
|
|
|
Carp::croak("Missing pbot reference to " . __FILE__) unless exists $args{pbot};
|
|
|
|
$self->{pbot} = delete $args{pbot};
|
|
|
|
$self->initialize(%args);
|
2020-02-15 23:38:32 +01:00
|
|
|
return $self;
|
2020-02-14 22:32:12 +01:00
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub initialize($self, %args) {
|
2020-02-15 23:38:32 +01:00
|
|
|
$self->{handlers} = [];
|
2010-03-22 08:33:44 +01:00
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub execute_all($self) {
|
2020-02-15 23:38:32 +01:00
|
|
|
foreach my $func (@{$self->{handlers}}) {
|
2021-08-06 21:59:21 +02:00
|
|
|
$func->{subref}->(@_);
|
2020-02-15 23:38:32 +01:00
|
|
|
}
|
2010-03-22 08:33:44 +01:00
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub execute($self, $ref) {
|
2020-02-15 23:38:32 +01:00
|
|
|
foreach my $func (@{$self->{handlers}}) {
|
2021-08-06 21:59:21 +02:00
|
|
|
if ($ref == $func || $ref == $func->{subref}) { return $func->{subref}->(@_); }
|
2010-03-22 08:33:44 +01:00
|
|
|
}
|
2020-02-15 23:38:32 +01:00
|
|
|
return undef;
|
2010-03-22 08:33:44 +01:00
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub register($self, $subref) {
|
2020-02-15 23:38:32 +01:00
|
|
|
my $ref = {subref => $subref};
|
|
|
|
push @{$self->{handlers}}, $ref;
|
|
|
|
return $ref;
|
2010-03-22 08:33:44 +01:00
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub register_front($self, $subref) {
|
2020-05-30 05:49:24 +02:00
|
|
|
my $ref = {subref => $subref};
|
|
|
|
unshift @{$self->{handlers}}, $ref;
|
|
|
|
return $ref;
|
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub unregister($self, $ref) {
|
2020-02-15 23:38:32 +01:00
|
|
|
@{$self->{handlers}} = grep { $_ != $ref } @{$self->{handlers}};
|
2010-03-22 08:33:44 +01:00
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub unregister_all($self) {
|
2020-02-15 23:38:32 +01:00
|
|
|
$self->{handlers} = [];
|
2020-02-15 16:26:29 +01:00
|
|
|
}
|
|
|
|
|
2010-03-22 08:33:44 +01:00
|
|
|
1;
|