This commit is contained in:
2020-12-17 14:09:14 +08:00
parent 672a719dbd
commit 36c1d0502a
151 changed files with 1937 additions and 2848 deletions
-157
View File
@@ -1,157 +0,0 @@
<?php
declare(strict_types=1);
namespace Snowflake\Abstracts;
use Exception;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
/**
* Class BaseAnnotation
* @package Snowflake\Snowflake\Annotation\Base
*/
abstract class BaseAnnotation extends Component
{
/**
* @param ReflectionClass $reflect
* @param string $method
* @param array $annotations
* @return array
* @throws ReflectionException
* @throws Exception
*/
public function instance(ReflectionClass $reflect, $method = '', $annotations = [])
{
$classMethods = $reflect->getMethods(ReflectionMethod::IS_PUBLIC);
if (!$reflect->isInstantiable()) {
throw new Exception('Class ' . $reflect->getName() . ' cannot be instantiated.');
}
$array = [];
$object = $reflect->newInstance();
if (!empty($method)) {
$array = $this->resolveDocComment($reflect->getMethod($method), $object, $annotations, $array);
} else {
foreach ($classMethods as $classMethod) {
$array = $this->resolveDocComment($classMethod, $object, $annotations, $array);
}
}
return $array;
}
/**
* @param ReflectionMethod $function
* @param $object
* @param $annotations
* @param $array
* @return array
* @throws
*/
protected function resolveDocComment(ReflectionMethod $function, $object, $annotations, $array)
{
$comment = $function->getDocComment();
$array = $this->getDocCommentAnnotation($annotations, $comment);
foreach ($array as $name => $annotation) {
foreach ($annotation as $index => $events) {
if (!isset($events[1])) {
continue;
}
if (!($_key = $this->getName($name, $events))) {
continue;
}
if (isset($item[2])) {
$handler = Snowflake::createObject($events[2]);
} else {
$handler = [$object, $events[1]];
}
if (!isset($array[$annotation])) {
$array[$annotation] = [];
}
$array[$name][] = [$_key, $handler];
}
}
return $array;
}
/**
* @param $object
* @param $events
* @throws NotFindClassException
* @throws ReflectionException
*/
protected function getOrCreate($object, $events)
{
if (isset($item[2])) {
$handler = Snowflake::createObject($events[2]);
} else {
$handler = [$object, $events[1]];
}
}
/**
* @param $annotations
* @param $comment
* @return array
*/
protected function getDocCommentAnnotation($annotations, $comment)
{
$array = [];
foreach ($annotations as $annotation) {
if (!$comment) {
continue;
}
preg_match('/@(' . $annotation . ')\((.*?)\)/', $comment, $events);
if (!isset($events[1])) {
continue;
}
if (!isset($array[$annotation])) {
$array[$annotation] = [];
}
$array[$annotation] = [$annotation, $events];
}
return $array;
}
/**
* @param $rule
* @param $content
* @param $rules
* @return bool
* @throws ReflectionException
* @throws NotFindClassException
* @throws Exception
*/
public function check($rule, $content, $rules)
{
if (empty($rule)) {
return true;
}
$explode = explode('|', $rule);
foreach ($explode as $value) {
$reflect = array_merge($rules[$value], [
'value' => $content
]);
$validator = Snowflake::createObject($reflect);
if (!$validator->check()) {
throw new Exception($validator->getMessage());
}
}
return false;
}
abstract public function runWith($path);
}
-15
View File
@@ -18,9 +18,7 @@ use HttpServer\Route\Router;
use HttpServer\Server;
use JetBrains\PhpStorm\Pure;
use Kafka\Producer;
use Snowflake\Annotation\Annotation;
use Annotation\Annotation as SAnnotation;
use Snowflake\Cache\Memcached;
use Snowflake\Cache\Redis;
use Snowflake\Di\Service;
use Snowflake\Error\ErrorHandler;
@@ -38,7 +36,6 @@ use Database\DatabasesProviders;
/**
* Class BaseApplication
* @package Snowflake\Snowflake\Base
* @property Annotation $annotation
* @property Event $event
* @property Router $router
* @property SPool $pool
@@ -46,7 +43,6 @@ use Database\DatabasesProviders;
* @property Server $server
* @property DatabasesProviders $db
* @property Connection $connections
* @property Memcached $memcached
* @property Logger $logger
* @property Jwt $jwt
* @property SAnnotation $attributes
@@ -283,16 +279,6 @@ abstract class BaseApplication extends Service
}
/**
* @return Annotation
* @throws ComponentException
*/
public function getAnnotation(): Annotation
{
return $this->get('annotation');
}
/**
* @return Connection
* @throws ComponentException
@@ -389,7 +375,6 @@ abstract class BaseApplication extends Service
$this->setComponents([
'error' => ['class' => ErrorHandler::class],
'event' => ['class' => Event::class],
'annotation' => ['class' => Annotation::class],
'connections' => ['class' => Connection::class],
'redis_connections' => ['class' => SRedis::class],
'pool' => ['class' => SPool::class],
+4 -4
View File
@@ -16,12 +16,12 @@ class BaseGoto extends Component
{
/**
* @param $message
* @param string $message
* @param int $statusCode
* @return mixed|void
* @throws Exception
* @return mixed
* @throws ExitException
*/
public function end(string $message, $statusCode = 200)
public function end(string $message, $statusCode = 200): mixed
{
throw new ExitException(JSON::to(12350, $message), $statusCode);
}
+9 -11
View File
@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Snowflake\Abstracts;
use Exception;
use JetBrains\PhpStorm\Pure;
use Snowflake\Error\Logger;
use Snowflake\Snowflake;
@@ -44,7 +45,7 @@ class BaseObject implements Configure
/**
* @return string
*/
public static function className()
#[Pure] public static function className(): string
{
return get_called_class();
}
@@ -72,7 +73,7 @@ class BaseObject implements Configure
* @return mixed
* @throws Exception
*/
public function __get($name)
public function __get($name): mixed
{
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
@@ -89,7 +90,7 @@ class BaseObject implements Configure
* @return bool
* @throws Exception
*/
public function addError($message, $model = 'app')
public function addError($message, $model = 'app'): bool
{
if ($message instanceof \Throwable) {
$this->error($message->getMessage(), $message->getFile(), $message->getLine());
@@ -109,9 +110,8 @@ class BaseObject implements Configure
* @param mixed $message
* @param string $method
* @param string $file
* @throws
*/
public function debug($message, string $method = __METHOD__, string $file = __FILE__)
public function debug(mixed $message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
@@ -125,9 +125,8 @@ class BaseObject implements Configure
* @param mixed $message
* @param string $method
* @param string $file
* @throws
*/
public function info($message, string $method = __METHOD__, string $file = __FILE__)
public function info(mixed $message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
@@ -140,9 +139,8 @@ class BaseObject implements Configure
* @param mixed $message
* @param string $method
* @param string $file
* @throws
*/
public function success($message, string $method = __METHOD__, string $file = __FILE__)
public function success(mixed $message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
@@ -157,7 +155,7 @@ class BaseObject implements Configure
* @param string $method
* @param string $file
*/
public function warning($message, string $method = __METHOD__, string $file = __FILE__)
public function warning(mixed $message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
@@ -172,7 +170,7 @@ class BaseObject implements Configure
* @param null $method
* @param null $file
*/
public function error($message, $method = null, $file = null)
public function error(mixed $message, $method = null, $file = null)
{
if (!empty($file)) {
echo "\033[41;37m[ERROR][" . date('Y-m-d H:i:s') . ']: ' . $file . "\033[0m";
+11 -7
View File
@@ -6,10 +6,12 @@
* Time: 14:28
*/
declare(strict_types=1);
namespace Snowflake\Abstracts;
use Exception;
use JetBrains\PhpStorm\Pure;
use Snowflake\Snowflake;
/**
@@ -48,7 +50,7 @@ class Component extends BaseObject
* @param null $callback
* @return bool
*/
public function hasEvent($name, $callback = null)
#[Pure] public function hasEvent($name, $callback = null): bool
{
if (!isset($this->_events[$name])) {
return false;
@@ -94,19 +96,21 @@ class Component extends BaseObject
/**
* @param $name
* @param null $handler
* @return mixed
* @return void
*/
public function off($name, $handler = NULL)
public function off($name, $handler = NULL): void
{
$aEvents = Snowflake::app()->event;
if (!isset($this->_events[$name])) {
return $aEvents->of($name, $handler);
$aEvents->of($name, $handler);
return;
}
if (empty($handler)) {
unset($this->_events[$name]);
return $aEvents->of($name, $handler);
$aEvents->of($name, $handler);
return;
}
foreach ($this->_events[$name] as $key => $val) {
@@ -117,7 +121,7 @@ class Component extends BaseObject
break;
}
return $aEvents->of($name, $handler);
$aEvents->of($name, $handler);
}
/**
@@ -150,7 +154,7 @@ class Component extends BaseObject
* @return mixed
* @throws Exception
*/
public function __get($name)
public function __get($name): mixed
{
if (property_exists($this, $name)) {
return $this->$name ?? null;
+7 -6
View File
@@ -9,6 +9,7 @@ declare(strict_types=1);
namespace Snowflake\Abstracts;
use Exception;
use JetBrains\PhpStorm\Pure;
use Snowflake\Exception\ConfigException;
use Snowflake\Abstracts\Component;
use Snowflake\Snowflake;
@@ -29,7 +30,7 @@ class Config extends Component
/**
* @return mixed
*/
public function getData()
public function getData(): mixed
{
return $this->data;
}
@@ -40,7 +41,7 @@ class Config extends Component
* @param $value
* @return mixed
*/
public function setData($key, $value)
public function setData($key, $value): mixed
{
return $this->data[$key] = $value;
}
@@ -52,10 +53,10 @@ class Config extends Component
* @return mixed
* @throws
*/
public static function get($key, $try = FALSE, $default = null)
public static function get($key, $try = FALSE, $default = null): mixed
{
$instance = Snowflake::app()->config->getData();
if (strpos($key, '.') === false) {
if (!str_contains($key, '.')) {
return isset($instance[$key]) ? $instance[$key] : $default;
}
foreach (explode('.', $key) as $value) {
@@ -82,7 +83,7 @@ class Config extends Component
* @return mixed
* @throws Exception
*/
public static function set($key, $value)
public static function set($key, $value): mixed
{
$config = Snowflake::app()->config;
return $config->setData($key, $value);
@@ -93,7 +94,7 @@ class Config extends Component
* @param bool $must_not_null
* @return bool
*/
public static function has($key, $must_not_null = false)
#[Pure] public static function has($key, $must_not_null = false): bool
{
$config = Snowflake::app()->config;
if (!isset($config->data[$key])) {
+6 -6
View File
@@ -29,7 +29,7 @@ class Input
/**
* @return string
*/
public function getCommandName()
public function getCommandName(): string
{
return $this->_command;
}
@@ -40,7 +40,7 @@ class Input
* @param null $default
* @return mixed|null
*/
public function get($key, $default = null)
public function get($key, $default = null): mixed
{
return $this->_argv[$key] ?? $default;
}
@@ -50,7 +50,7 @@ class Input
* @param $value
* @return $this
*/
public function set($key, $value)
public function set($key, $value): static
{
$this->_argv[$key] = $value;
return $this;
@@ -60,7 +60,7 @@ class Input
/**
* @return false|string
*/
public function toJson()
public function toJson(): bool|string
{
return json_encode($this->_argv, JSON_UNESCAPED_UNICODE);
}
@@ -71,7 +71,7 @@ class Input
* @return array
* @throws Exception
*/
public function resolve($parameters)
public function resolve($parameters): array
{
$arrays = [];
$parameters = array_slice($parameters, 1);
@@ -90,7 +90,7 @@ class Input
/**
* @return string
*/
public function getCommand()
public function getCommand(): string
{
return $this->_command;
}
+1 -1
View File
@@ -19,7 +19,7 @@ abstract class Listener extends Component implements IListener
* @return string
* @throws \Exception
*/
public function getName()
public function getName(): string
{
if (empty($this->trigger)) {
throw new \Exception('Listener name con\'t empty.');
+16 -15
View File
@@ -5,6 +5,7 @@ namespace Snowflake\Abstracts;
use Exception;
use JetBrains\PhpStorm\Pure;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
@@ -37,10 +38,10 @@ abstract class Pool extends Component
/**
* @param $name
* @return mixed
* @return array
* @throws Exception
*/
protected function get($name)
protected function get($name): array
{
[$timeout, $connection] = $this->_items[$name]->pop();
if (!$this->checkCanUse($name, $timeout, $connection)) {
@@ -56,12 +57,12 @@ abstract class Pool extends Component
* @param false $isMaster
* @return string
*/
public function name($cds, $isMaster = false)
#[Pure] public function name($cds, $isMaster = false): string
{
if ($isMaster === true) {
return hash('sha256',$cds . 'master');
return hash('sha256', $cds . 'master');
} else {
return hash('sha256',$cds . 'slave');
return hash('sha256', $cds . 'slave');
}
}
@@ -74,7 +75,7 @@ abstract class Pool extends Component
* 检查连接可靠性
* @throws Exception
*/
public function checkCanUse($name, $time, $client)
public function checkCanUse(string $name, int $time, mixed $client): mixed
{
throw new Exception('Undefined system processing function.');
}
@@ -83,7 +84,7 @@ abstract class Pool extends Component
* @param $name
* @throws Exception
*/
public function desc($name)
public function desc(string $name)
{
throw new Exception('Undefined system processing function.');
}
@@ -93,16 +94,16 @@ abstract class Pool extends Component
* @param $isMaster
* @throws Exception
*/
public function getConnection(array $config, $isMaster)
public function getConnection(array $config, bool $isMaster)
{
throw new Exception('Undefined system processing function.');
}
/**
* @param $name
* @return mixed
* @return bool
*/
public function hasItem($name)
public function hasItem(string $name): bool
{
return $this->size($name) > 0;
}
@@ -112,7 +113,7 @@ abstract class Pool extends Component
* @param $name
* @return mixed
*/
public function size($name)
public function size(string $name): mixed
{
if (!isset($this->_items[$name])) {
return 0;
@@ -125,7 +126,7 @@ abstract class Pool extends Component
* @param $name
* @param $client
*/
public function push($name, $client)
public function push(string $name, mixed $client)
{
$this->_items[$name]->push([time(), $client]);
unset($client);
@@ -133,9 +134,9 @@ abstract class Pool extends Component
/**
* @param $name
* @param string $name
*/
public function clean($name)
public function clean(string $name)
{
if (!isset($this->_items[$name])) {
return;
@@ -150,7 +151,7 @@ abstract class Pool extends Component
/**
* @return Channel[]
*/
protected function getChannels()
protected function getChannels(): array
{
return $this->_items;
}
-282
View File
@@ -1,282 +0,0 @@
<?php
declare(strict_types=1);
namespace Snowflake\Annotation;
use Exception;
use HttpServer\Route\Annotation\Http;
use HttpServer\Route\Annotation\Tcp;
use HttpServer\Route\Annotation\Websocket;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Snowflake\Abstracts\BaseAnnotation;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
/**
* Class Annotation
* @package Snowflake\Snowflake\Annotation
* @property Http $http
* @property Websocket $websocket
* @property Tcp $tcp
*/
class Annotation extends BaseAnnotation
{
public string $namespace = '';
public string $prefix = '';
public string $path = '';
protected array $_Scan_directory = [];
protected array $_alias = [];
protected array $params = [];
private array $_classMap = [
'http' => Http::class,
'tcp' => Tcp::class,
'websocket' => Websocket::class
];
/**
* @param $name
* @param $class
* @return mixed
* @throws
*/
public function register($name, $class)
{
if (!isset($this->_classMap[$name]) || is_string($this->_classMap[$name])) {
$this->_classMap[$name] = Snowflake::createObject($class);
}
return $this->_classMap[$name];
}
/**
* @param $path
* @param $namespace
* @throws ReflectionException
*/
public function registration_notes($path = '', $namespace = '')
{
if (empty($path)) {
$path = $this->path;
}
if (empty($namespace)) {
$namespace = $this->namespace;
}
$this->scanning(rtrim($path, '/'), $namespace, get_called_class());
}
/**
* @param ReflectionClass $reflect
* @param string $className
* @throws ReflectionException
* @throws Exception
* @Message(updatePosition)
* 注入注解
*/
private function resolve(ReflectionClass $reflect, string $className)
{
$controller = $reflect->newInstance();
$annotations = $this->getAnnotation($className);
$methods = $reflect->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($methods as $function) {
foreach ($annotations as $annotation) {
$comment = $function->getDocComment();
$methodName = $function->getName();
if (!$comment) {
continue;
}
preg_match('/@(' . $annotation . ')\((.*?)\)/', $comment, $events);
if (!isset($events[1])) {
continue;
}
if (!$this->isLegitimate($events)) {
continue;
}
$this->push($this->getName($annotation, $events), [$controller, $methodName]);
}
}
}
/**
* @param $name
* @return mixed
* @throws Exception
*/
public function get($name)
{
if (!isset($this->_classMap[$name])) {
throw new Exception('Undefined analytic class ' . $name . '.');
}
return $this->_classMap[$name];
}
/**
* @param $events
* @throws Exception
*/
public function isLegitimate($events)
{
throw new Exception('Undefined analytic function isLegitimate.');
}
/**
* @param $function
* @param $events
* @throws Exception
*/
public function getName($function, $events)
{
throw new Exception('Undefined analytic function getName.');
}
/**
* @param $controller
* @param $methodName
* @param $events
* @throws Exception
*/
public function createHandler($controller, $methodName, $events)
{
throw new Exception('Undefined analytic function.');
}
/**
* @param string $path
* @param $namespace
* @param $className
* @throws ReflectionException
*/
protected function scanning(string $path, $namespace, $className)
{
$di = Snowflake::getDi();
foreach (glob($path . '/*') as $file) {
if (is_dir($file)) {
$this->scanning($path, $namespace, $className);
}
$explode = explode('/', $file);
$class = str_replace('.php', '', end($explode));
$this->resolve($di->getReflect($namespace . '\\' . $class), $className);
}
}
/**
* @param $path
* @param array $params
* @return bool|mixed
*/
public function runWith($path, $params = [])
{
if (!$this->has($path)) {
return null;
}
$callback = $this->_Scan_directory[$path];
if (!isset($this->params[$path])) {
return $callback(...$params);
}
return $callback(...$this->params[$path]);
}
/**
* @param $name
* @param $callback
* @param array $params
*/
public function push($name, $callback, $params = [])
{
$this->_Scan_directory[$name] = $callback;
if (!empty($params)) {
$this->params[$name] = $params;
}
}
/**
* @param $name
* @return array|null[]
*/
public function pop($name)
{
if (isset($this->_Scan_directory[$name])) {
return [$this->_Scan_directory[$name], $this->params[$name] ?? []];
}
return [null, null];
}
/**
* @param $path
* @return bool|mixed
*/
public function has($path)
{
return isset($this->_Scan_directory[$path]);
}
/**
* @param $name
* @return mixed|null
* @throws ReflectionException
* @throws NotFindClassException
* @throws Exception
*/
public function __get($name)
{
if (!isset($this->_classMap[$name])) {
return parent::__get($name); // TODO: Change the autogenerated stub
}
if (!is_object($this->_classMap[$name])) {
$this->_classMap[$name] = Snowflake::createObject($this->_classMap[$name]);
}
return $this->_classMap[$name];
}
/**
* @param ReflectionClass $reflect
* @return array
*/
protected function getPrivates(ReflectionClass $reflect)
{
$arrays = [];
$properties = $reflect->getProperties(ReflectionMethod::IS_PRIVATE);
foreach ($properties as $property) {
$arrays[] = $property->getName();
}
return $arrays;
}
/**
* @param string $class
* @return string[]
* @throws ReflectionException
*/
public function getAnnotation(string $class)
{
$reflect = Snowflake::getDi()->getReflect($class);
return $this->getPrivates($reflect);
}
}
+13 -10
View File
@@ -20,6 +20,7 @@ use Snowflake\Abstracts\Config;
use Snowflake\Abstracts\Input;
use Snowflake\Abstracts\Kernel;
use Snowflake\Exception\NotFindClassException;
use stdClass;
use Swoole\Timer;
/**
@@ -54,7 +55,7 @@ class Application extends BaseApplication
* @return $this
* @throws
*/
public function import(string $service)
public function import(string $service): static
{
if (!class_exists($service)) {
throw new NotFindClassException($service);
@@ -71,7 +72,7 @@ class Application extends BaseApplication
* @param $kernel
* @return $this
*/
public function commands(Kernel $kernel)
public function commands(Kernel $kernel): static
{
foreach ($kernel->getCommands() as $command) {
$this->register($command);
@@ -93,20 +94,22 @@ class Application extends BaseApplication
/**
* @param $argv
* @return bool|string|void
* @throws
* @param Input $argv
* @return bool|string
* @throws Exception
* @throws NotFindClassException
* @throws \ReflectionException
*/
public function start(Input $argv)
public function start(Input $argv): bool|string
{
$this->set('input', $argv);
try {
$manager = Snowflake::app()->get('console');
$manager->setParameters($argv);
$class = $manager->search();
response()->send($manager->execCommand($class));
return response()->send($manager->execCommand($class));
} catch (\Throwable $exception) {
response()->send(implode("\n", [
return response()->send(implode("\n", [
'Msg: ' . $exception->getMessage(),
'Line: ' . $exception->getLine(),
'File: ' . $exception->getFile()
@@ -119,10 +122,10 @@ class Application extends BaseApplication
/**
* @param $className
* @param null $abstracts
* @return mixed
* @return stdClass
* @throws Exception
*/
public function make($className, $abstracts = null)
public function make($className, $abstracts = null): stdClass
{
return make($className, $abstracts);
}
+21 -18
View File
@@ -6,10 +6,12 @@
* Time: 14:51
*/
declare(strict_types=1);
namespace Snowflake\Cache;
use Exception;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Component;
use Swoole\Coroutine\System;
@@ -32,8 +34,9 @@ class File extends Component implements ICache
/**
* @param $key
* @param $val
* @return string|int
*/
public function set($key, $val)
public function set($key, $val): string|int
{
if (is_array($val) || is_object($val)) {
$val = serialize($val);
@@ -42,15 +45,15 @@ class File extends Component implements ICache
if (!$this->exists($tmpFile)) {
touch($tmpFile);
}
System::writeFile($tmpFile, $val, LOCK_EX);
return System::writeFile($tmpFile, $val, LOCK_EX);
}
/**
* @param $key
* @param array $hashKeys
* @return mixed|void
* @return array|bool
*/
public function hMget($key, array $hashKeys)
public function hMGet($key, array $hashKeys): array|bool
{
$hash = $this->get($key);
if (!is_array($hash)) {
@@ -67,9 +70,9 @@ class File extends Component implements ICache
/**
* @param $key
* @param array $val
* @return mixed|void
* @return mixed
*/
public function hMset($key, array $val)
public function hMSet($key, array $val): mixed
{
$hash = $this->get($key);
if (!is_array($hash)) {
@@ -81,11 +84,11 @@ class File extends Component implements ICache
}
/**
* @param $key
* @param $hashKey
* @return mixed|void
* @param string $key
* @param string $hashKey
* @return string|int|bool
*/
public function hget($key, $hashKey)
public function hGet(string $key, string $hashKey): string|int|bool|null
{
$hash = $this->get($key);
if (!is_array($hash)) {
@@ -98,9 +101,9 @@ class File extends Component implements ICache
* @param $key
* @param $hashKey
* @param $hashValue
* @return mixed|void
* @return mixed
*/
public function hset($key, $hashKey, $hashValue)
public function hSet($key, $hashKey, $hashValue): mixed
{
$hash = $this->get($key);
if (!is_array($hash)) {
@@ -116,20 +119,20 @@ class File extends Component implements ICache
* @param $key
* @return bool
*/
public function exists($key)
#[Pure] public function exists($key): bool
{
return file_exists($key);
}
/**
* @param $key
* @return mixed|null
* @return mixed|bool
*/
public function get($key)
public function get($key): string|bool
{
$tmpFile = $this->getCacheKey($key);
if (!$this->exists($tmpFile)) {
return NULL;
return false;
}
$content = file_get_contents($tmpFile);
return unserialize($content);
@@ -140,8 +143,8 @@ class File extends Component implements ICache
* @return string
* @throws
*/
private function getCacheKey($key)
private function getCacheKey($key): string
{
return storage($key,'cache');
return storage($key, 'cache');
}
}
+15 -14
View File
@@ -6,6 +6,7 @@
* Time: 16:35
*/
declare(strict_types=1);
namespace Snowflake\Cache;
/**
@@ -17,36 +18,36 @@ interface ICache
/**
* @param $key
* @param $val
* @return mixed
* @return string|int
*/
public function set($key, $val);
public function set($key, $val): string|int;
/**
* @param $key
* @return mixed
* @return string|int|bool
*/
public function get($key);
public function get($key): string|int|bool;
/**
* @param $key
* @param $hashKeys
* @return mixed
* @param array $hashKeys
* @return array|bool|null
*/
public function hMget($key, array $hashKeys);
public function hMGet($key, array $hashKeys): array|bool|null;
/**
* @param $key
* @param array $val
* @return mixed
*/
public function hMset($key, array $val);
public function hMSet($key, array $val): mixed;
/**
* @param $key
* @param $hashKey
* @return mixed
* @param string $key
* @param string $hashKey
* @return string|int|bool
*/
public function hget($key, $hashKey);
public function hGet(string $key, string $hashKey): string|int|bool;
/**
* @param $key
@@ -54,11 +55,11 @@ interface ICache
* @param $hashValue
* @return mixed
*/
public function hset($key, $hashKey, $hashValue);
public function hSet($key, $hashKey, $hashValue): mixed;
/**
* @param $key
* @return bool
*/
public function exists($key);
public function exists($key): bool;
}
-154
View File
@@ -1,154 +0,0 @@
<?php
declare(strict_types=1);
namespace Snowflake\Cache;
use Exception;
use Snowflake\Abstracts\Component;
use Snowflake\Abstracts\Config;
use Snowflake\Event;
use Snowflake\Exception\ConfigException;
use Snowflake\Snowflake;
/**
* Class Memcached
* @package Yoc\cache
*/
class Memcached extends Component implements ICache
{
/** @var \Memcached */
private \Memcached $_memcached;
public string $host = '127.0.0.1';
public int $port = 11211;
public int $timeout = 60;
/**
* @throws Exception
*/
public function init()
{
$event = Snowflake::app()->event;
$event->on(Event::RELEASE_ALL, [$this, 'destroy']);
$event->on(Event::EVENT_AFTER_REQUEST, [$this, 'release']);
$id = Config::get('id', false, 'system');
$this->_memcached = new \Memcached($id);
$this->addServer();
}
/**
* @return \Memcached
* @throws Exception
*/
public function getConnect()
{
return $this->_memcached;
}
/**
* @throws ConfigException
* @throws Exception
*/
private function addServer()
{
$array = [];
$memcached = Config::get('cache.memcached');
if (isset($memcached[0])) {
foreach ($memcached as $value) {
$array[] = [$value['host'], $value['port'], $value['weight']];
}
$isConnected = $this->_memcached->addServers($array);
} else {
$array[] = Config::get('cache.memcached.host', true);
$array[] = Config::get('cache.memcached.port', true);
$array[] = Config::get('cache.memcached.weight', true);
$isConnected = $this->_memcached->addServer(...$array);
}
if (!$isConnected) {
throw new Exception('Cache Memcache Host 127.0.0.1 Connect Fail.');
}
}
/**
* @param $key
* @param $val
* @return mixed|void
*/
public function set($key, $val)
{
// TODO: Implement set() method.
if (is_array($val) || is_object($val)) {
$val = serialize($val);
}
$this->_memcached->set($key, $val);
}
/**
* @param $key
* @return mixed|void
*/
public function get($key)
{
// TODO: Implement get() method.
}
/**
* @param $key
* @param array $hashKeys
* @return mixed|void
*/
public function hMget($key, array $hashKeys)
{
// TODO: Implement hMget() method.
}
/**
* @param $key
* @param array $val
* @return mixed|void
*/
public function hMset($key, array $val)
{
// TODO: Implement hMset() method.
}
/**
* @param $key
* @param $hashKey
* @return mixed|void
*/
public function hget($key, $hashKey)
{
// TODO: Implement hget() method.
}
/**
* @param $key
* @param $hashKey
* @param $hashValue
* @return mixed|void
*/
public function hset($key, $hashKey, $hashValue)
{
// TODO: Implement hset() method.
}
/**
* @param $key
* @return bool|void
*/
public function exists($key)
{
// TODO: Implement exists() method.
}
}
+3 -3
View File
@@ -46,7 +46,7 @@ class Redis extends Component
* @return mixed
* @throws
*/
public function __call($name, $arguments)
public function __call($name, $arguments): mixed
{
if (method_exists($this, $name)) {
$data = $this->{$name}(...$arguments);
@@ -82,7 +82,7 @@ SCRIPT;
* @return int
* @throws Exception
*/
public function unlock($key)
public function unlock($key): int
{
$redis = $this->proxy();
return $redis->del($key);
@@ -113,7 +113,7 @@ SCRIPT;
* @return \Redis
* @throws Exception
*/
public function proxy()
public function proxy(): \Redis
{
$connections = Snowflake::app()->pool->redis;
+4 -4
View File
@@ -24,7 +24,7 @@ class ArrayAccess
* @return array
* @throws Exception
*/
public static function toArray($data)
public static function toArray($data): array
{
if (!is_object($data) && !is_array($data)) {
return $data;
@@ -49,10 +49,10 @@ class ArrayAccess
/**
* @param $data
* @return array|mixed
* @return array
* @throws Exception
*/
public static function objToArray($data)
public static function objToArray($data): array
{
if (!is_object($data)) {
return $data;
@@ -77,7 +77,7 @@ class ArrayAccess
* @param array $newArray
* @return array
*/
public static function merge(array $oldArray, array $newArray)
public static function merge(array $oldArray, array $newArray): array
{
if (empty($oldArray)) {
return $newArray;
+8 -6
View File
@@ -9,6 +9,8 @@ declare(strict_types=1);
namespace Snowflake\Core;
use JetBrains\PhpStorm\Pure;
/**
* Class DateFormat
* @package Snowflake\Snowflake\Core
@@ -20,7 +22,7 @@ class DateFormat
* @param $time
* @return bool|false|int|string
*/
private static function check($time)
private static function check($time): bool|int|string
{
if ($time === null) {
$time = time();
@@ -46,7 +48,7 @@ class DateFormat
*
* 获取指定日期当周第一天的时间
*/
public static function getWeekCurrentDay($time = null)
public static function getWeekCurrentDay($time = null): bool|int
{
if (!($time = static::check($time))) {
return false;
@@ -64,7 +66,7 @@ class DateFormat
*
* 获取指定日期当月第一天的时间
*/
public static function getMonthCurrentDay($time = null)
public static function getMonthCurrentDay($time = null): bool|int
{
if (!($time = static::check($time))) {
return false;
@@ -75,10 +77,10 @@ class DateFormat
/**
* @param $time
* @return bool|false|int|string
* @return bool|int|string 指定的月份有几天
* 指定的月份有几天
*/
public static function getMonthTotalDay($time)
public static function getMonthTotalDay($time): bool|int|string
{
if (!($time = static::check($time))) {
return false;
@@ -94,7 +96,7 @@ class DateFormat
* @param null $endTime
* @return string
*/
public static function mtime($startTime, $endTime = null)
#[Pure] public static function mtime($startTime, $endTime = null)
{
if ($endTime === null) {
$endTime = microtime(true);
+4 -4
View File
@@ -30,10 +30,10 @@ class Dtl extends Component
/**
* @return mixed
* @return array
* @throws Exception
*/
public function toArray()
public function toArray(): array
{
if (!is_array($this->params)) {
return ArrayAccess::toArray($this->params);
@@ -44,10 +44,10 @@ class Dtl extends Component
/**
* @param $name
* @return mixed|null
* @return mixed
* @throws Exception
*/
public function get($name)
public function get($name): mixed
{
$array = $this->toArray();
if (!isset($array[$name])) {
+18 -11
View File
@@ -5,6 +5,9 @@ declare(strict_types=1);
namespace Snowflake\Core;
use Exception;
use JetBrains\PhpStorm\Pure;
/**
* Class Help
* @package Snowflake\Snowflake\Core
@@ -16,7 +19,7 @@ class Help
* @param array $data
* @return string
*/
public static function toXml(array $data)
#[Pure] public static function toXml(array $data)
{
$xml = "<xml>";
foreach ($data as $key => $val) {
@@ -33,9 +36,9 @@ class Help
/**
* @param $xml
* @return array|mixed
* @return mixed
*/
public static function toArray($xml)
public static function toArray($xml): mixed
{
if (empty($xml)) {
return null;
@@ -49,7 +52,11 @@ class Help
}
public static function jsonToArray($xml)
/**
* @param $xml
* @return mixed
*/
public static function jsonToArray($xml): mixed
{
$_xml = json_decode($xml, true);
if (is_null($_xml)) {
@@ -62,7 +69,7 @@ class Help
* @param $xml
* @return mixed
*/
public static function xmlToArray($xml)
public static function xmlToArray($xml): mixed
{
if (is_array($xml)) {
return $xml;
@@ -79,9 +86,9 @@ class Help
/**
* @param $parameter
* @return array|false|string
* @throws \Exception
* @throws Exception
*/
public static function toString($parameter)
public static function toString($parameter): bool|array|string
{
if (!is_string($parameter)) {
$parameter = ArrayAccess::toArray($parameter);
@@ -94,9 +101,9 @@ class Help
/**
* @param mixed $json
* @return false|mixed|string
* @return bool|string
*/
public static function toJson($json)
public static function toJson(mixed $json): bool|string
{
if (is_object($json)) {
$json = get_object_vars($json);
@@ -122,7 +129,7 @@ class Help
*
* 随机字符串
*/
public static function random($length = 20)
public static function random($length = 20): string
{
$res = [];
$str = 'abcdefghijklmnopqrstuvwxyz';
@@ -144,7 +151,7 @@ class Help
* @param $type
* @return string
*/
public static function sign(array $array, $key, $type)
public static function sign(array $array, $key, $type): string
{
ksort($array, SORT_ASC);
$string = [];
+4 -4
View File
@@ -24,7 +24,7 @@ class JSON
* @return false|string
* @throws Exception
*/
public static function encode($data)
public static function encode($data): bool|string
{
if (empty($data)) {
return $data;
@@ -41,7 +41,7 @@ class JSON
* @param bool $asArray
* @return mixed
*/
public static function decode($data, $asArray = true)
public static function decode($data, $asArray = true): mixed
{
if (is_array($data)) {
return $data;
@@ -58,7 +58,7 @@ class JSON
* @return mixed
* @throws
*/
public static function to($code, $message = '', $data = [], $count = 0, $exPageInfo = [])
public static function to($code, $message = '', $data = [], $count = 0, $exPageInfo = []): mixed
{
$params['code'] = $code;
if (!is_string($message)) {
@@ -91,7 +91,7 @@ class JSON
* @return false|int|string
* @throws Exception
*/
public static function output($state, $body)
public static function output($state, $body): bool|int|string
{
$params['state'] = $state;
$params['body'] = ArrayAccess::toArray($body);
+4 -4
View File
@@ -18,7 +18,7 @@ class Reader
* @param int $size
* @return array and int
*/
public static function readerServerLogPagination($filepath, $page = 1, $size = 20)
public static function readerServerLogPagination($filepath, $page = 1, $size = 20): array
{
$count = 0;
$strings = [];
@@ -56,7 +56,7 @@ class Reader
* @param $lines
* @return mixed
*/
public static function read_backward_line($filename, $start, $lines)
public static function read_backward_line($filename, $start, $lines): mixed
{
$lines++;
$offset = -1;
@@ -100,7 +100,7 @@ class Reader
* @param $filepath
* @return int
*/
private static function read_count_by_file($filepath)
private static function read_count_by_file($filepath): int
{
$count = 0;
//只读方式打开文件
@@ -123,7 +123,7 @@ class Reader
* @param int $size
* @return array
*/
public static function folderPagination($filepath, $page = 1, $size = 20)
public static function folderPagination($filepath, $page = 1, $size = 20): array
{
$count = 0;
$strings = [];
+18 -17
View File
@@ -5,6 +5,7 @@ namespace Snowflake\Core;
use Exception;
use JetBrains\PhpStorm\Pure;
/**
* Class Str
@@ -23,7 +24,7 @@ class Str
* @return string
* 获取随机字符串
*/
public static function rand(int $length = 20)
#[Pure] public static function rand(int $length = 20): string
{
$string = '';
if ($length < 1) $length = 20;
@@ -38,10 +39,10 @@ class Str
/**
* @param int $length
*
* @return int
* @return int|string 获取随机数字
* 获取随机数字
*/
public static function random(int $length = 20)
#[Pure] public static function random(int $length = 20): int|string
{
$number = '';
$default = str_split(self::NUMBER);
@@ -54,13 +55,13 @@ class Str
/**
* @param $string
* @param $sublen
* @param $sullen
* @param bool $strip_tags
* @param string $append
*
* @return string
*/
public static function cut_str_utf8($string, $sublen, $strip_tags = true, $append = '...')
public static function cut_str_utf8($string, $sullen, $strip_tags = true, $append = '...'): string
{
if ($strip_tags) {
$string = strip_tags($string);
@@ -71,7 +72,7 @@ class Str
for ($i = 0; $i < count($t_string[0]); $i++) {
$str .= $t_string[0][$i];
//转为gbk,一个汉字长度为2
if (strlen(@iconv('utf-8', 'gbk', $str)) >= $sublen) {
if (strlen(@iconv('utf-8', 'gbk', $str)) >= $sullen) {
if ($i != count($t_string[0]) - 1) $str .= $append;
break;
}
@@ -86,7 +87,7 @@ class Str
* @return bool
* 判断是否为json字符串
*/
public static function isJson($data, $callback = null)
public static function isJson($data, $callback = null): bool
{
$json = !is_null(json_decode($data)) && !is_numeric($data);
if ($json && is_callable($callback, true)) {
@@ -102,7 +103,7 @@ class Str
* @return bool
* 判断是否序列化字符串
*/
public static function isSerialize($data, $callBack = null)
public static function isSerialize($data, $callBack = null): bool
{
$false = !empty($data) && unserialize($data) !== false;
if ($false && is_callable($callBack, true)) {
@@ -118,7 +119,7 @@ class Str
* @param string $append
* @return string
*/
public static function cut($string, int $length = 20, $append = '...')
#[Pure] public static function cut($string, int $length = 20, $append = '...'): string
{
if (empty($string)) {
return '';
@@ -144,7 +145,7 @@ class Str
*
* @return string
*/
public static function encrypt($str, $number = 10, $key = 'xshucai.com')
public static function encrypt($str, $number = 10, $key = 'xshucai.com'): string
{
$res = [];
$add = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
@@ -166,7 +167,7 @@ class Str
* @param $type
* @return string
*/
public static function filename($file, $type)
#[Pure] public static function filename($file, $type): string
{
switch ($type) {
case 'image/png':
@@ -187,7 +188,7 @@ class Str
* @return array
* 剩余天,带分秒
*/
public static function timeout($endTime, int $startTime = null)
public static function timeout($endTime, int $startTime = null): array
{
$endTime = $endTime - (!empty($startTime) ? $startTime : time());
@@ -206,7 +207,7 @@ class Str
/**
* @return false|int
*/
public static function get_sy_time()
public static function get_sy_time(): bool|int
{
$time = strtotime('+1days', strtotime(date('Y-m-d')));
@@ -217,7 +218,7 @@ class Str
* @param string $string
* @return string
*/
public static function encode(string $string)
#[Pure] public static function encode(string $string): string
{
return addslashes($string);
}
@@ -227,7 +228,7 @@ class Str
* @return string|string[]|null
* 清除标点符号
*/
public static function clear(string $string)
public static function clear(string $string): array|string|null
{
$char = '。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()';
return preg_replace(array("/[[:punct:]]/i", '/[' . $char . ']/u', '/[ ]{2,}/'), '', $string);
@@ -237,12 +238,12 @@ class Str
/**
* @param int $user
* @param array $param
* @param int $requestTime
* @param null $requestTime
*
* @return string
* @throws Exception
*/
public static function token($user, $param = [], $requestTime = NULL)
public static function token(int $user, $param = [], $requestTime = NULL): string
{
$str = '';
if (!$requestTime) {
+2 -2
View File
@@ -21,7 +21,7 @@ class Xml
* @param bool $asArray
* @return array|object
*/
public static function toArray($data, $asArray = true)
public static function toArray($data, $asArray = true): object|array
{
$data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($asArray) {
@@ -35,7 +35,7 @@ class Xml
* @param $str
* @return array|bool|object
*/
public static function isXml($str)
public static function isXml($str): object|bool|array
{
$xml_parser = xml_parser_create();
if (!xml_parse($xml_parser, $str, true)) {
+4 -4
View File
@@ -88,7 +88,7 @@ class ErrorHandler extends Component implements ErrorInterface
public function errorHandler()
{
$error = func_get_args();
if (strpos($error[2], 'vendor/Reboot.php') !== FALSE) {
if (str_contains($error[2], 'vendor/Reboot.php')) {
return;
}
@@ -116,7 +116,7 @@ class ErrorHandler extends Component implements ErrorInterface
* @return false|string
* @throws Exception
*/
public function sendError($message, $file, $line, $code = 500)
public function sendError($message, $file, $line, $code = 500): bool|string
{
$path = ['file' => $file, 'line' => $line];
@@ -130,7 +130,7 @@ class ErrorHandler extends Component implements ErrorInterface
/**
* @return mixed
*/
public function getErrorMessage()
public function getErrorMessage(): mixed
{
$message = $this->message;
$this->message = NULL;
@@ -140,7 +140,7 @@ class ErrorHandler extends Component implements ErrorInterface
/**
* @return bool
*/
public function getAsError()
public function getAsError(): bool
{
return $this->message !== NULL;
}
+1 -1
View File
@@ -23,6 +23,6 @@ interface ErrorInterface
* @param int $code
* @return mixed
*/
public function sendError($message, $file, $line, $code = 500);
public function sendError($message, $file, $line, $code = 500): mixed;
}
+45 -45
View File
@@ -30,58 +30,58 @@ class Logger extends Component
/**
* @param $message
* @param string $category
* @param null $_
* @param string $method
* @param null $file
* @throws Exception
*/
public function debug($message, $category = 'app', $_ = null)
public function debug(mixed $message, string $method = 'app', $file = null)
{
$this->writer($message, $category);
$this->writer($message, $method);
}
/**
* @param $message
* @param string $category
* @param string $method
* @throws Exception
*/
public function trance($message, $category = 'app')
public function trance($message, $method = 'app')
{
$this->writer($message, $category);
$this->writer($message, $method);
}
/**
* @param $message
* @param string $category
* @param null $_
* @param string $method
* @param null $file
* @throws Exception
*/
public function error($message, $category = 'error', $_ = null)
public function error(mixed $message, $method = 'error', $file = null)
{
$this->writer($message, $category);
$this->writer($message, $method);
}
/**
* @param $message
* @param string $category
* @param null $_
* @param string $method
* @param null $file
* @throws Exception
*/
public function success($message, $category = 'app', $_ = null)
public function success(mixed $message, $method = 'app', $file = null)
{
$this->writer($message, $category);
$this->writer($message, $method);
}
/**
* @param $message
* @param string $category
* @param string $method
* @return string
* @throws Exception
*/
private function writer($message, $category = 'app')
private function writer($message, $method = 'app'): string
{
$this->print_r($message, $category);
$this->print_r($message, $method);
if ($message instanceof Throwable) {
$message = $message->getMessage();
} else {
@@ -96,7 +96,7 @@ class Logger extends Component
if (!is_array($this->logs)) {
$this->logs = [];
}
$this->logs[] = [$category, $message];
$this->logs[] = [$method, $message];
}
return $message;
}
@@ -104,17 +104,17 @@ class Logger extends Component
/**
* @param $message
* @param $category
* @param $method
* @throws Exception
*/
public function print_r($message, $category = '')
public function print_r($message, $method = '')
{
$debug = Config::get('debug', false, ['enable' => false]);
if ((bool)$debug['enable'] === true) {
if (!is_callable($debug['callback'] ?? null, true)) {
return;
}
call_user_func($debug['callback'], $message, $category);
call_user_func($debug['callback'], $message, $method);
}
}
@@ -123,33 +123,33 @@ class Logger extends Component
* @param string $application
* @return mixed
*/
public function getLastError($application = 'app')
public function getLastError($application = 'app'): mixed
{
$_tmp = [];
$filetype = [];
foreach ($this->logs as $key => $val) {
if ($val[0] != $application) {
continue;
}
$_tmp[] = $val[1];
$filetype[] = $val[1];
}
if (empty($_tmp)) {
if (empty($filetype)) {
return 'Unknown error.';
}
return end($_tmp);
return end($filetype);
}
/**
* @param $messages
* @param string $category
* @param string $method
* @throws
*/
public function write(string $messages, $category = 'app')
public function write(string $messages, $method = 'app')
{
if (empty($messages)) {
return;
}
$fileName = 'server-' . date('Y-m-d') . '.log';
$dirName = 'log/' . (empty($category) ? 'app' : $category);
$dirName = 'log/' . (empty($method) ? 'app' : $method);
$logFile = '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL;
Snowflake::writeFile(storage($fileName, $dirName), $logFile, FILE_APPEND);
@@ -167,9 +167,9 @@ class Logger extends Component
/**
* @param $logFile
* @return false|string
* @return string
*/
private function getSource($logFile)
private function getSource($logFile): string
{
if (!file_exists($logFile)) {
shell_exec('echo 3 > /proc/sys/vm/drop_caches');
@@ -191,8 +191,8 @@ class Logger extends Component
return;
}
foreach ($this->logs as $log) {
[$category, $message] = $log;
$this->write($message, $category);
[$method, $message] = $log;
$this->write($message, $method);
}
$this->logs = [];
}
@@ -200,7 +200,7 @@ class Logger extends Component
/**
* @return array
*/
public function clear()
public function clear(): array
{
return $this->logs = [];
}
@@ -209,7 +209,7 @@ class Logger extends Component
* @param $data
* @return string
*/
private function arrayFormat($data)
private function arrayFormat($data): string
{
if (is_string($data)) {
return $data;
@@ -220,15 +220,15 @@ class Logger extends Component
$data = get_object_vars($data);
}
$_tmp = [];
$filetype = [];
foreach ($data as $key => $val) {
if (is_array($val)) {
$_tmp[] = $this->arrayFormat($val);
$filetype[] = $this->arrayFormat($val);
} else {
$_tmp[] = (is_string($key) ? $key . ' : ' : '') . $val;
$filetype[] = (is_string($key) ? $key . ' : ' : '') . $val;
}
}
return implode(PHP_EOL, $_tmp);
return implode(PHP_EOL, $filetype);
}
@@ -269,12 +269,12 @@ class Logger extends Component
* @param Throwable $exception
* @return array
*/
private function getException(Throwable $exception)
private function getException(Throwable $exception): array
{
$_tmp = [$exception->getMessage()];
$_tmp[] = $exception->getFile() . ' on line ' . $exception->getLine();
$_tmp[] = $exception->getTrace();
return $_tmp;
$filetype = [$exception->getMessage()];
$filetype[] = $exception->getFile() . ' on line ' . $exception->getLine();
$filetype[] = $exception->getTrace();
return $filetype;
}
}
+6 -6
View File
@@ -87,7 +87,7 @@ class Event extends BaseObject
* @param $name
* @param $callback
*/
public function of($name, $callback)
public function of($name, $callback): void
{
if (!isset($this->_events[$name])) {
return;
@@ -106,7 +106,7 @@ class Event extends BaseObject
* @param $name
* @return bool
*/
public function offName($name)
public function offName($name): bool
{
if (!$this->exists($name)) {
return true;
@@ -121,7 +121,7 @@ class Event extends BaseObject
* @param null $callback
* @return bool
*/
public function exists($name, $callback = null)
public function exists($name, $callback = null): bool
{
if (!isset($this->_events[$name])) {
return false;
@@ -142,9 +142,9 @@ class Event extends BaseObject
/**
* @param $name
* @param $handler
* @return mixed|null
* @return mixed
*/
public function get($name, $handler)
public function get($name, $handler): mixed
{
if (!$this->exists($name)) {
return null;
@@ -173,7 +173,7 @@ class Event extends BaseObject
* @return bool|mixed
* @throws Exception
*/
public function trigger($name, $parameter = null, $handler = null, $is_remove = false)
public function trigger($name, $parameter = null, $handler = null, $is_remove = false): mixed
{
if (!$this->exists($name)) {
return false;
+8 -1
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Snowflake\Exception;
use JetBrains\PhpStorm\Pure;
use Throwable;
/**
@@ -14,7 +15,13 @@ use Throwable;
class AuthException extends \Exception
{
public function __construct($message = "", $code = 0, Throwable $previous = null)
/**
* AuthException constructor.
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
#[Pure] public function __construct($message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message, 401, $previous);
}
+9 -1
View File
@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Snowflake\Exception;
use JetBrains\PhpStorm\Pure;
use Throwable;
/**
@@ -19,7 +20,14 @@ use Throwable;
class ComponentException extends \Exception
{
public function __construct(string $message = "", int $code = 0, Throwable $previous = NULL)
/**
* ComponentException constructor.
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
#[Pure] public function __construct(string $message = "", int $code = 0, Throwable $previous = NULL)
{
parent::__construct($message, 5000, $previous);
}
+4
View File
@@ -5,6 +5,10 @@ declare(strict_types=1);
namespace Snowflake\Exception;
/**
* Class ConfigException
* @package Snowflake\Exception
*/
class ConfigException extends \Exception
{
+4 -1
View File
@@ -4,7 +4,10 @@ declare(strict_types=1);
namespace Snowflake\Exception;
/**
* Class InitException
* @package Snowflake\Exception
*/
class InitException extends \Exception
{
+8 -1
View File
@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Snowflake\Exception;
use JetBrains\PhpStorm\Pure;
use Throwable;
/**
@@ -19,7 +20,13 @@ use Throwable;
class NotFindClassException extends \Exception
{
public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
/**
* NotFindClassException constructor.
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
#[Pure] public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
{
$message = "No class named `$message` was found, please check if the class name is correct";
parent::__construct($message, 404, $previous);
@@ -5,6 +5,10 @@ declare(strict_types=1);
namespace Snowflake\Exception;
/**
* Class RedisConnectException
* @package Snowflake\Exception
*/
class RedisConnectException extends \Exception
{
+25 -17
View File
@@ -10,9 +10,15 @@ use Snowflake\Abstracts\Config;
use Snowflake\Core\Str;
use Snowflake\Exception\AuthException;
use Snowflake\Abstracts\Component;
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException;
use Snowflake\Snowflake;
/**
* Class Jwt
* @package Snowflake\Jwt
*/
class Jwt extends Component
{
@@ -122,7 +128,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return array
* @throws Exception
*/
public function create(int $unionId, $headers = [])
public function create(int $unionId, $headers = []): array
{
$this->user = $unionId;
$this->config['time'] = time();
@@ -149,7 +155,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @throws Exception
* 对相关信息进行加密
*/
private function createEncrypt($unionId)
private function createEncrypt($unionId): array
{
$caches = $this->clear($unionId);
$param = $this->assembly(array_merge($this->config, [
@@ -182,7 +188,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return array
* @throws
*/
private function assembly(array $param, $update = FALSE)
private function assembly(array $param, $update = FALSE): array
{
if (isset($param['sign'])) {
unset($param['sign']);
@@ -205,7 +211,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return array
* @throws Exception
*/
public function refresh($headers = [])
public function refresh($headers = []): array
{
$this->data = $headers;
if (!openssl_public_decrypt(base64_decode($headers['refresh']), $data, $this->public)) {
@@ -226,9 +232,9 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
/**
* @param $param
*
* @return mixed
* @return array
*/
private function initialize(array $param)
private function initialize(array $param): array
{
$_param = [
'version' => '1',
@@ -270,7 +276,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return string
* @throws Exception
*/
private function authKey(string $_source, string $token)
private function authKey(string $_source, string $token): string
{
$source = $this->getSource();
if (!empty($_source)) $source = $_source;
@@ -283,7 +289,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
/**
* @return string
*/
public function getSource()
public function getSource(): string
{
return $this->data['source'] ?? 'browser';
}
@@ -295,7 +301,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
*
* @return string
*/
private function token(int $user, $param = [], $requestTime = NULL)
private function token(int $user, $param = [], $requestTime = NULL): string
{
$str = '';
@@ -318,7 +324,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return mixed
* 将字符串替换成指定格式
*/
private function preg(string $str)
private function preg(string $str): mixed
{
$preg = '/(\w{10})(\w{3})(\w{4})(\w{9})(\w{6})/';
return preg_replace($preg, '$1-$2-$3-$4-$5', $str);
@@ -329,7 +335,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return string[]
* @throws Exception
*/
public function clear(int $user)
public function clear(int $user): array
{
$this->user = $user;
$redis = $this->getRedis();
@@ -356,7 +362,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return bool
* @throws AuthException
*/
public function check(array $data, int $user)
public function check(array $data, int $user): bool
{
$this->data = $data;
$this->user = $user;
@@ -378,7 +384,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return mixed
* @throws
*/
public function getCurrentOnlineUser()
public function getCurrentOnlineUser(): mixed
{
$this->data = request()->headers->getHeaders();
$model = $this->getUserModel();
@@ -398,10 +404,12 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
/**
* @param array $header
* @return false|mixed
* @return mixed
* @throws AuthException
* @throws ComponentException
* @throws Exception
*/
public static function checkAuth(array $header = [])
public static function checkAuth(array $header = []): mixed
{
$instance = Snowflake::app()->getJwt();
if (empty($header)) {
@@ -435,7 +443,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @throws AuthException
* @throws Exception
*/
private function getUserModel()
private function getUserModel(): bool|array
{
if (!isset($this->data['token'])) {
throw new AuthException('暂无访问权限!');
@@ -448,7 +456,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY=
* @return Redis
* @throws Exception
*/
private function getRedis()
private function getRedis(): Redis
{
return Snowflake::app()->getRedis();
}
+14 -14
View File
@@ -105,7 +105,7 @@ class Connection extends Pool
*
* db is in transaction
*/
public function inTransaction($cds)
public function inTransaction($cds): bool
{
$coroutineName = $this->name($cds, true);
if (!Context::hasContext('begin_' . $coroutineName)) {
@@ -162,7 +162,7 @@ class Connection extends Pool
* @param false $isMaster
* @return array
*/
private function getIndex($name, $isMaster = false)
private function getIndex($name, $isMaster = false): array
{
return [Coroutine::getCid(), $this->name($name, $isMaster)];
}
@@ -197,7 +197,7 @@ class Connection extends Pool
* @return mixed
* @throws Exception
*/
public function getConnection(array $config, $isMaster = false)
public function getConnection(array $config, $isMaster = false): mixed
{
$coroutineName = $this->name($config['cds'], $isMaster);
if (!isset($this->hasCreate[$coroutineName])) {
@@ -222,7 +222,7 @@ class Connection extends Pool
* @param $client
* @return mixed
*/
private function saveClient($coroutineName, $client)
private function saveClient($coroutineName, $client): mixed
{
return Context::setContext($coroutineName, $client);
}
@@ -234,7 +234,7 @@ class Connection extends Pool
* @return PDO
* @throws Exception
*/
private function nowClient($coroutineName, $config)
private function nowClient($coroutineName, $config): PDO
{
$client = $this->createConnect($coroutineName, ...$this->parseConfig($config));
if ($number = Context::getContext('begin_' . $coroutineName, Coroutine::getCid())) {
@@ -251,7 +251,7 @@ class Connection extends Pool
* @param $config
* @return array
*/
private function parseConfig($config)
private function parseConfig($config): array
{
return [$config['cds'], $config['username'], $config['password'], $config['charset'] ?? 'utf8mb4'];
}
@@ -283,7 +283,7 @@ class Connection extends Pool
* @param $coroutineName
* @return bool
*/
private function hasClient($coroutineName)
private function hasClient($coroutineName): bool
{
return Context::hasContext($coroutineName);
}
@@ -323,19 +323,19 @@ class Connection extends Pool
/**
* @param $name
* @param $time
* @param $connect
* @param $client
* @return bool
*/
public function checkCanUse($name, $time, $connect)
public function checkCanUse($name, $time, $client): bool
{
try {
if ($time + 60 * 10 > time()) {
return $result = true;
}
if (empty($connect) || !($connect instanceof PDO)) {
if (empty($client) || !($client instanceof PDO)) {
return $result = false;
}
if (!$connect->getAttribute(PDO::ATTR_SERVER_INFO)) {
if (!$client->getAttribute(PDO::ATTR_SERVER_INFO)) {
return $result = false;
}
return $result = true;
@@ -358,7 +358,7 @@ class Connection extends Pool
* @return PDO
* @throws Exception
*/
public function createConnect($coroutineName, $cds, $username, $password, $charset = 'utf8mb4')
public function createConnect($coroutineName, $cds, $username, $password, $charset = 'utf8mb4'): PDO
{
try {
$link = new PDO($cds, $username, $password, [
@@ -408,9 +408,9 @@ class Connection extends Pool
}
/**
* @param $coroutineName
* @param string $coroutineName
*/
public function desc($coroutineName)
public function desc(string $coroutineName)
{
if (!isset($this->hasCreate[$coroutineName])) {
$this->hasCreate[$coroutineName] = 0;
+3 -11
View File
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace Snowflake\Pool;
use Snowflake\Cache\Memcached;
use JetBrains\PhpStorm\Pure;
use Snowflake\Snowflake;
/**
@@ -21,7 +21,7 @@ class Pool extends \Snowflake\Abstracts\Pool
/**
* @return Redis
*/
public function getRedis()
#[Pure] public function getRedis(): Redis
{
return Snowflake::app()->redis_connections;
}
@@ -29,18 +29,10 @@ class Pool extends \Snowflake\Abstracts\Pool
/**
* @return Connection
*/
public function getDb()
#[Pure] public function getDb(): Connection
{
return Snowflake::app()->connections;
}
/**
* @return Memcached
*/
public function getMemcached()
{
return Snowflake::app()->memcached;
}
}
+10 -9
View File
@@ -31,10 +31,11 @@ class Redis extends Pool
/**
* @param array $config
* @param bool $isMaster
* @return mixed|null
* @return mixed
* @throws RedisConnectException
* @throws Exception
*/
public function getConnection(array $config, $isMaster = false)
public function getConnection(array $config, $isMaster = false): mixed
{
$name = $config['host'] . ':' . $config['prefix'] . ':' . $config['databases'];
$coroutineName = $this->name('redis:' . $name, $isMaster);
@@ -53,7 +54,7 @@ class Redis extends Pool
* @return mixed
* @throws Exception
*/
public function getByChannel($coroutineName, $config)
public function getByChannel($coroutineName, $config): mixed
{
if (!$this->hasItem($coroutineName)) {
return $this->saveClient($coroutineName, $this->createConnect($config, $coroutineName));
@@ -72,7 +73,7 @@ class Redis extends Pool
* @return mixed
* @throws Exception
*/
private function saveClient($coroutineName, $client)
private function saveClient($coroutineName, $client): mixed
{
return Context::setContext($coroutineName, $client);
}
@@ -84,7 +85,7 @@ class Redis extends Pool
* @return SRedis
* @throws RedisConnectException
*/
private function createConnect(array $config, string $coroutineName)
private function createConnect(array $config, string $coroutineName): SRedis
{
$redis = new SRedis();
if (!$redis->connect($config['host'], (int)$config['port'], $config['timeout'])) {
@@ -139,7 +140,7 @@ class Redis extends Pool
/**
* @param $coroutineName
*/
public function remove($coroutineName)
public function remove(string $coroutineName)
{
Context::deleteId($coroutineName);
}
@@ -148,10 +149,10 @@ class Redis extends Pool
* @param $name
* @param $time
* @param $client
* @return bool|mixed
* @return bool
* @throws Exception
*/
public function checkCanUse($name, $time, $client)
public function checkCanUse(string $name, int $time, mixed $client): bool
{
try {
if ($time + 60 * 10 < time()) {
@@ -173,7 +174,7 @@ class Redis extends Pool
}
}
public function desc($name)
public function desc(string $name)
{
// TODO: Implement desc() method.
}
+5 -5
View File
@@ -23,7 +23,7 @@ use Swoole\Timer;
*/
class ServerInotify extends Process
{
private $inotify;
private mixed $inotify;
private bool $isReloading = false;
private bool $isReloadingOut = false;
private array $watchFiles = [];
@@ -80,10 +80,10 @@ class ServerInotify extends Process
/**
* @param $path
* @param bool $isReload
* @return void|mixed
* @return mixed
* @throws Exception
*/
private function loadByDir($path, $isReload = false)
private function loadByDir($path, $isReload = false): mixed
{
$path = rtrim($path, '/');
foreach (glob(realpath($path) . '/*') as $value) {
@@ -105,7 +105,7 @@ class ServerInotify extends Process
* @param $isReload
* @return bool
*/
private function checkFile($value, $isReload)
private function checkFile($value, $isReload): bool
{
$md5 = md5($value);
$mTime = filectime($value);
@@ -243,7 +243,7 @@ class ServerInotify extends Process
* @return bool
* @throws Exception
*/
public function watch($dir)
public function watch($dir): bool
{
//目录不存在
if (!is_dir($dir)) {
+9 -4
View File
@@ -25,6 +25,11 @@ defined('PARAMS_IS_NULL') or define('PARAMS_IS_NULL', 'Required items cannot be
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
* @package Snowflake
*/
class Snowflake
{
@@ -135,7 +140,7 @@ class Snowflake
/**
* @param $workerId
* @return false|int|mixed
* @return mixed
* @throws Exception
*/
public static function setProcessId($workerId): mixed
@@ -146,7 +151,7 @@ class Snowflake
/**
* @param $workerId
* @return false|int|mixed
* @return mixed
* @throws Exception
*/
public static function setWorkerId($workerId): mixed
@@ -314,7 +319,7 @@ class Snowflake
/**
* @return bool
*/
public static function isMac()
#[Pure] public static function isMac(): bool
{
$output = strtolower(PHP_OS | PHP_OS_FAMILY);
if (str_contains('mac', $output)) {
@@ -329,7 +334,7 @@ class Snowflake
/**
* @return bool
*/
public static function isLinux(): bool
#[Pure] public static function isLinux(): bool
{
if (!static::isMac()) {
return true;