Files
kiri-http-server/Server.php
T

103 lines
2.2 KiB
PHP
Raw Normal View History

2022-01-09 03:49:02 +08:00
<?php
2022-01-10 11:39:55 +08:00
namespace Kiri\Server;
2022-01-09 03:49:02 +08:00
use Exception;
2022-01-12 14:54:51 +08:00
use Kiri;
2022-01-09 03:49:02 +08:00
use Kiri\Events\EventDispatch;
2023-04-15 23:48:47 +08:00
use Kiri\Router\Router;
2022-01-12 11:20:33 +08:00
use Kiri\Server\Events\OnShutdown;
2023-07-20 15:02:06 +08:00
use Kiri\Server\Abstracts\AsyncServer;
2022-01-09 03:49:02 +08:00
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
defined('PID_PATH') or define('PID_PATH', APP_PATH . 'storage/server.pid');
2022-09-07 13:54:21 +08:00
2022-01-09 03:49:02 +08:00
/**
* Class Server
* @package Http
*/
2023-04-15 23:48:47 +08:00
class Server
2022-01-09 03:49:02 +08:00
{
2023-04-02 00:32:35 +08:00
2023-06-12 15:33:47 +08:00
/**
* @var int
*/
2023-06-12 15:34:08 +08:00
private int $daemon = 0;
/**
2023-07-31 23:08:58 +08:00
* @param AsyncServer $manager
* @param State $state
* @param EventDispatch $dispatch
* @param Router $router
2023-06-12 15:34:08 +08:00
*/
2023-07-31 23:08:58 +08:00
public function __construct(public AsyncServer $manager,
public State $state,
public EventDispatch $dispatch,
public Router $router)
2023-06-12 15:34:08 +08:00
{
}
/**
* @return void
* @throws Exception
*/
public function start(): void
{
2023-08-11 02:18:04 +08:00
if (\config('reload.hot', false) === true) {
$this->manager->addProcess(HotReload::class);
2023-07-06 16:00:02 +08:00
} else {
2023-08-11 02:18:04 +08:00
$this->router->scan_build_route();
2023-07-06 16:00:02 +08:00
}
2023-07-31 23:08:58 +08:00
$this->manager->initCoreServers(\config('server', []), $this->daemon);
$this->manager->start();
2023-07-06 16:00:02 +08:00
}
2023-06-12 15:34:08 +08:00
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function shutdown(): void
{
2023-07-06 16:00:02 +08:00
$configs = \config('server', []);
2023-07-31 23:08:58 +08:00
$instances = $this->manager->sortService($configs['ports'] ?? []);
2023-07-06 16:00:02 +08:00
foreach ($instances as $config) {
2023-07-31 23:08:58 +08:00
$this->state->exit($config->port);
2023-06-12 15:34:08 +08:00
}
2023-07-31 23:08:58 +08:00
$this->dispatch->dispatch(new OnShutdown());
2023-06-12 15:34:08 +08:00
}
/**
* @return bool
* @throws Exception
*/
public function isRunner(): bool
{
2023-07-31 23:08:58 +08:00
return $this->state->isRunner();
2023-06-12 15:34:08 +08:00
}
/**
* @param $daemon
* @return Server
*/
public function setDaemon($daemon): static
{
if (!in_array($daemon, [0, 1])) {
return $this;
}
$this->daemon = $daemon;
return $this;
}
2022-01-09 03:49:02 +08:00
}