diff --git a/plugins/module_utils/opnsense_utils.py b/plugins/module_utils/opnsense_utils.py index 90dc1fc3..7c43e263 100644 --- a/plugins/module_utils/opnsense_utils.py +++ b/plugins/module_utils/opnsense_utils.py @@ -11,6 +11,32 @@ import subprocess +def _run_php_command(php_cmd: str) -> dict: + """ + Helper method to execute a PHP command and capture the output. + + Args: + php_cmd (str): The complete PHP command to execute. + + Returns: + dict: A dictionary containing stdout, stderr, and return code details. + """ + cmd_result = subprocess.run( + ["php", "-r", php_cmd], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, # do not raise exception if program fails + ) + + return { + "stdout": cmd_result.stdout.decode().strip(), + "stdout_lines": cmd_result.stdout.decode().strip().splitlines(), + "stderr": cmd_result.stderr.decode().strip(), + "stderr_lines": cmd_result.stderr.decode().strip().splitlines(), + "rc": cmd_result.returncode, + } + + def run_function( php_requirements: List[str], configure_function: str, configure_params: List = None ) -> dict: @@ -26,34 +52,32 @@ def run_function( and rc of the command """ if configure_params is None: - configure_params = [] + params_string = "" + else: + params_string = ",".join(configure_params) # assemble the php require statements - requirements_string = " ".join( - ["require '" + req + "';" for req in php_requirements] - ) - params_string = ",".join(configure_params) + requirements_string = " ".join([f"require '{req}';" for req in php_requirements]) # assemble php command php_cmd = f"{requirements_string} {configure_function}({params_string});" - # run command - cmd_result = subprocess.run( - [ - "php", - "-r", - php_cmd, - ], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - # do not raise exception if program fails - # handle subprocess process error in module using stderr - check=False, - ) - return { - "stdout": cmd_result.stdout.decode().strip(), - "stdout_lines": cmd_result.stdout.decode().strip().splitlines(), - "stderr": cmd_result.stderr.decode().strip(), - "stderr_lines": cmd_result.stderr.decode().strip().splitlines(), - "rc": cmd_result.returncode, - } + return _run_php_command(php_cmd) + + +def run_command(php_requirements: List[str], command: str) -> dict: + """ + Executes a PHP command with specified requirements, capturing the output. + + Args: + php_requirements (List[str]): PHP files to require before executing the command. + command (str): The PHP command to execute. + + Returns: + dict: A dictionary containing stdout, stderr, and return code details. + """ + + requirements_string = " ".join([f"require '{req}';" for req in php_requirements]) + php_cmd = f"{requirements_string} {command}" + + return _run_php_command(php_cmd)