This commit is contained in:
2020-08-31 01:27:08 +08:00
parent d6d4027b0d
commit e4f01d9499
119 changed files with 12232 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace Snowflake\Abstracts;
/**
* Class BaseAnnotation
* @package BeReborn\Annotation\Base
*/
abstract class BaseAnnotation extends Component
{
public function each()
{
}
}
+251
View File
@@ -0,0 +1,251 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/10/7 0007
* Time: 2:13
*/
namespace Snowflake\Abstracts;
use Exception;
use HttpServer\Http\Request;
use HttpServer\Http\Response;
use HttpServer\Route\Router;
use HttpServer\Server;
use Snowflake\Annotation\Annotation;
use Snowflake\Config;
use Snowflake\Di\Service;
use Snowflake\Error\ErrorHandler;
use Snowflake\Error\Logger;
use Snowflake\Exception\ComponentException;
use Snowflake\Pool\Connection;
use Snowflake\Pool\RedisClient;
use Snowflake\Processes;
use Snowflake\Snowflake;
use Snowflake\Event;
/**
* Class BaseApplication
* @package BeReborn\Base
* @property $json
* @property Annotation $annotation
* @property Event $event
* @property Router $router
* @property Processes $processes
* @property \Snowflake\Pool\Pool $pool
* @property Server $servers
* @property Connection $connections
*/
abstract class BaseApplication extends Service
{
/**
* @var string
*/
public $storage = APP_PATH . '/storage';
public $envPath = APP_PATH . '/.env';
/**
* Init constructor.
*
* @param array $config
*
* @throws
*/
public function __construct(array $config = [])
{
Snowflake::init($this);
$this->moreComponents();
$this->parseInt($config);
$this->initErrorHandler();
$this->enableEnvConfig();
Component::__construct($config);
}
/**
* @return mixed
*/
public function enableEnvConfig()
{
if (!file_exists($this->envPath)) {
return [];
}
$lines = $this->readLinesFromFile($this->envPath);
foreach ($lines as $line) {
if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
[$key, $value] = explode('=', $line);
putenv(trim($key) . '=' . trim($value));
}
}
return $lines;
}
/**
* Read lines from the file, auto detecting line endings.
*
* @param string $filePath
*
* @return array
*/
protected function readLinesFromFile($filePath)
{
// Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect);
return $lines;
}
/**
* Determine if the line in the file is a comment, e.g. begins with a #.
*
* @param string $line
*
* @return bool
*/
protected function isComment($line)
{
$line = ltrim($line);
return isset($line[0]) && $line[0] === '#';
}
/**
* Determine if the given line looks like it's setting a variable.
*
* @param string $line
*
* @return bool
*/
protected function looksLikeSetter($line)
{
return strpos($line, '=') !== false;
}
/**
* @param $config
*
* @throws
*/
public function parseInt($config)
{
foreach ($config as $key => $value) {
Config::set($key, $value);
}
// if (isset($config['id'])) {
// $this->id = $config['id'];
// unset($config['id']);
// }
// if (isset($config['storage'])) {
// $this->storage = $config['storage'];
// unset($config['storage']);
// }
// if (!empty($this->runtimePath)) {
// if (!is_dir($this->runtimePath)) {
// mkdir($this->runtimePath, 777);
// }
//
// if (!is_dir($this->runtimePath) || !is_writeable($this->runtimePath)) {
// throw new InitException("Directory {$this->runtimePath} does not have write permission");
// }
// }
// if (isset($config['aliases'])) {
// $this->classAlias($config);
// }
//
// foreach ($this->moreComponents() as $key => $val) {
// if (isset($config['components'][$key])) {
// $config['components'][$key] = array_merge($val, $config['components'][$key]);
// } else {
// $config['components'][$key] = $val;
// }
// }
}
/**
* @param array $data
*/
private function classAlias(array &$data)
{
foreach ($data['aliases'] as $key => $val) {
class_alias($val, $key, true);
}
unset($data['aliases']);
}
/**
* @param $name
* @return mixed
* @throws ComponentException
*/
public function clone($name)
{
return clone $this->get($name);
}
/**
*
* @throws Exception
*/
public function initErrorHandler()
{
$this->get('error')->register();
}
/**
* @return mixed
*/
public function getLocalIps()
{
return swoole_get_local_ip();
}
/**
* @return mixed
*/
public function getFirstLocal()
{
return current($this->getLocalIps());
}
/**
* @param $ip
* @return bool
*/
public function isLocal($ip)
{
return $this->getFirstLocal() == $ip;
}
/**
* @throws Exception
*/
protected function moreComponents()
{
return $this->setComponents([
'error' => ['class' => ErrorHandler::class],
'event' => ['class' => Event::class],
'annotation' => ['class' => Annotation::class],
'processes' => ['class' => Processes::class],
'connections' => ['class' => Connection::class],
'redis_connections' => ['class' => RedisClient::class],
'pool' => ['class' => \Snowflake\Pool\Pool::class],
'response' => ['class' => Response::class],
'request' => ['class' => Request::class],
'config' => ['class' => Config::class],
'logger' => ['class' => Logger::class],
'router' => ['class' => Router::class],
]);
}
}
+211
View File
@@ -0,0 +1,211 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/30 0030
* Time: 14:10
*/
namespace Snowflake\Abstracts;
use Exception;
use Snowflake\Error\Logger;
use Snowflake\Snowflake;
/**
* Class BaseObject
* @method defer()
* @package BeReborn\Base
* @method afterInit
* @method initialization
*/
class BaseObject implements Configure
{
/**
* BaseAbstract constructor.
*
* @param array $config
*/
public function __construct($config = [])
{
// if (!empty($config) && is_array($config)) {
// Snowflake::configure($this, $config);
// }
$this->init();
}
public function init()
{
}
/**
* @return string
*/
public static function className()
{
return get_called_class();
}
/**
* @param $name
* @param $value
*
* @throws Exception
*/
public function __set($name, $value)
{
$method = 'set' . ucfirst($name);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
$this->error('set ' . $name . ' not exists ' . get_called_class());
throw new Exception('The set name ' . $name . ' not find in class ' . get_class($this));
}
}
/**
* @param $name
*
* @return mixed
* @throws Exception
*/
public function __get($name)
{
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method();
} else {
throw new Exception('The get name ' . $name . ' not find in class ' . get_class($this));
}
}
/**
* @param $name
* @param $arguments
*
* @return mixed
* @throws Exception
*/
public function __call($name, $arguments)
{
if (!method_exists($this, $name)) {
throw new Exception("Not find " . get_called_class() . "::($name)");
} else {
$result = $this->$name(...$arguments);
if (method_exists($this, 'defer')) {
$this->defer();
}
return $result;
}
}
/**
* @param $message
* @param string $model
* @return bool
* @throws Exception
*/
public function addError($message, $model = 'app')
{
if ($message instanceof Exception) {
$this->error($message->getMessage(), $message->getFile(), $message->getLine());
} else {
if (!is_string($message)) {
$message = json_encode($message, JSON_UNESCAPED_UNICODE);
}
$this->error($message);
}
return FALSE;
}
/**
* @param string $message
* @param string $method
* @param string $file
* @throws
*/
public function debug($message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
}
echo "\033[35m[DEBUG][" . date('Y-m-d H:i:s') . ']: ' . $message . "\033[0m";
echo PHP_EOL;
Logger::trance($message, 'debug');
}
/**
* @param string $message
* @param string $method
* @param string $file
* @throws
*/
public function info($message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
}
echo "\033[34m[INFO][" . date('Y-m-d H:i:s') . ']: ' . $message . "\033[0m";
echo PHP_EOL;
Logger::trance($message, 'info');
}
/**
* @param string $message
* @param string $method
* @param string $file
* @throws
*/
public function success($message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
}
echo "\033[36m[SUCCESS][" . date('Y-m-d H:i:s') . ']: ' . $message . "\033[0m";
echo PHP_EOL;
Logger::trance($message, 'success');
}
/**
* @param string $message
* @param string $method
* @param string $file
* @throws
*/
public function warning($message, string $method = __METHOD__, string $file = __FILE__)
{
if (!is_string($message)) {
$message = print_r($message, true);
}
echo "\033[33m[SUCCESS][" . date('Y-m-d H:i:s') . ']: ' . $message . "\033[0m";
echo PHP_EOL;
Logger::trance($message, 'warning');
}
/**
* @param string $message
* @param string|null $method
* @param string|null $file
* @throws Exception
*/
public function error($message, string $method = null, string $file = null)
{
if (!empty($file)) {
echo "\033[41;37m[ERROR][" . date('Y-m-d H:i:s') . ']: ' . $file . "\033[0m";
echo PHP_EOL;
}
if (!is_string($message)) {
$message = print_r($message, true);
}
echo "\033[41;37m[ERROR][" . date('Y-m-d H:i:s') . ']: ' . (empty($method) ? '' : $method . ': ') . $message . "\033[0m";
echo PHP_EOL;
Logger::error($message, 'error');
}
}
+145
View File
@@ -0,0 +1,145 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/30 0030
* Time: 14:28
*/
namespace Snowflake\Abstracts;
use Exception;
/**
* Class Component
* @package BeReborn\Base
*/
class Component extends BaseObject
{
/**
* @var array
*/
private $_events = [];
/**
* @param $name [事件名称]
* @param $callback [回调函数]
* @param array $param [函数参数]
*
* {
* 事件名, 回调, 参数
* }
*/
public function on($name, $callback, $param = [])
{
if (isset($this->_events[$name])) {
array_push($this->_events[$name], [$callback, $param]);
} else {
$this->_events[$name][] = [$callback, $param];
}
}
/**
* @param $name
* @param null $callback
* @return bool
*/
public function hasEvent($name, $callback = null)
{
if (!isset($this->_events[$name])) {
return false;
}
if (!is_array($this->_events[$name])) {
return false;
}
foreach ($this->_events[$name] as $event) {
[$_callback, $param] = $event;
if ($_callback === $callback) {
return true;
}
}
return false;
}
/**
* @param $name
* @param null $event
* @param array $params
* @param bool $isRemove
* @throws Exception
*/
public function trigger($name, $event = null, $params = [], $isRemove = false)
{
if (isset($this->_events[$name])) {
$events = $this->_events[$name];
foreach ($events as $key => $_event) {
if (!empty($event)) {
$_event = $event;
}
call_user_func($_event, ...$params);
if ($isRemove) {
unset($this->_events[$name][$key]);
of($name, $_event);
}
}
}
fire($name, $event);
}
/**
* @param $name
* @param null $handler
* @return mixed
*/
public function off($name, $handler = NULL)
{
if (!isset($this->_events[$name])) {
return of($name, $handler);
}
if (empty($handler)) {
unset($this->_events[$name]);
return of($name, $handler);
}
foreach ($this->_events[$name] as $key => $val) {
if ($val[0] != $handler) {
continue;
}
unset($this->_events[$name][$key]);
break;
}
return of($name, $handler);
}
/**
*/
public function offAll()
{
$this->_events = [];
ofAll();
}
/**
* @param $name
* @return mixed
* @throws Exception
*/
public function __get($name)
{
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method();
} else if (property_exists($this, $name)) {
return $this->$name ?? null;
} else {
return parent::__get($name);
}
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/5/24 0024
* Time: 11:50
*/
namespace Snowflake;
use Exception;
use Snowflake\Exception\ConfigException;
use Snowflake\Abstracts\Component;
/**
* Class Config
* @package BeReborn\Base
*/
class Config extends Component
{
const ERROR_MESSAGE = 'The not find :key in app configs.';
public $data;
/**
* @param $key
* @param bool $try
* @param mixed $default
* @return null
* @throws
*/
public static function get($key, $try = FALSE, $default = null)
{
$config = Snowflake::get()->config;
if (isset($config->data[$key])) {
return $config->data[$key];
} else if ($default !== null) {
return $default;
} else if ($try) {
throw new ConfigException(str_replace(':key', $key, self::ERROR_MESSAGE));
}
return NULL;
}
/**
* @param $key
* @param $value
* @return mixed
* @throws Exception
*/
public static function set($key, $value)
{
$config = Snowflake::get()->config;
return $config->data[$key] = $value;
}
/**
* @param $key
* @param bool $must_not_null
* @return bool
*/
public static function has($key, $must_not_null = false)
{
$config = Snowflake::get()->config;
if (!isset($config->data[$key])) {
return false;
}
$config = $config->data[$key];
if ($must_not_null === false) {
return true;
}
return !empty($config);
}
/**
* @param $name
* @param $value
*/
public function __set($name, $value)
{
$this->data[$name] = $value;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/30 0030
* Time: 14:11
*/
namespace Snowflake\Abstracts;
/**
* Interface Configure
* @package BeReborn\Base
*/
interface Configure
{
}
+156
View File
@@ -0,0 +1,156 @@
<?php
namespace Snowflake\Abstracts;
use Exception;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
/**
* Class Pool
* @package BeReborn\Pool
*/
abstract class Pool extends Component
{
/** @var Channel[] */
private $_items = [];
public $max = 60;
private $is_ticker = false;
/**
* @param $name
* @param false $isMaster
* @param int $max
*/
public function initConnections($name, $isMaster = false, $max = 60)
{
$name = $this->name($name, $isMaster);
if (isset($this->_items[$name]) &&
$this->_items[$name] instanceof Channel) {
return;
}
$this->_items[$name] = new Channel($max);
}
/**
* @param $name
* @param int $timeout
* @return mixed
*/
protected function get($name, $timeout = -1)
{
if ($this->is_ticker) {
Coroutine::sleep(1);
}
if ($timeout != -1) {
$client = $this->_items[$name]->pop($timeout);
} else {
$client = $this->_items[$name]->pop(60);
}
if (!$this->checkCanUse(...$client)) {
unset($client);
return [0, null];
} else {
return $client;
}
}
/**
* @param $cds
* @param false $isMaster
* @return string
*/
public function name($cds, $isMaster = false)
{
return hash('sha1', $cds . ($isMaster ? 'master' : 'slave'));
}
/**
* @param $time
* @param $client
* @return mixed
* 检查连接可靠性
* @throws Exception
*/
public function checkCanUse($time, $client)
{
throw new Exception('Undefined system processing function.');
}
/**
* @param $name
* @throws Exception
*/
public function desc($name)
{
throw new Exception('Undefined system processing function.');
}
/**
* @param array $config
* @param $isMaster
* @throws Exception
*/
public function getConnection(array $config, $isMaster)
{
throw new Exception('Undefined system processing function.');
}
/**
* @param $name
* @return mixed
*/
public function hasItem($name)
{
return $this->hasLength($name) > 0;
}
/**
* @param $name
* @return mixed
*/
public function hasLength($name)
{
if (!isset($this->_items[$name])) {
return 0;
}
return $this->_items[$name]->length();
}
/**
* @param $name
* @param $client
*/
public function push($name, $client)
{
if (!isset($this->_items[$name])) {
return;
}
if (!$this->_items[$name]->isFull()) {
$this->_items[$name]->push([time(), $client]);
}
}
/**
* @param $name
*/
public function clean($name)
{
if (!isset($this->_items[$name])) {
return;
}
while ([$time, $client] = $this->_items[$name]->pop(0.001)) {
unset($client);
}
}
}