AnP/Python/AnP/Managers/ControllersManager.py
2026-07-18 12:17:41 +02:00

73 lines
2.6 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Any, Self, TypeVar
from AnP.Interfaces.Application.AnPInterface import AnPInterface
from AnP.Abstracts.ControllerAbstract import ControllerAbstract
from AnP.Models.RequestModel import RequestModel
from AnP.Utils.Checks import Check
ControllerType = TypeVar("ControllerType", bound = ControllerAbstract)
class ControllersManager:
def __init__(self:Self, anp:AnPInterface) -> None:
self.anp:AnPInterface = anp
self.__controllers:dict[str, ControllerAbstract] = {}
self.update()
def update(self:Self) -> None:
key:str
for key in ("default_controllers_files", "controllers_files", "default_controllers", "controllers"):
self.add(self.anp.settings.get(key), True)
def reset(self:Self) -> None:
self.__controllers = {}
self.update()
def add(self:Self, inputs:Any|None, overwrite:bool = False) -> None:
subinputs:dict[str, Any|None]
for subinputs in self.anp.files.load_json(inputs, True):
key:str
controller:Any|None
for key, controller in subinputs.items():
if Check.is_mark_key(key) and controller is None:
continue
ControllerClass:type[ControllerAbstract]|None
if Check.is_string(controller):
ControllerClass = self.anp.models.get(ControllerAbstract, controller)
elif Check.is_class(controller, ControllerAbstract):
ControllerClass = controller
elif Check.is_dictionary(controller) and "type" in controller and Check.is_string(controller["type"]):
ControllerClass = self.anp.models.get(ControllerAbstract, controller["type"])
else:
continue
if ControllerClass and (
overwrite or key not in self.__controllers
):
self.__controllers[key] = ControllerClass(self.anp, (
controller if Check.is_dictionary(controller) else
None))
def execute(self:Self, key:str, method:str, *arguments:Any) -> Any|None:
if key in self.__controllers and hasattr(self.__controllers[key], method):
return getattr(self.__controllers[key], method)(*arguments)
return None
def get(self:Self, key:str, Type:type[ControllerType]) -> ControllerType|None:
if key in self.__controllers and isinstance(self.__controllers[key], Type):
return self.__controllers[key]
return None