<?php

namespace tw\async\tasks;

use ReflectionClass;

class AsyncClass extends Task
{
    public function getCmd(): string
    {
        return 'async_class';
    }

    protected function _exec(array $params)
    {
        $className = $params['class'] ?? '';
        $classArgs = $params['classArgs'] ?? [];
        $methodName = $params['method'] ?? '';
        $methodArgs = $params['methodArgs'] ?? [];

        $class = new ReflectionClass($className);
        $method = $class->getMethod($methodName);
        if ($method->isStatic()) {
            return $method->invokeArgs(null, $methodArgs);
        }
        $inst = $class->newInstanceArgs($classArgs);
        return $method->invokeArgs($inst, $methodArgs);
    }

    /**
     * 异步调用类
     * 
     * @param string $classname: 类名，包含完整命名空间
     * @param array $classArgs: 初始化类参数
     * @param string $methodName: 函数名称
     * @param array $methodArgs: 函数参数
     * @return bool
     */
    public static function push(string $className, array $classArgs, string $methodName, array $methodArgs)
    {
        $inst = new self();
        return $inst->put([
            'class' => $className,
            'classArgs' => $classArgs,
            'method' => $methodName,
            'methodArgs' => $methodArgs,
        ]);
    }
}
