Hook system improvements

+ Allow assigning multiple hook types to a class.
+ Add hook types, that are executed (almost) on every occasion.
This commit is contained in:
magmaus3 2022-11-20 13:21:45 +01:00
parent d4b2efe048
commit e66ed05ef7
Signed by: magmaus3
GPG key ID: 966755D3F4A9B251
2 changed files with 23 additions and 23 deletions

View file

@ -11,36 +11,35 @@ class HookMan:
def __new__(cls):
return reduce(lambda x, y: y(x), cls.hooks, super(HookMan, cls).__new__(cls))
def execute_hooks(self, hook_type, *args, **kwargs):
def execute_hooks(self, hook_type, isAdminAction=False, *args, **kwargs):
if hook_type not in self.hooks:
return
for hook in self.hooks[hook_type]:
print(f"Executing hook {hook.__name__}")
hook_type = None
if isAdminAction:
admin_hooks = self.hooks["admin*"]
else:
admin_hooks = []
for hook in \
(lambda: self.hooks[hook_type] if hook_type in self.hooks else [])() \
+ (lambda: self.hooks["*"] if "*" in self.hooks else [])() \
+ admin_hooks:
print(f"\tExecuting hook {hook.__name__}")
try:
hook()(*args, **kwargs)
hook()(hook_type=hook_type, isAdminAction=isAdminAction, *args, **kwargs)
except Exception as exc:
raise HookException(exc)
@classmethod
def add_hook(cls, func, *args, **kwargs):
"""Adds a hook."""
hook_type = func.hook_type
if hook_type in cls.hooks:
cls.hooks[hook_type] = cls.hooks[hook_type] + [func]
else:
cls.hooks[hook_type] = [func]
hook_types = func.hook_type
for hook_type in hook_types:
if hook_type in cls.hooks:
cls.hooks[hook_type] = cls.hooks[hook_type] + [func]
else:
cls.hooks[hook_type] = [func]
hook = HookMan()
# @hook.add_hook
# class example_hook:
# """Example hook."""
# hook_type = "player_login"
#
# def __call__(self, *args, **kwargs):
# print("Hook player_login,", kwargs)
#
#
hook.execute_hooks("player_login", hello="john")

View file

@ -11,8 +11,9 @@ hook = hook_system.hook
class Login:
# Different hook types are executed at different places.
# In this case, the hook is executed when a user logs in.
#
# Check the documentation for more hook types.
hook_type = "player_login"
hook_type = ["player_login"]
def __call__(self, *args, **kwargs):
def __call__(self, hook_type, *args, **kwargs):
print("LOGIN HOOK:", args, kwargs)