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

117 lines
1.8 KiB
PHP
Raw Normal View History

2021-07-19 19:04:13 +08:00
<?php
namespace Server\Abstracts;
use Closure;
use Exception;
2021-07-26 02:55:55 +08:00
use Snowflake\Abstracts\Config;
2021-07-21 19:05:11 +08:00
use Snowflake\Event;
2021-07-26 02:55:55 +08:00
use Snowflake\Exception\ConfigException;
2021-07-19 19:04:13 +08:00
use Snowflake\Snowflake;
2021-08-03 14:06:47 +08:00
use Swoole\Server\Port;
2021-07-19 19:04:13 +08:00
/**
* Class Server
* @package Server\Abstracts
*/
abstract class Server
{
protected array $_events = [];
2021-07-21 19:05:11 +08:00
protected Event $_event;
2021-08-03 14:06:47 +08:00
abstract public function bindCallback(\Swoole\Server|Port $server, ?array $settings = []);
2021-07-26 02:55:55 +08:00
2021-08-02 17:31:24 +08:00
/**
* @param $prefix
* @throws ConfigException
*/
protected function setProcessName($prefix)
{
if (Snowflake::getPlatform()->isMac()) {
return;
}
$name = Config::get('id', 'system-service');
if (!empty($prefix)) {
$name .= '.' . $prefix;
}
swoole_set_process_name($name);
}
2021-07-26 02:55:55 +08:00
2021-07-21 19:05:11 +08:00
/**
* Server constructor.
* @throws Exception
*/
public function __construct()
{
$this->_event = Snowflake::getApp('event');
}
2021-07-19 19:04:13 +08:00
/**
* @param string $name
* @param array|null $events
* @throws Exception
*/
public function setEvents(string $name, ?array $events): void
{
if (is_array($events) && is_string($events[0])) {
2021-08-02 17:31:24 +08:00
$events[0] = Snowflake::getDi()->get($events[0]);
2021-07-19 19:04:13 +08:00
}
2021-07-21 14:11:20 +08:00
if (!is_callable($events)) {
return;
}
2021-07-19 19:04:13 +08:00
$this->_events[$name] = $events;
}
/**
* @return array
*/
public function getEvents(): array
{
return $this->_events;
}
/**
* @param string $name
* @return mixed
*/
public function getEvent(string $name): mixed
{
return $this->_events[$name] ?? null;
}
/**
* @param $name
* @param Closure|null $closure
* @param array $params
* @return mixed
*/
public function runEvent($name, ?Closure $closure, array $params): void
{
$event = $this->getEvent($name);
if (empty($event)) {
if (!is_callable($closure)) {
return;
}
call_user_func($closure, ...$params);
} else {
call_user_func($event, ...$params);
}
}
}