This commit is contained in:
2020-12-15 14:04:02 +08:00
parent c2d9250be9
commit a37df0ce7a
16 changed files with 225 additions and 162 deletions
+1 -2
View File
@@ -12,10 +12,9 @@ interface IAnnotation
/** /**
* @param array|Closure $handler * @param array|Closure $handler
* @param array $attributes
* @return mixed * @return mixed
*/ */
public function setHandler(array|Closure $handler, array $attributes): mixed; public function setHandler(array|Closure $handler): mixed;
} }
+5 -5
View File
@@ -4,6 +4,7 @@
namespace Annotation\Route; namespace Annotation\Route;
use Annotation\IAnnotation;
use Closure; use Closure;
use Exception; use Exception;
use HttpServer\Route\Node; use HttpServer\Route\Node;
@@ -17,7 +18,7 @@ use Snowflake\Snowflake;
* Class Socket * Class Socket
* @package Annotation * @package Annotation
*/ */
#[\Attribute(\Attribute::TARGET_METHOD)] class Socket #[\Attribute(\Attribute::TARGET_METHOD)] class Socket implements IAnnotation
{ {
const CLOSE = 'CLOSE'; const CLOSE = 'CLOSE';
@@ -38,7 +39,7 @@ use Snowflake\Snowflake;
*/ */
public function __construct( public function __construct(
public string $event, public string $event,
public ?string $uri, public ?string $uri = null,
public ?array $middleware = null, public ?array $middleware = null,
public ?array $interceptor = null, public ?array $interceptor = null,
public ?array $limits = null, public ?array $limits = null,
@@ -50,18 +51,17 @@ use Snowflake\Snowflake;
/** /**
* @param array|Closure $handler * @param array|Closure $handler
* @param array $attributes
* @return Node|null * @return Node|null
* @throws ComponentException * @throws ComponentException
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function setHandler(array|Closure $handler, array $attributes): ?Node public function setHandler(array|Closure $handler): ?Node
{ {
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
// TODO: Implement setHandler() method. // TODO: Implement setHandler() method.
$method = $this->event . '::' . ($this->uri ?? 'event'); $method = $this->event . '::' . (empty($this->uri) ? 'event' : $this->uri);
$node = $router->addRoute($method, $handler, 'sw::socket'); $node = $router->addRoute($method, $handler, 'sw::socket');
return $this->add($node); return $this->add($node);
+4 -6
View File
@@ -8,8 +8,6 @@ use Exception;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Abstracts\Input; use Snowflake\Abstracts\Input;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
/** /**
* Class AbstractConsole * Class AbstractConsole
@@ -46,7 +44,7 @@ abstract class AbstractConsole extends Component
* @param Input $input * @param Input $input
* @return $this * @return $this
*/ */
public function setParameters(Input $input) public function setParameters(Input $input): static
{ {
$this->parameters = $input; $this->parameters = $input;
return $this; return $this;
@@ -56,7 +54,7 @@ abstract class AbstractConsole extends Component
* @param Command $command * @param Command $command
* @return mixed * @return mixed
*/ */
public function execCommand(Command $command) public function execCommand(Command $command): mixed
{ {
return $command->onHandler($this->parameters); return $command->onHandler($this->parameters);
} }
@@ -64,7 +62,7 @@ abstract class AbstractConsole extends Component
/** /**
* @return Command|null * @return Command|null
*/ */
public function search() public function search(): ?Command
{ {
$name = $this->parameters->getCommandName(); $name = $this->parameters->getCommandName();
$this->parameters->set('commandList', $this->getCommandList()); $this->parameters->set('commandList', $this->getCommandList());
@@ -132,7 +130,7 @@ abstract class AbstractConsole extends Component
/** /**
* @return array * @return array
*/ */
private function getCommandList() private function getCommandList(): array
{ {
$_tmp = []; $_tmp = [];
foreach ($this->commands as $command) { foreach ($this->commands as $command) {
+2 -2
View File
@@ -19,7 +19,7 @@ abstract class Command extends BaseObject implements CommandInterface
* @return string * @return string
* 返回执行的命令名称 * 返回执行的命令名称
*/ */
public function getName() public function getName(): string
{ {
return $this->command; return $this->command;
} }
@@ -30,7 +30,7 @@ abstract class Command extends BaseObject implements CommandInterface
* *
* 返回命令描述 * 返回命令描述
*/ */
public function getDescription() public function getDescription(): string
{ {
return $this->description; return $this->description;
} }
+5 -1
View File
@@ -16,7 +16,11 @@ class DefaultCommand extends Command
public string $description = 'help'; public string $description = 'help';
public function onHandler(Input $dtl) /**
* @param Input $dtl
* @return string
*/
public function onHandler(Input $dtl): string
{ {
$param = $dtl->get('commandList'); $param = $dtl->get('commandList');
+12 -10
View File
@@ -6,14 +6,15 @@
* Time: 9:44 * Time: 9:44
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Database\Base; namespace Database\Base;
use ArrayIterator; use ArrayIterator;
use Database\ActiveQuery; use Database\ActiveQuery;
use Exception;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Database\ActiveRecord; use Database\ActiveRecord;
use Snowflake\Exception\NotFindClassException;
use Traversable; use Traversable;
/** /**
@@ -52,7 +53,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
/** /**
* @return int * @return int
*/ */
public function getLength() public function getLength(): int
{ {
return count($this->_item); return count($this->_item);
} }
@@ -84,10 +85,11 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
} }
/** /**
* @return ArrayIterator|Traversable * @return Traversable|CollectionIterator|ArrayIterator
* @throws Exception * @throws \ReflectionException
* @throws NotFindClassException
*/ */
public function getIterator() public function getIterator(): Traversable|CollectionIterator|ArrayIterator
{ {
return new CollectionIterator($this->model, $this->query, $this->_item); return new CollectionIterator($this->model, $this->query, $this->_item);
} }
@@ -96,16 +98,16 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
* @param mixed $offset * @param mixed $offset
* @return bool * @return bool
*/ */
public function offsetExists($offset) public function offsetExists(mixed $offset): bool
{ {
return !empty($this->_item) && isset($this->_item[$offset]); return !empty($this->_item) && isset($this->_item[$offset]);
} }
/** /**
* @param mixed $offset * @param mixed $offset
* @return mixed|null|ActiveRecord * @return ActiveRecord|null
*/ */
public function offsetGet($offset) public function offsetGet(mixed $offset): ?ActiveRecord
{ {
if (!$this->offsetExists($offset)) { if (!$this->offsetExists($offset)) {
return NULL; return NULL;
@@ -123,7 +125,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
* @param mixed $offset * @param mixed $offset
* @param mixed $value * @param mixed $value
*/ */
public function offsetSet($offset, $value) public function offsetSet(mixed $offset, mixed $value)
{ {
$this->_item[$offset] = $value; $this->_item[$offset] = $value;
} }
@@ -132,7 +134,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
/** /**
* @param mixed $offset * @param mixed $offset
*/ */
public function offsetUnset($offset) public function offsetUnset(mixed $offset)
{ {
if ($this->offsetExists($offset)) { if ($this->offsetExists($offset)) {
unset($this->_item[$offset]); unset($this->_item[$offset]);
+6 -3
View File
@@ -6,6 +6,7 @@ namespace Database\Base;
use Database\ActiveQuery; use Database\ActiveQuery;
use Database\ActiveRecord; use Database\ActiveRecord;
use Exception;
use ReflectionException; use ReflectionException;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -48,8 +49,9 @@ class CollectionIterator extends \ArrayIterator
/** /**
* @param $current * @param $current
* @return ActiveRecord * @return ActiveRecord
* @throws Exception
*/ */
protected function newModel($current) protected function newModel($current): ActiveRecord
{ {
return (clone $this->model)->setAttributes($current); return (clone $this->model)->setAttributes($current);
@@ -57,9 +59,10 @@ class CollectionIterator extends \ArrayIterator
/** /**
* @return ActiveRecord|mixed * @return mixed
* @throws Exception
*/ */
public function current() public function current(): mixed
{ {
$current = parent::current(); $current = parent::current();
if (!($current instanceof ActiveRecord)) { if (!($current instanceof ActiveRecord)) {
+2 -8
View File
@@ -10,6 +10,7 @@ namespace Database;
use Database\Base\AbstractCollection; use Database\Base\AbstractCollection;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure;
/** /**
* Class Collection * Class Collection
@@ -18,18 +19,11 @@ use Exception;
*/ */
class Collection extends AbstractCollection class Collection extends AbstractCollection
{ {
/**
* @return int
*/
public function getLength()
{
return count($this->_item);
}
/** /**
* @return array * @return array
*/ */
public function getItems() public function getItems(): array
{ {
// TODO: Change the autogenerated stub // TODO: Change the autogenerated stub
return $this->_item; return $this->_item;
+16 -7
View File
@@ -4,11 +4,13 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Annotation\Route\Socket;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Route\Annotation\Http; use HttpServer\Route\Annotation\Http;
use HttpServer\Route\Annotation\Tcp; use HttpServer\Route\Annotation\Tcp;
use HttpServer\Route\Annotation\Websocket; use HttpServer\Route\Annotation\Websocket;
use HttpServer\Route\Annotation\Websocket as AWebsocket; use HttpServer\Route\Annotation\Websocket as AWebsocket;
use HttpServer\Route\Node;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -47,14 +49,17 @@ class OnClose extends Callback
* @throws ComponentException * @throws ComponentException
* @throws Exception * @throws Exception
*/ */
private function execute(Server $server, int $fd) private function execute(Server $server, int $fd): void
{ {
try { try {
[$manager, $name] = $this->resolve($server, $fd); $router = Snowflake::app()->getRouter();
if (empty($manager) || !$manager->has($name)) { if (!($server instanceof WServer) || !$server->isEstablished($fd)) {
return; return;
} }
$manager->runWith($name, [$fd]); $node = $router->search(Socket::CLOSE . '::event', 'sw:socket');
if ($node instanceof Node) {
$node->dispatch();
}
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$this->addError($exception); $this->addError($exception);
} finally { } finally {
@@ -70,14 +75,18 @@ class OnClose extends Callback
* @return array|null * @return array|null
* @throws Exception * @throws Exception
*/ */
public function resolve($server, $fd) public function resolve($server, $fd): ?array
{ {
if ($server instanceof WServer) { if ($server instanceof WServer) {
if (!$server->isEstablished($fd)) { if (!$server->isEstablished($fd)) {
return [null, null]; return [null, null];
} }
$manager = Snowflake::app()->annotation->websocket; $router = Snowflake::app()->getRouter();
$name = $manager->getName(AWebsocket::CLOSE); $node = $router->search(Socket::HANDSHAKE . '::' . null, 'sw:socket');
if ($node === null) {
return [null, null];
}
return $node->dispatch();
} else if ($server instanceof HServer) { } else if ($server instanceof HServer) {
$manager = Snowflake::app()->annotation->http; $manager = Snowflake::app()->annotation->http;
$name = $manager->getName(Http::CLOSE); $name = $manager->getName(Http::CLOSE);
+9 -7
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Annotation\Route\Socket;
use Exception; use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Route\Annotation\Websocket as AWebsocket; use HttpServer\Route\Annotation\Websocket as AWebsocket;
@@ -87,20 +88,21 @@ class OnHandshake extends Callback
/** /**
* @param SRequest $request * @param SRequest $request
* @param SResponse $response * @param SResponse $response
* @return mixed|bool|null * @return mixed
* @throws ComponentException * @throws ComponentException
* @throws Exception
*/ */
private function execute(SRequest $request, SResponse $response) private function execute(SRequest $request, SResponse $response): mixed
{ {
try { try {
$this->resolveParse($request, $response); $this->resolveParse($request, $response);
$manager = Snowflake::app()->annotation->websocket; $router = Snowflake::app()->getRouter();
$name = $manager->getName(AWebsocket::HANDSHAKE); $node = $router->search(Socket::HANDSHAKE . '::event', 'sw:socket');
if (!$manager->has($name)) { if ($node === null) {
return $this->disconnect($response); return $this->disconnect($response, 502);
} }
return $manager->runWith($name, [$request, $response]); return $node->dispatch();
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$this->addError($exception->getMessage()); $this->addError($exception->getMessage());
return $this->disconnect($response, 500); return $this->disconnect($response, 500);
+18 -23
View File
@@ -4,8 +4,10 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Annotation\Route\Socket;
use Exception; use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Http\Request;
use HttpServer\Route\Annotation\Websocket as AWebsocket; use HttpServer\Route\Annotation\Websocket as AWebsocket;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -28,16 +30,14 @@ class OnMessage extends Callback
public function onHandler(Server $server, Frame $frame) public function onHandler(Server $server, Frame $frame)
{ {
try { try {
if ($frame->opcode == 0x08) { if ($frame->opcode != 0x08) {
return; $event = Snowflake::app()->getEvent();
Coroutine::defer(function () use ($event) {
$event->trigger(Event::EVENT_AFTER_REQUEST);
});
$content = $this->resolve($event, $frame, $server);
$server->send($frame->fd, $content);
} }
$event = Snowflake::app()->getEvent();
Coroutine::defer(function () use ($event) {
$event->trigger(Event::EVENT_AFTER_REQUEST);
});
$this->resolve($event, $frame, $server);
$manager = Snowflake::app()->getAnnotation()->websocket;
$manager->runWith($this->name($manager, $frame), [$frame, $server]);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$this->addError($exception->getMessage(), 'websocket'); $this->addError($exception->getMessage(), 'websocket');
$server->send($frame->fd, $exception->getMessage()); $server->send($frame->fd, $exception->getMessage());
@@ -50,30 +50,25 @@ class OnMessage extends Callback
* @param $event * @param $event
* @param $frame * @param $frame
* @param $server * @param $server
* @return mixed
* @throws Exception * @throws Exception
*/ */
private function resolve($event, $frame, $server) private function resolve($event, $frame, $server): mixed
{ {
if ($event->exists(Event::SERVER_MESSAGE)) { if ($event->exists(Event::SERVER_MESSAGE)) {
$event->trigger(Event::SERVER_MESSAGE, [$server, $frame]); $event->trigger(Event::SERVER_MESSAGE, [$server, $frame]);
} else { } else {
$frame->data = json_decode($frame->data, true); $frame->data = json_decode($frame->data, true);
} }
if (!isset($frame->data['route'])) { if (empty($route = $frame->data['route'] ?? null)) {
throw new Exception('Format error.'); throw new Exception('Format error.');
} }
$router = Snowflake::app()->getRouter();
$node = $router->search(Socket::MESSAGE . '::' . $route, 'sw:socket');
if ($node === null) {
throw new Exception('Page not found.');
}
return $node->dispatch();
} }
/**
* @param $manager
* @param $frame
* @return mixed
*/
private function name($manager, $frame)
{
return $manager->getName(AWebsocket::MESSAGE, [null, null, $frame->data['route']]);
}
} }
+4 -3
View File
@@ -29,10 +29,11 @@ class OnWorkerStart extends Callback
* @param Server $server * @param Server $server
* @param int $worker_id * @param int $worker_id
* *
* @return mixed|void * @return mixed
* @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function onHandler(Server $server, int $worker_id) public function onHandler(Server $server, int $worker_id): void
{ {
$get_name = $this->get_process_name($server, $worker_id); $get_name = $this->get_process_name($server, $worker_id);
if (!empty($get_name) && !Snowflake::isMac()) { if (!empty($get_name) && !Snowflake::isMac()) {
@@ -66,7 +67,7 @@ class OnWorkerStart extends Callback
* @return string * @return string
* @throws ConfigException * @throws ConfigException
*/ */
private function get_process_name($socket, $worker_id) private function get_process_name($socket, $worker_id): string
{ {
$prefix = rtrim(Config::get('id',false, 'system:'), ':'); $prefix = rtrim(Config::get('id',false, 'system:'), ':');
if ($worker_id >= $socket->setting['worker_num']) { if ($worker_id >= $socket->setting['worker_num']) {
+26 -9
View File
@@ -76,10 +76,10 @@ class Router extends Application implements RouterInterface
* @param $path * @param $path
* @param $handler * @param $handler
* @param string $method * @param string $method
* @return mixed|Node|null * @return ?Node
* @throws * @throws ConfigException
*/ */
public function addRoute($path, $handler, $method = 'any') public function addRoute($path, $handler, $method = 'any'): ?Node
{ {
$method = strtolower($method); $method = strtolower($method);
if (!isset($this->nodes[$method])) { if (!isset($this->nodes[$method])) {
@@ -99,9 +99,9 @@ class Router extends Application implements RouterInterface
* @param $path * @param $path
* @param $handler * @param $handler
* @param string $method * @param string $method
* @return mixed * @return ?Node
*/ */
private function hash($path, $handler, $method = 'any') private function hash($path, $handler, $method = 'any'): ?Node
{ {
$path = $this->resolve($path); $path = $this->resolve($path);
@@ -278,7 +278,7 @@ class Router extends Application implements RouterInterface
* @return Node * @return Node
* @throws * @throws
*/ */
public function NodeInstance($value, $index = 0, $method = 'get') public function NodeInstance($value, $index = 0, $method = 'get'): Node
{ {
$node = new Node(); $node = new Node();
$node->childes = []; $node->childes = [];
@@ -301,7 +301,7 @@ class Router extends Application implements RouterInterface
* @param $method * @param $method
* @return array * @return array
*/ */
private function loadNamespace($method) private function loadNamespace($method): array
{ {
$name = array_column($this->groupTacks, 'namespace'); $name = array_column($this->groupTacks, 'namespace');
if ($method == 'package' || $method == 'receive') { if ($method == 'package' || $method == 'receive') {
@@ -333,7 +333,7 @@ class Router extends Application implements RouterInterface
/** /**
* @return string * @return string
*/ */
public function addPrefix() public function addPrefix(): string
{ {
$prefix = array_column($this->groupTacks, 'prefix'); $prefix = array_column($this->groupTacks, 'prefix');
@@ -352,7 +352,7 @@ class Router extends Application implements RouterInterface
* @return Node|null * @return Node|null
* 查找指定路由 * 查找指定路由
*/ */
public function tree_search(?array $explode, $method) public function tree_search(?array $explode, $method): ?Node
{ {
if (empty($explode)) { if (empty($explode)) {
return $this->nodes[$method]['/'] ?? null; return $this->nodes[$method]['/'] ?? null;
@@ -523,7 +523,24 @@ class Router extends Application implements RouterInterface
return null; return null;
} }
return $methods['/']; return $methods['/'];
}
/**
* @param $uri
* @param $method
* @return Node|null
*/
public function search($uri, $method): Node|null
{
if (!isset($this->nodes[$method])) {
return null;
}
$methods = $this->nodes[$method];
if (isset($methods[$uri])) {
return $methods[$uri];
}
return $methods['/'] ?? null;
} }
+49 -22
View File
@@ -3,6 +3,7 @@
namespace HttpServer; namespace HttpServer;
use Annotation\IAnnotation;
use HttpServer\Events\OnClose; use HttpServer\Events\OnClose;
use HttpServer\Events\OnConnect; use HttpServer\Events\OnConnect;
use HttpServer\Events\OnPacket; use HttpServer\Events\OnPacket;
@@ -57,7 +58,7 @@ class Server extends Application
/** @var Http|Websocket|Packet|Receive */ /** @var Http|Websocket|Packet|Receive */
private $baseServer; private Packet|Websocket|Receive|Http $baseServer;
public int $daemon = 0; public int $daemon = 0;
@@ -83,7 +84,7 @@ class Server extends Application
* @return Http|Packet|Receive|Websocket * @return Http|Packet|Receive|Websocket
* @throws Exception * @throws Exception
*/ */
public function initCore(array $configs) public function initCore(array $configs): Packet|Websocket|Receive|Http
{ {
$this->enableCoroutine((bool)Config::get('settings.enable_coroutine')); $this->enableCoroutine((bool)Config::get('settings.enable_coroutine'));
@@ -95,10 +96,10 @@ class Server extends Application
/** /**
* @param $configs * @param $configs
* @return null * @return Packet|Websocket|Receive|Http|null
* @throws Exception * @throws Exception
*/ */
private function orders($configs) private function orders($configs): Packet|Websocket|Receive|Http|null
{ {
$servers = $this->sortServers($configs); $servers = $this->sortServers($configs);
foreach ($servers as $server) { foreach ($servers as $server) {
@@ -133,14 +134,16 @@ class Server extends Application
/** /**
* @param $host * @param $host
* @param $Port * @param $Port
* @return Http|Packet|Receive|Websocket
* @throws Exception * @throws Exception
*/ */
public function error_stop($host, $Port) public function error_stop($host, $Port): Packet|Websocket|Receive|Http
{ {
$this->error(sprintf('Port %s::%d is already.', $host, $Port)); $this->error(sprintf('Port %s::%d is already.', $host, $Port));
if ($this->baseServer) { if ($this->baseServer) {
$this->baseServer->shutdown(); $this->baseServer->shutdown();
} }
return $this->baseServer;
} }
@@ -148,7 +151,7 @@ class Server extends Application
* @return bool * @return bool
* @throws ConfigException * @throws ConfigException
*/ */
public function isRunner() public function isRunner(): bool
{ {
$port = $this->sortServers(Config::get('servers')); $port = $this->sortServers(Config::get('servers'));
if (empty($port)) { if (empty($port)) {
@@ -200,16 +203,17 @@ class Server extends Application
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function onProcessListener() public function onProcessListener(): void
{ {
if (!($this->baseServer instanceof \Swoole\Server)) { if (!($this->baseServer instanceof \Swoole\Server)) {
return false; return;
} }
$processes = Config::get('processes'); $processes = Config::get('processes');
if (!empty($processes) && is_array($processes)) { if (!empty($processes) && is_array($processes)) {
return $this->deliveryProcess(merge($processes, $this->process)); $this->deliveryProcess(merge($processes, $this->process));
} else {
$this->deliveryProcess($this->process);
} }
return $this->deliveryProcess($this->process);
} }
@@ -243,7 +247,7 @@ class Server extends Application
* @param $daemon * @param $daemon
* @return Server * @return Server
*/ */
public function setDaemon($daemon) public function setDaemon($daemon): static
{ {
if (!in_array($daemon, [0, 1])) { if (!in_array($daemon, [0, 1])) {
return $this; return $this;
@@ -256,7 +260,7 @@ class Server extends Application
/** /**
* @return Http|Websocket|Packet|Receive * @return Http|Websocket|Packet|Receive
*/ */
public function getServer() public function getServer(): Packet|Websocket|Receive|Http
{ {
return $this->baseServer; return $this->baseServer;
} }
@@ -267,7 +271,7 @@ class Server extends Application
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function create($config) private function create($config): mixed
{ {
$settings = Config::get('settings', false, []); $settings = Config::get('settings', false, []);
if (!isset($this->server[$config['type']])) { if (!isset($this->server[$config['type']])) {
@@ -299,10 +303,10 @@ class Server extends Application
/** /**
* @param $config * @param $config
* @param $settings * @param $settings
* @return mixed * @return \Swoole\Server|Packet|Receive|Http|Websocket
* @throws Exception * @throws Exception
*/ */
private function dispatchCreate($config, $settings) private function dispatchCreate($config, $settings): \Swoole\Server|Packet|Receive|Http|Websocket
{ {
if (!($this->baseServer instanceof \Swoole\Server)) { if (!($this->baseServer instanceof \Swoole\Server)) {
$this->parseServer($config, $settings); $this->parseServer($config, $settings);
@@ -323,10 +327,10 @@ class Server extends Application
/** /**
* @param $config * @param $config
* @param $settings * @param $settings
* @return void * @return Packet|Websocket|Receive|Http
* @throws Exception * @throws Exception
*/ */
private function parseServer($config, $settings) private function parseServer($config, $settings): Packet|Websocket|Receive|Http
{ {
$class = $this->dispatch($config['type']); $class = $this->dispatch($config['type']);
if ($this->isUse($config['port'])) { if ($this->isUse($config['port'])) {
@@ -342,7 +346,7 @@ class Server extends Application
} else if ($this->baseServer instanceof Http) { } else if ($this->baseServer instanceof Http) {
$this->onLoadHttpHandler(); $this->onLoadHttpHandler();
} }
$this->baseServer->set($settings); return $this->baseServer->set($settings);
} }
@@ -427,6 +431,19 @@ class Server extends Application
$event->on(Event::SERVER_WORKER_START, function () { $event->on(Event::SERVER_WORKER_START, function () {
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
$router->loadRouterSetting(); $router->loadRouterSetting();
$attributes = Snowflake::app()->getAttributes();
$attributes->readControllers(CONTROLLER_PATH, 'controllers');
$aliases = $attributes->getAlias('controllers');
foreach ($aliases as $alias) {
$handler = $alias['handler'];
foreach ($alias['attributes'] as $key => $attribute) {
if ($attribute instanceof IAnnotation) {
$attribute->setHandler($handler);
}
}
}
}); });
} }
@@ -438,8 +455,18 @@ class Server extends Application
{ {
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
$event->on(Event::SERVER_WORKER_START, function () { $event->on(Event::SERVER_WORKER_START, function () {
$websocket = Snowflake::app()->annotation->websocket; $attributes = Snowflake::app()->getAttributes();
$websocket->registration_notes(APP_PATH . 'app/Websocket', 'App\\Websocket'); $attributes->readControllers(SOCKET_PATH, 'sockets');
$aliases = $attributes->getAlias('sockets');
foreach ($aliases as $alias) {
$handler = $alias['handler'];
foreach ($alias['attributes'] as $key => $attribute) {
if ($attribute instanceof IAnnotation) {
$attribute->setHandler($handler);
}
}
}
}); });
} }
@@ -448,7 +475,7 @@ class Server extends Application
* @param $type * @param $type
* @return string * @return string
*/ */
private function dispatch($type) private function dispatch($type): string
{ {
$default = [ $default = [
self::HTTP => Http::class, self::HTTP => Http::class,
@@ -463,7 +490,7 @@ class Server extends Application
* @param $servers * @param $servers
* @return array * @return array
*/ */
private function sortServers($servers) private function sortServers($servers): array
{ {
$array = []; $array = [];
foreach ($servers as $server) { foreach ($servers as $server) {
+40 -30
View File
@@ -11,17 +11,15 @@ namespace Snowflake\Abstracts;
use Exception; use Exception;
use HttpServer\Client\Client;
use HttpServer\Client\HttpClient;
use HttpServer\Client\Curl;
use HttpServer\Client\Http2; use HttpServer\Client\Http2;
use HttpServer\Client\IClient;
use HttpServer\Http\Request; use HttpServer\Http\Request;
use HttpServer\Http\Response; use HttpServer\Http\Response;
use HttpServer\Route\Router; use HttpServer\Route\Router;
use HttpServer\Server; use HttpServer\Server;
use JetBrains\PhpStorm\Pure;
use Kafka\Producer; use Kafka\Producer;
use Snowflake\Annotation\Annotation; use Snowflake\Annotation\Annotation;
use Annotation\Annotation as SAnnotation;
use Snowflake\Cache\Memcached; use Snowflake\Cache\Memcached;
use Snowflake\Cache\Redis; use Snowflake\Cache\Redis;
use Snowflake\Di\Service; use Snowflake\Di\Service;
@@ -51,6 +49,7 @@ use Database\DatabasesProviders;
* @property Memcached $memcached * @property Memcached $memcached
* @property Logger $logger * @property Logger $logger
* @property Jwt $jwt * @property Jwt $jwt
* @property SAnnotation $attributes
* @property Http2 $http2 * @property Http2 $http2
* @property BaseGoto $goto * @property BaseGoto $goto
* @property Producer $kafka * @property Producer $kafka
@@ -82,14 +81,14 @@ abstract class BaseApplication extends Service
$this->initErrorHandler(); $this->initErrorHandler();
$this->enableEnvConfig(); $this->enableEnvConfig();
Component::__construct($config); parent::__construct($config);
} }
/** /**
* @return mixed * @return array
*/ */
public function enableEnvConfig() public function enableEnvConfig(): array
{ {
if (!file_exists($this->envPath)) { if (!file_exists($this->envPath)) {
return []; return [];
@@ -112,7 +111,7 @@ abstract class BaseApplication extends Service
* *
* @return array * @return array
*/ */
protected function readLinesFromFile(string $filePath) protected function readLinesFromFile(string $filePath): array
{ {
// Read file into an array of lines with auto-detected line endings // Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings'); $autodetect = ini_get('auto_detect_line_endings');
@@ -130,7 +129,7 @@ abstract class BaseApplication extends Service
* *
* @return bool * @return bool
*/ */
protected function isComment(string $line) protected function isComment(string $line): bool
{ {
$line = ltrim($line); $line = ltrim($line);
@@ -144,9 +143,9 @@ abstract class BaseApplication extends Service
* *
* @return bool * @return bool
*/ */
protected function looksLikeSetter(string $line) #[Pure] protected function looksLikeSetter(string $line): bool
{ {
return strpos($line, '=') !== false; return str_contains($line, '=');
} }
@@ -161,7 +160,7 @@ abstract class BaseApplication extends Service
Config::set($key, $value); Config::set($key, $value);
} }
if ($storage = Config::get('storage', false, 'storage')) { if ($storage = Config::get('storage', false, 'storage')) {
if (strpos($storage, APP_PATH) === false) { if (!str_contains($storage, APP_PATH)) {
$storage = APP_PATH . $storage . '/'; $storage = APP_PATH . $storage . '/';
} }
if (!is_dir($storage)) { if (!is_dir($storage)) {
@@ -204,7 +203,7 @@ abstract class BaseApplication extends Service
* @return mixed * @return mixed
* @throws ComponentException * @throws ComponentException
*/ */
public function clone($name) public function clone($name): mixed
{ {
return clone $this->get($name); return clone $this->get($name);
} }
@@ -221,7 +220,7 @@ abstract class BaseApplication extends Service
/** /**
* @return mixed * @return mixed
*/ */
public function getLocalIps() public function getLocalIps(): mixed
{ {
return swoole_get_local_ip(); return swoole_get_local_ip();
} }
@@ -229,7 +228,7 @@ abstract class BaseApplication extends Service
/** /**
* @return mixed * @return mixed
*/ */
public function getFirstLocal() public function getFirstLocal(): mixed
{ {
return current($this->getLocalIps()); return current($this->getLocalIps());
} }
@@ -249,7 +248,7 @@ abstract class BaseApplication extends Service
* @return Producer * @return Producer
* @throws ComponentException * @throws ComponentException
*/ */
public function getKafka() public function getKafka(): Producer
{ {
return $this->get('kafka'); return $this->get('kafka');
} }
@@ -259,7 +258,7 @@ abstract class BaseApplication extends Service
* @return \Redis|Redis * @return \Redis|Redis
* @throws ComponentException * @throws ComponentException
*/ */
public function getRedis() public function getRedis(): Redis|\Redis
{ {
return $this->get('redis'); return $this->get('redis');
} }
@@ -268,7 +267,7 @@ abstract class BaseApplication extends Service
* @param $ip * @param $ip
* @return bool * @return bool
*/ */
public function isLocal($ip) public function isLocal($ip): bool
{ {
return $this->getFirstLocal() == $ip; return $this->getFirstLocal() == $ip;
} }
@@ -278,7 +277,7 @@ abstract class BaseApplication extends Service
* @return ErrorHandler * @return ErrorHandler
* @throws ComponentException * @throws ComponentException
*/ */
public function getError() public function getError(): ErrorHandler
{ {
return $this->get('error'); return $this->get('error');
} }
@@ -288,7 +287,7 @@ abstract class BaseApplication extends Service
* @return Annotation * @return Annotation
* @throws ComponentException * @throws ComponentException
*/ */
public function getAnnotation() public function getAnnotation(): Annotation
{ {
return $this->get('annotation'); return $this->get('annotation');
} }
@@ -298,7 +297,7 @@ abstract class BaseApplication extends Service
* @return Connection * @return Connection
* @throws ComponentException * @throws ComponentException
*/ */
public function getConnections() public function getConnections(): Connection
{ {
return $this->get('connections'); return $this->get('connections');
} }
@@ -308,7 +307,7 @@ abstract class BaseApplication extends Service
* @return Pool * @return Pool
* @throws ComponentException * @throws ComponentException
*/ */
public function getPool() public function getPool(): Pool
{ {
return $this->get('pool'); return $this->get('pool');
} }
@@ -317,7 +316,7 @@ abstract class BaseApplication extends Service
* @return Response * @return Response
* @throws ComponentException * @throws ComponentException
*/ */
public function getResponse() public function getResponse(): Response
{ {
return $this->get('response'); return $this->get('response');
} }
@@ -326,7 +325,7 @@ abstract class BaseApplication extends Service
* @return Request * @return Request
* @throws ComponentException * @throws ComponentException
*/ */
public function getRequest() public function getRequest(): Request
{ {
return $this->get('request'); return $this->get('request');
} }
@@ -336,7 +335,7 @@ abstract class BaseApplication extends Service
* @return Config * @return Config
* @throws ComponentException * @throws ComponentException
*/ */
public function getConfig() public function getConfig(): Config
{ {
return $this->get('config'); return $this->get('config');
} }
@@ -346,7 +345,7 @@ abstract class BaseApplication extends Service
* @return Router * @return Router
* @throws ComponentException * @throws ComponentException
*/ */
public function getRouter() public function getRouter(): Router
{ {
return $this->get('router'); return $this->get('router');
} }
@@ -356,7 +355,7 @@ abstract class BaseApplication extends Service
* @return Event * @return Event
* @throws ComponentException * @throws ComponentException
*/ */
public function getEvent() public function getEvent(): Event
{ {
return $this->get('event'); return $this->get('event');
} }
@@ -366,18 +365,28 @@ abstract class BaseApplication extends Service
* @return Jwt * @return Jwt
* @throws ComponentException * @throws ComponentException
*/ */
public function getJwt() public function getJwt(): Jwt
{ {
return $this->get('jwt'); return $this->get('jwt');
} }
/**
* @return SAnnotation
* @throws ComponentException
*/
public function getAttributes(): SAnnotation
{
return $this->get('attributes');
}
/** /**
* @throws Exception * @throws Exception
*/ */
protected function moreComponents() protected function moreComponents(): void
{ {
return $this->setComponents([ $this->setComponents([
'error' => ['class' => ErrorHandler::class], 'error' => ['class' => ErrorHandler::class],
'event' => ['class' => Event::class], 'event' => ['class' => Event::class],
'annotation' => ['class' => Annotation::class], 'annotation' => ['class' => Annotation::class],
@@ -388,6 +397,7 @@ abstract class BaseApplication extends Service
'request' => ['class' => Request::class], 'request' => ['class' => Request::class],
'config' => ['class' => Config::class], 'config' => ['class' => Config::class],
'logger' => ['class' => Logger::class], 'logger' => ['class' => Logger::class],
'attributes' => ['class' => SAnnotation::class],
'router' => ['class' => Router::class], 'router' => ['class' => Router::class],
'redis' => ['class' => Redis::class], 'redis' => ['class' => Redis::class],
'jwt' => ['class' => Jwt::class], 'jwt' => ['class' => Jwt::class],
+26 -24
View File
@@ -7,6 +7,7 @@ namespace Snowflake;
use Exception; use Exception;
use HttpServer\IInterface\Task; use HttpServer\IInterface\Task;
use JetBrains\PhpStorm\Pure;
use ReflectionException; use ReflectionException;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Core\JSON; use Snowflake\Core\JSON;
@@ -21,6 +22,8 @@ use Swoole\WebSocket\Server;
defined('DB_ERROR_BUSY') or define('DB_ERROR', 'The database is busy. Please try again later.'); defined('DB_ERROR_BUSY') or define('DB_ERROR', 'The database is busy. Please try again later.');
defined('SELECT_IS_NULL') or define('SELECT_IS_NULL', 'Query data does not exist, please check the relevant conditions.'); defined('SELECT_IS_NULL') or define('SELECT_IS_NULL', 'Query data does not exist, please check the relevant conditions.');
defined('PARAMS_IS_NULL') or define('PARAMS_IS_NULL', 'Required items cannot be empty, please add.'); defined('PARAMS_IS_NULL') or define('PARAMS_IS_NULL', 'Required items cannot be empty, please add.');
defined('CONTROLLER_PATH') or define('CONTROLLER_PATH', APP_PATH . 'app/Http/Controllers/');
defined('SOCKET_PATH') or define('SOCKET_PATH', APP_PATH . 'app/Websocket/');
class Snowflake class Snowflake
{ {
@@ -46,16 +49,16 @@ class Snowflake
/** /**
* @return mixed * @return mixed
*/ */
public static function app() public static function app(): Application
{ {
return static::$service; return static::$service;
} }
/** /**
* @param $name * @param $name
* @return mixed * @return bool
*/ */
public static function has($name) public static function has($name): bool
{ {
return static::$service->has($name); return static::$service->has($name);
} }
@@ -67,7 +70,7 @@ class Snowflake
*/ */
public static function setAlias($className, $id) public static function setAlias($className, $id)
{ {
return static::$service->setAlias($className, $id); static::$service->setAlias($className, $id);
} }
@@ -79,7 +82,7 @@ class Snowflake
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
public static function createObject($className, $construct = []) public static function createObject($className, $construct = []): mixed
{ {
if (is_string($className)) { if (is_string($className)) {
return static::$container->get($className, $construct); return static::$container->get($className, $construct);
@@ -101,7 +104,7 @@ class Snowflake
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public static function getStoragePath() public static function getStoragePath(): string
{ {
$default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR; $default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR;
$path = Config::get('storage', false, $default); $path = Config::get('storage', false, $default);
@@ -115,7 +118,7 @@ class Snowflake
/** /**
* @return bool * @return bool
*/ */
public static function inCoroutine() public static function inCoroutine(): bool
{ {
return Coroutine::getCid() > 0; return Coroutine::getCid() > 0;
} }
@@ -124,7 +127,7 @@ class Snowflake
/** /**
* @return Container * @return Container
*/ */
public static function getDi() public static function getDi(): Container
{ {
return static::$container; return static::$container;
} }
@@ -135,7 +138,7 @@ class Snowflake
* @return false|int|mixed * @return false|int|mixed
* @throws Exception * @throws Exception
*/ */
public static function setProcessId($workerId) public static function setProcessId($workerId): mixed
{ {
return self::writeFile(storage('socket.sock'), $workerId); return self::writeFile(storage('socket.sock'), $workerId);
} }
@@ -146,7 +149,7 @@ class Snowflake
* @return false|int|mixed * @return false|int|mixed
* @throws Exception * @throws Exception
*/ */
public static function setWorkerId($workerId) public static function setWorkerId($workerId): mixed
{ {
if (empty($workerId)) { if (empty($workerId)) {
return $workerId; return $workerId;
@@ -171,9 +174,9 @@ class Snowflake
* @param $fileName * @param $fileName
* @param $content * @param $content
* @param null $is_append * @param null $is_append
* @return false|int|mixed * @return mixed
*/ */
public static function writeFile($fileName, $content, $is_append = null) public static function writeFile($fileName, $content, $is_append = null): mixed
{ {
$params = [$fileName, (string)$content]; $params = [$fileName, (string)$content];
if ($is_append !== null) { if ($is_append !== null) {
@@ -188,7 +191,7 @@ class Snowflake
* @param $config * @param $config
* @return mixed * @return mixed
*/ */
public static function configure($object, $config) public static function configure($object, $config): mixed
{ {
foreach ($config as $key => $value) { foreach ($config as $key => $value) {
if (!property_exists($object, $key)) { if (!property_exists($object, $key)) {
@@ -214,7 +217,7 @@ class Snowflake
* @return Server|null * @return Server|null
* @throws * @throws
*/ */
public static function getWebSocket() #[Pure] public static function getWebSocket(): ?Server
{ {
$server = static::app()->server->getServer(); $server = static::app()->server->getServer();
if (!($server instanceof Server)) { if (!($server instanceof Server)) {
@@ -228,7 +231,7 @@ class Snowflake
* @return false|string * @return false|string
* @throws Exception * @throws Exception
*/ */
public static function getMasterPid() public static function getMasterPid(): bool|string
{ {
$default = APP_PATH . 'storage/server.pid'; $default = APP_PATH . 'storage/server.pid';
$server = Config::get('settings.pid_file', false, $default); $server = Config::get('settings.pid_file', false, $default);
@@ -239,10 +242,10 @@ class Snowflake
/** /**
* @param int $fd * @param int $fd
* @param $data * @param $data
* @return false|mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function push(int $fd, $data) public static function push(int $fd, $data): mixed
{ {
$server = static::getWebSocket(); $server = static::getWebSocket();
if (empty($server)) { if (empty($server)) {
@@ -281,9 +284,8 @@ class Snowflake
/** /**
* @param $process * @param $process
* @return mixed|void
*/ */
public static function shutdown($process) public static function shutdown($process): void
{ {
static::app()->server->getServer()->shutdown(); static::app()->server->getServer()->shutdown();
if ($process instanceof Process) { if ($process instanceof Process) {
@@ -296,7 +298,7 @@ class Snowflake
* @param $tmp * @param $tmp
* @return string * @return string
*/ */
public static function rename($tmp) public static function rename($tmp): string
{ {
$hash = md5_file($tmp['tmp_name']); $hash = md5_file($tmp['tmp_name']);
@@ -315,9 +317,9 @@ class Snowflake
public static function isMac() public static function isMac()
{ {
$output = strtolower(PHP_OS | PHP_OS_FAMILY); $output = strtolower(PHP_OS | PHP_OS_FAMILY);
if (strpos('mac', $output) !== false) { if (str_contains('mac', $output)) {
return true; return true;
} else if (strpos('darwin', $output) !== false) { } else if (str_contains('darwin', $output)) {
return true; return true;
} else { } else {
return false; return false;
@@ -327,7 +329,7 @@ class Snowflake
/** /**
* @return bool * @return bool
*/ */
public static function isLinux() public static function isLinux(): bool
{ {
if (!static::isMac()) { if (!static::isMac()) {
return true; return true;
@@ -340,7 +342,7 @@ class Snowflake
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function reload() public static function reload(): mixed
{ {
return Process::kill((int)Snowflake::getMasterPid(), SIGUSR1); return Process::kill((int)Snowflake::getMasterPid(), SIGUSR1);
} }