Files
kiri-http-server/Tasker/AsyncTaskExecute.php
T

98 lines
1.9 KiB
PHP
Raw Normal View History

2021-11-30 14:32:56 +08:00
<?php
2021-11-30 14:34:15 +08:00
namespace Server\Tasker;
2021-11-30 14:32:56 +08:00
use Annotation\Inject;
use Exception;
2021-11-30 14:59:51 +08:00
use Kiri\Abstracts\BaseObject;
use Kiri\Core\HashMap;
2021-11-30 14:32:56 +08:00
use Kiri\Di\Container;
use Psr\Container\ContainerInterface;
2021-11-30 14:59:51 +08:00
use ReflectionException;
2021-11-30 14:32:56 +08:00
use Server\Contract\OnTaskInterface;
2021-11-30 14:34:15 +08:00
use Server\SwooleServerInterface;
2021-11-30 14:32:56 +08:00
2021-11-30 14:59:51 +08:00
/**
*
*/
class AsyncTaskExecute extends BaseObject
2021-11-30 14:32:56 +08:00
{
/**
* @var SwooleServerInterface
*/
#[Inject(SwooleServerInterface::class)]
public SwooleServerInterface $server;
/**
* @var Container
*/
#[Inject(ContainerInterface::class)]
public ContainerInterface $container;
2021-11-30 14:59:51 +08:00
private HashMap $hashMap;
/**
*
*/
public function init()
{
$this->hashMap = new HashMap();
}
/**
* @param string $key
* @param $handler
*/
public function reg(string $key, $handler)
{
$this->hashMap->put($key, $handler);
}
2021-11-30 14:32:56 +08:00
/**
* @param OnTaskInterface|string $handler
* @param array $params
* @param int|null $workerId
* @throws Exception
*/
public function execute(OnTaskInterface|string $handler, array $params = [], int $workerId = null)
{
if ($workerId === null || $workerId <= $this->server->setting['worker_num']) {
2021-11-30 14:43:55 +08:00
$workerId = random_int($this->server->setting['worker_num'] + 1, $this->server->setting['task_worker_num']);
2021-11-30 14:32:56 +08:00
}
if (is_string($handler)) {
$handler = $this->handle($handler, $params);
}
$this->server->task(serialize($handler), $workerId);
}
/**
* @param $handler
* @param $params
* @return object
2021-11-30 14:59:51 +08:00
* @throws ReflectionException
2021-11-30 14:32:56 +08:00
* @throws Exception
*/
private function handle($handler, $params): object
{
2021-11-30 14:59:51 +08:00
if (!class_exists($handler) && $this->hashMap->has($handler)) {
$handler = $this->hashMap->get($handler);
}
2021-11-30 14:32:56 +08:00
$implements = $this->container->getReflect($handler);
if (!in_array(OnTaskInterface::class, $implements->getInterfaceNames())) {
throw new Exception('Task must instance ' . OnTaskInterface::class);
}
return $implements->newInstanceArgs($params);
}
}