Files
kiri-core/HttpServer/Service/Abstracts/Server.php
T

98 lines
2.2 KiB
PHP
Raw Normal View History

2020-09-02 11:38:47 +08:00
<?php
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-09-02 11:38:47 +08:00
namespace HttpServer\Service\Abstracts;
use Exception;
use ReflectionException;
use Snowflake\Application;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
trait Server
{
/** @var Application */
public $application;
/**
* Server constructor.
* @param $host
* @param null $port
* @param null $mode
* @param null $sock_type
*/
public function __construct($host, $port = null, $mode = null, $sock_type = null)
{
2020-09-03 11:39:20 +08:00
$this->application = Snowflake::app();
2020-09-02 11:38:47 +08:00
parent::__construct($host, $port, $mode, $sock_type);
}
/**
* @param array $settings
* @return mixed|void
*/
public function set(array $settings)
{
parent::set($settings); // TODO: Change the autogenerated stub
$this->onInit();
}
/**
2020-12-17 14:09:14 +08:00
* @return mixed
2020-09-02 11:38:47 +08:00
* @throws NotFindClassException
* @throws ReflectionException
*/
2020-12-17 14:09:14 +08:00
public function onHandlerListener(): mixed
2020-09-02 11:38:47 +08:00
{
2020-10-14 11:13:26 +08:00
$this->on('WorkerStop', $this->createHandler('workerStop'));
$this->on('WorkerExit', $this->createHandler('workerExit'));
$this->on('WorkerStart', $this->createHandler('workerStart'));
$this->on('WorkerError', $this->createHandler('workerError'));
$this->on('ManagerStart', $this->createHandler('managerStart'));
$this->on('ManagerStop', $this->createHandler('managerStop'));
$this->on('PipeMessage', $this->createHandler('pipeMessage'));
$this->on('Shutdown', $this->createHandler('shutdown'));
$this->on('Start', $this->createHandler('start'));
2020-09-02 11:38:47 +08:00
$this->addTask();
}
/**
* @throws NotFindClassException
* @throws ReflectionException
*/
protected function addTask()
{
$settings = $this->setting;
if (($taskNumber = $settings['task_worker_num'] ?? 0) > 0) {
2020-10-14 11:13:26 +08:00
$this->on('Finish', $this->createHandler('finish'));
$this->on('Task', $this->createHandler('task'));
2020-09-02 11:38:47 +08:00
}
}
/**
* @param $eventName
* @return array
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
2020-12-17 14:09:14 +08:00
protected function createHandler($eventName): array
2020-09-02 11:38:47 +08:00
{
$classPrefix = 'HttpServer\Events\On' . ucfirst($eventName);
if (!class_exists($classPrefix)) {
throw new Exception('class not found.');
}
2020-09-03 11:39:20 +08:00
$class = Snowflake::createObject($classPrefix, [Snowflake::app()]);
2020-09-02 11:38:47 +08:00
return [$class, 'onHandler'];
}
}