This commit is contained in:
as2252258@163.com
2021-03-28 16:09:18 +08:00
parent 7ea7b1e36e
commit 86e8ad68e9
11 changed files with 1341 additions and 1145 deletions
+232 -232
View File
@@ -24,280 +24,280 @@ class Loader extends BaseObject
{ {
private array $_classes = []; private array $_classes = [];
private array $_fileMap = []; private array $_fileMap = [];
private array $_directoryMap = []; private array $_directoryMap = [];
/** /**
* @param $path * @param $path
* @param $namespace * @param $namespace
* @throws Exception * @throws Exception
*/ */
public function loader($path, $namespace) public function loader($path, $namespace)
{ {
$this->_scanDir(new DirectoryIterator($path), $namespace); $this->_scanDir(new DirectoryIterator($path), $namespace);
} }
/** /**
* @return array * @return array
*/ */
public function getClasses(): array public function getClasses(): array
{ {
return $this->_classes; return $this->_classes;
} }
/** /**
* @param string $class * @param string $class
* @param string $property * @param string $property
* @return mixed * @return mixed
*/ */
public function getProperty(string $class, string $property = ''): mixed public function getProperty(string $class, string $property = ''): mixed
{ {
if (!isset($this->_classes[$class])) { if (!isset($this->_classes[$class])) {
return null; return null;
} }
$properties = $this->_classes[$class]['property']; $properties = $this->_classes[$class]['property'];
if (!empty($property) && isset($properties[$property])) { if (!empty($property) && isset($properties[$property])) {
return $properties[$property]; return $properties[$property];
} }
return $properties; return $properties;
} }
/** /**
* @param string $class * @param string $class
* @param mixed $handler * @param mixed $handler
* @return Loader * @return Loader
*/ */
public function injectProperty(string $class, object $handler): static public function injectProperty(string $class, object $handler): static
{ {
$properties = $this->getProperty($class); $properties = $this->getProperty($class);
if (empty($properties)) { if (empty($properties)) {
return $this; return $this;
} }
foreach ($properties as $property => $attributes) { foreach ($properties as $property => $attributes) {
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {
$attribute->execute([$handler, $property]); $attribute->execute([$handler, $property]);
} }
} }
return $this; return $this;
} }
/** /**
* @param string $class * @param string $class
* @param string $method * @param string $method
* @return mixed * @return mixed
*/ */
public function getMethod(string $class, string $method = ''): array public function getMethod(string $class, string $method = ''): array
{ {
if (!isset($this->_classes[$class])) { if (!isset($this->_classes[$class])) {
return []; return [];
} }
$properties = $this->_classes[$class]['methods']; $properties = $this->_classes[$class]['methods'];
if (!empty($method) && isset($properties[$method])) { if (!empty($method) && isset($properties[$method])) {
return $properties[$method]; return $properties[$method];
} }
return $properties; return $properties;
} }
/** /**
* @param string $class * @param string $class
* @return array * @return array
*/ */
public function getTarget(string $class): array public function getTarget(string $class): array
{ {
return $this->_classes[$class] ?? []; return $this->_classes[$class] ?? [];
} }
/** /**
* @param DirectoryIterator $paths * @param DirectoryIterator $paths
* @param $namespace * @param $namespace
* @throws Exception * @throws Exception
*/ */
public function _scanDir(DirectoryIterator $paths, $namespace) public function _scanDir(DirectoryIterator $paths, $namespace)
{ {
$DIRECTORY = $this->createDirectoryMap($paths); /** @var DirectoryIterator $path */
foreach ($paths as $path) { $DIRECTORY = $this->createDirectoryMap($paths);
if ($path->getFilename() === '.' || $path->getFilename() === '..') { foreach ($paths as $path) {
continue; if ($path->isDot()) continue;
}
if (str_starts_with($path->getFilename(), '.')) {
continue;
}
if ($path->isDir()) {
$this->_scanDir(new DirectoryIterator($path->getRealPath()), $namespace);
continue;
}
if ($path->getExtension() !== 'php') { if (str_starts_with($path->getFilename(), '.')) {
continue; continue;
} }
if ($path->isDir()) {
$this->_scanDir(new DirectoryIterator($path->getRealPath()), $namespace);
continue;
}
if (!in_array($path->getRealPath(), $this->_directoryMap[$DIRECTORY])) { if ($path->getExtension() !== 'php') {
$this->_directoryMap[$DIRECTORY][] = $path->getRealPath(); continue;
} }
try { if (!in_array($path->getRealPath(), $this->_directoryMap[$DIRECTORY])) {
$replace = Snowflake::getDi()->getReflect($this->explodeFileName($path, $namespace)); $this->_directoryMap[$DIRECTORY][] = $path->getRealPath();
if (empty($replace) || !$replace->isInstantiable()) { }
continue;
}
if (!$replace->getAttributes(Target::class)) { try {
continue; $replace = Snowflake::getDi()->getReflect($this->explodeFileName($path, $namespace));
} if (empty($replace) || !$replace->isInstantiable()) {
continue;
}
$_array = ['handler' => $replace->newInstanceWithoutConstructor(), 'target' => [], 'methods' => [], 'property' => []]; if (!$replace->getAttributes(Target::class)) {
foreach ($replace->getAttributes() as $attribute) { continue;
if ($attribute->getName() == Attribute::class) { }
continue;
}
$_array['target'][] = $attribute->newInstance();
}
$methods = $replace->getMethods(ReflectionMethod::IS_PUBLIC); $_array = ['handler' => $replace->newInstanceWithoutConstructor(), 'target' => [], 'methods' => [], 'property' => []];
foreach ($methods as $method) { foreach ($replace->getAttributes() as $attribute) {
$_method = []; if ($attribute->getName() == Attribute::class) {
foreach ($method->getAttributes() as $attribute) { continue;
if (!class_exists($attribute->getName())) { }
continue; $_array['target'][] = $attribute->newInstance();
} }
$_method[] = $attribute->newInstance();
}
$_array['methods'][$method->getName()] = $_method;
}
$methods = $replace->getProperties(); $methods = $replace->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) { foreach ($methods as $method) {
$_property = []; $_method = [];
if ($method->isStatic()) continue; foreach ($method->getAttributes() as $attribute) {
foreach ($method->getAttributes() as $attribute) { if (!class_exists($attribute->getName())) {
if (!class_exists($attribute->getName())) { continue;
continue; }
} $_method[] = $attribute->newInstance();
$property = $attribute->newInstance(); }
if ($property instanceof Inject) { $_array['methods'][$method->getName()] = $_method;
$property->execute([$_array['handler'], $method]); }
} else {
$_property[] = $attribute->newInstance();
}
}
$_array['property'][$method->getName()] = $_property;
}
$this->_fileMap[$replace->getFileName()] = $replace->getName(); $methods = $replace->getProperties();
foreach ($methods as $method) {
$_property = [];
if ($method->isStatic()) continue;
foreach ($method->getAttributes() as $attribute) {
if (!class_exists($attribute->getName())) {
continue;
}
$property = $attribute->newInstance();
if ($property instanceof Inject) {
$property->execute([$_array['handler'], $method]);
} else {
$_property[] = $attribute->newInstance();
}
}
$_array['property'][$method->getName()] = $_property;
}
$this->_fileMap[$replace->getFileName()] = $replace->getName();
$this->_classes[$replace->getName()] = $_array; $this->_classes[$replace->getName()] = $_array;
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
$this->error($throwable->getMessage()); $this->error($throwable->getMessage());
$this->error($throwable->getFile()); $this->error($throwable->getFile());
$this->error($throwable->getLine()); $this->error($throwable->getLine());
} }
} }
} }
/** /**
* @param string $path * @param string $path
*/ */
public function loadByDirectory(string $path) public function loadByDirectory(string $path)
{ {
foreach ($this->_fileMap as $fileName => $className) { foreach ($this->_fileMap as $fileName => $className) {
if (!str_starts_with($fileName, $path)) { if (!str_starts_with($fileName, $path)) {
continue; continue;
} }
if (!isset($this->_classes[$className])) { if (!isset($this->_classes[$className])) {
continue; continue;
} }
$annotations = $this->_classes[$className]; $annotations = $this->_classes[$className];
if (isset($annotations['target']) && !empty($annotations['target'])) { if (isset($annotations['target']) && !empty($annotations['target'])) {
foreach ($annotations['target'] as $value) { foreach ($annotations['target'] as $value) {
$value->execute([$annotations['handler']]); $value->execute([$annotations['handler']]);
} }
} }
foreach ($annotations['methods'] as $name => $attribute) { foreach ($annotations['methods'] as $name => $attribute) {
foreach ($attribute as $value) { foreach ($attribute as $value) {
if (!($value instanceof \Annotation\Attribute)) { if (!($value instanceof \Annotation\Attribute)) {
continue; continue;
} }
$value->execute([$annotations['handler'], $name]); $value->execute([$annotations['handler'], $name]);
} }
} }
} }
} }
/** /**
* @param DirectoryIterator $path * @param DirectoryIterator $path
* @param string $namespace * @param string $namespace
* @return string * @return string
*/ */
private function explodeFileName(DirectoryIterator $path, string $namespace): string private function explodeFileName(DirectoryIterator $path, string $namespace): string
{ {
$replace = str_replace(APP_PATH . 'app', '', $path->getRealPath()); $replace = str_replace(APP_PATH . 'app', '', $path->getRealPath());
$replace = str_replace('.php', '', $replace); $replace = str_replace('.php', '', $replace);
$replace = str_replace(DIRECTORY_SEPARATOR, '\\', $replace); $replace = str_replace(DIRECTORY_SEPARATOR, '\\', $replace);
$explode = explode('\\', $replace); $explode = explode('\\', $replace);
array_shift($explode); array_shift($explode);
return $namespace . '\\' . implode('\\', $explode); return $namespace . '\\' . implode('\\', $explode);
} }
/** /**
* @param DirectoryIterator $directoryIterator * @param DirectoryIterator $directoryIterator
* @return string * @return string
*/ */
public function createDirectoryMap(DirectoryIterator $directoryIterator): string public function createDirectoryMap(DirectoryIterator $directoryIterator): string
{ {
$DIRECTORY = explode(DIRECTORY_SEPARATOR, $directoryIterator->getRealPath()); $DIRECTORY = explode(DIRECTORY_SEPARATOR, $directoryIterator->getRealPath());
array_pop($DIRECTORY); array_pop($DIRECTORY);
$DIRECTORY = implode(DIRECTORY_SEPARATOR, $DIRECTORY); $DIRECTORY = implode(DIRECTORY_SEPARATOR, $DIRECTORY);
if (!isset($this->_directoryMap[$DIRECTORY])) { if (!isset($this->_directoryMap[$DIRECTORY])) {
$this->_directoryMap[$DIRECTORY] = []; $this->_directoryMap[$DIRECTORY] = [];
} }
return $DIRECTORY; return $DIRECTORY;
} }
/** /**
* @param string $Directory * @param string $Directory
* @return array * @return array
*/ */
public function getDirectoryFiles(string $Directory): array public function getDirectoryFiles(string $Directory): array
{ {
if (!isset($this->_directoryMap[$Directory])) { if (!isset($this->_directoryMap[$Directory])) {
return []; return [];
} }
return $this->_directoryMap[$Directory]; return $this->_directoryMap[$Directory];
} }
/** /**
* @param string $filename * @param string $filename
* @return mixed * @return mixed
*/ */
public function getClassByFilepath(string $filename): mixed public function getClassByFilepath(string $filename): mixed
{ {
if (!isset($this->_fileMap[$filename])) { if (!isset($this->_fileMap[$filename])) {
return null; return null;
} }
return $this->_classes[$this->_fileMap[$filename]]; return $this->_classes[$this->_fileMap[$filename]];
} }
} }
-2
View File
@@ -36,8 +36,6 @@ abstract class Callback extends HttpService
protected function clear(Server $server, $worker_id, $message) protected function clear(Server $server, $worker_id, $message)
{ {
try { try {
Snowflake::clearProcessId($server->worker_pid);
/** @var Process $logger */ /** @var Process $logger */
$logger = Snowflake::app()->get(LoggerProcess::class); $logger = Snowflake::app()->get(LoggerProcess::class);
$logger->write(Json::encode([$this->_MESSAGE[$message] . $worker_id, 'app'])); $logger->write(Json::encode([$this->_MESSAGE[$message] . $worker_id, 'app']));
+27 -30
View File
@@ -5,12 +5,8 @@ namespace HttpServer;
use Exception; use Exception;
use ReflectionException;
use Snowflake\Abstracts\Input; use Snowflake\Abstracts\Input;
use Snowflake\Event;
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException; use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindPropertyException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
/** /**
@@ -20,40 +16,41 @@ use Snowflake\Snowflake;
class Command extends \Console\Command class Command extends \Console\Command
{ {
public string $command = 'sw:server'; public string $command = 'sw:server';
public string $description = 'server start|stop|reload|restart'; public string $description = 'server start|stop|reload|restart';
const ACTIONS = ['start', 'stop', 'restart']; const ACTIONS = ['start', 'stop', 'restart'];
/** /**
* @param Input $dtl * @param Input $dtl
* @return string * @return string
* @throws Exception * @throws Exception
* @throws ConfigException * @throws ConfigException
*/ */
public function onHandler(Input $dtl): string public function onHandler(Input $dtl): string
{ {
$manager = Snowflake::app()->getServer(); $manager = Snowflake::app()->getServer();
$manager->setDaemon($dtl->get('daemon', 0)); $manager->setDaemon($dtl->get('daemon', 0));
if (!in_array($dtl->get('action'), self::ACTIONS)) { if (!in_array($dtl->get('action'), self::ACTIONS)) {
return 'I don\'t know what I want to do.'; return 'I don\'t know what I want to do.';
} }
if ($manager->isRunner() && $dtl->get('action') == 'start') { /** @var Shutdown $shutdown */
return 'Service is running. Please use restart.'; $shutdown = Snowflake::app()->get('shutdown');
} if ($shutdown->isRunning() && $dtl->get('action') == 'start') {
return 'Service is running. Please use restart.';
}
$manager->shutdown(); $shutdown->shutdown();
if ($dtl->get('action') == 'stop') { if ($dtl->get('action') == 'stop') {
return 'shutdown success.'; return 'shutdown success.';
} }
return $manager->start();
return $manager->start(); }
}
} }
+3
View File
@@ -26,6 +26,9 @@ class OnBeforeReload extends Callback
{ {
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
$event->trigger(Event::SERVER_BEFORE_RELOAD, [$server]); $event->trigger(Event::SERVER_BEFORE_RELOAD, [$server]);
Snowflake::clearWorkerPid();
Snowflake::clearTaskPid();
} }
} }
+3 -1
View File
@@ -69,7 +69,9 @@ class OnWorkerStart extends Callback
{ {
putenv('environmental=' . Snowflake::TASK); putenv('environmental=' . Snowflake::TASK);
fire(Event::SERVER_TASK_START); Snowflake::setTaskId($server->worker_pid);
fire(Event::SERVER_TASK_START);
} }
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace HttpServer;
use Exception;
use Snowflake\Abstracts\Component;
/**
* Class Shutdown
* @package HttpServer
*/
class Shutdown extends Component
{
private string $taskDirectory;
private string $workerDirectory;
private string $managerDirectory;
private string $processDirectory;
public function init()
{
$this->taskDirectory = storage(null, 'pid/task');
$this->workerDirectory = storage(null, 'pid/worker');
$this->managerDirectory = storage(null, 'pid/manager');
$this->processDirectory = storage(null, 'pid/process');
}
/**
* @throws Exception
*/
public function shutdown(): void
{
$master_pid = Server()->setting['pid_file'] ?? PID_PATH;
clearstatcache($master_pid);
if (file_exists($master_pid)) {
$this->close($master_pid);
}
$this->closeOther();
}
/**
* 关闭其他进程
*/
private function closeOther(): void
{
$this->directoryCheck($this->managerDirectory);
$this->directoryCheck($this->taskDirectory);
$this->directoryCheck($this->workerDirectory);
$this->directoryCheck($this->processDirectory);
}
/**
* @return bool
* @throws Exception
* check server is running.
*/
public function isRunning()
{
$master_pid = Server()->setting['pid_file'] ?? PID_PATH;
return $this->pidIsExists($master_pid);
}
/**
* @param $content
* @return bool
*/
public function pidIsExists($content): bool
{
$content = shell_exec('ps -eo pid,cmd,state | grep ' . $content . ' | grep -v grep');
if (empty($content)) {
return false;
}
return true;
}
/**
* @param string $path
*/
public function directoryCheck(string $path)
{
$dir = new \DirectoryIterator($path);
if ($dir->getSize() < 1) {
return true;
}
foreach ($dir as $value) {
/** @var \DirectoryIterator $value */
if (!$value->valid()) continue;
$this->close($value->getRealPath());
}
return false;
}
/**
* @param string $value
*/
public function close(string $value)
{
$resource = fopen($value, 'r');
$content = fgets($resource);
fclose($resource);
while ($this->pidIsExists($content)) {
exec('kill -15 ' . $content);
sleep(1);
}
@unlink($value);
}
}
+435 -433
View File
@@ -22,6 +22,7 @@ use HttpServer\Service\Http;
use HttpServer\Service\Packet; use HttpServer\Service\Packet;
use HttpServer\Service\Receive; use HttpServer\Service\Receive;
use HttpServer\Service\Websocket; use HttpServer\Service\Websocket;
use HttpServer\Shutdown;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Kafka\Producer; use Kafka\Producer;
use Annotation\Annotation as SAnnotation; use Annotation\Annotation as SAnnotation;
@@ -51,437 +52,438 @@ use Swoole\Table;
abstract class BaseApplication extends Service abstract class BaseApplication extends Service
{ {
use TraitApplication; use TraitApplication;
/** /**
* @var string * @var string
*/ */
public string $storage = APP_PATH . 'storage'; public string $storage = APP_PATH . 'storage';
public string $envPath = APP_PATH . '.env'; public string $envPath = APP_PATH . '.env';
/** /**
* Init constructor. * Init constructor.
* *
* @param array $config * @param array $config
* *
* @throws * @throws
*/ */
public function __construct(array $config = []) public function __construct(array $config = [])
{ {
Snowflake::init($this); Snowflake::init($this);
$this->moreComponents(); $this->moreComponents();
$this->parseInt($config); $this->parseInt($config);
$this->parseEvents($config); $this->parseEvents($config);
$this->initErrorHandler(); $this->initErrorHandler();
$this->enableEnvConfig(); $this->enableEnvConfig();
parent::__construct($config); parent::__construct($config);
} }
/** /**
* @return array * @return array
*/ */
public function enableEnvConfig(): array public function enableEnvConfig(): array
{ {
if (!file_exists($this->envPath)) { if (!file_exists($this->envPath)) {
return []; return [];
} }
$lines = $this->readLinesFromFile($this->envPath); $lines = $this->readLinesFromFile($this->envPath);
foreach ($lines as $line) { foreach ($lines as $line) {
if (!$this->isComment($line) && $this->looksLikeSetter($line)) { if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
[$key, $value] = explode('=', $line); [$key, $value] = explode('=', $line);
putenv(trim($key) . '=' . trim($value)); putenv(trim($key) . '=' . trim($value));
} }
} }
return $lines; return $lines;
} }
/** /**
* Read lines from the file, auto detecting line endings. * Read lines from the file, auto detecting line endings.
* *
* @param string $filePath * @param string $filePath
* *
* @return array * @return array
*/ */
protected function readLinesFromFile(string $filePath): array 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');
ini_set('auto_detect_line_endings', '1'); ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect); ini_set('auto_detect_line_endings', $autodetect);
return $lines; return $lines;
} }
/** /**
* Determine if the line in the file is a comment, e.g. begins with a #. * Determine if the line in the file is a comment, e.g. begins with a #.
* *
* @param string $line * @param string $line
* *
* @return bool * @return bool
*/ */
protected function isComment(string $line): bool protected function isComment(string $line): bool
{ {
$line = ltrim($line); $line = ltrim($line);
return isset($line[0]) && $line[0] === '#'; return isset($line[0]) && $line[0] === '#';
} }
/** /**
* Determine if the given line looks like it's setting a variable. * Determine if the given line looks like it's setting a variable.
* *
* @param string $line * @param string $line
* *
* @return bool * @return bool
*/ */
#[Pure] protected function looksLikeSetter(string $line): bool #[Pure] protected function looksLikeSetter(string $line): bool
{ {
return str_contains($line, '='); return str_contains($line, '=');
} }
/** /**
* @param $config * @param $config
* *
* @throws * @throws
*/ */
public function parseInt($config) public function parseInt($config)
{ {
foreach ($config as $key => $value) { foreach ($config as $key => $value) {
Config::set($key, $value); Config::set($key, $value);
} }
if ($storage = Config::get('storage', false, 'storage')) { if ($storage = Config::get('storage', false, 'storage')) {
if (!str_contains($storage, APP_PATH)) { if (!str_contains($storage, APP_PATH)) {
$storage = APP_PATH . $storage . '/'; $storage = APP_PATH . $storage . '/';
} }
if (!is_dir($storage)) { if (!is_dir($storage)) {
mkdir($storage); mkdir($storage);
} }
if (!is_dir($storage) || !is_writeable($storage)) { if (!is_dir($storage) || !is_writeable($storage)) {
throw new InitException("Directory {$storage} does not have write permission"); throw new InitException("Directory {$storage} does not have write permission");
} }
} }
} }
/** /**
* @param $config * @param $config
* *
* @throws * @throws
*/ */
public function parseEvents($config) public function parseEvents($config)
{ {
if (!isset($config['events']) || !is_array($config['events'])) { if (!isset($config['events']) || !is_array($config['events'])) {
return; return;
} }
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
foreach ($config['events'] as $key => $value) { foreach ($config['events'] as $key => $value) {
if (is_string($value)) { if (is_string($value)) {
$value = Snowflake::createObject($value); $value = Snowflake::createObject($value);
} }
if (is_array($value) && isset($value[0]) && !($value[0] instanceof \Closure)) { if (is_array($value) && isset($value[0]) && !($value[0] instanceof \Closure)) {
if (!is_callable($value, true)) { if (!is_callable($value, true)) {
throw new InitException("Class does not hav callback."); throw new InitException("Class does not hav callback.");
} }
$event->on($key, $value); $event->on($key, $value);
} else { } else {
foreach ($value as $item) { foreach ($value as $item) {
if (!is_callable($item, true)) { if (!is_callable($item, true)) {
throw new InitException("Class does not hav callback."); throw new InitException("Class does not hav callback.");
} }
$event->on($key, $item); $event->on($key, $item);
} }
} }
} }
} }
/** /**
* @param $name * @param $name
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function clone($name): mixed public function clone($name): mixed
{ {
return clone $this->get($name); return clone $this->get($name);
} }
/** /**
* *
* @throws Exception * @throws Exception
*/ */
public function initErrorHandler() public function initErrorHandler()
{ {
$this->get('error')->register(); $this->get('error')->register();
} }
/** /**
* @return mixed * @return mixed
*/ */
public function getLocalIps(): mixed public function getLocalIps(): mixed
{ {
return swoole_get_local_ip(); return swoole_get_local_ip();
} }
/** /**
* @return mixed * @return mixed
*/ */
public function getFirstLocal(): mixed public function getFirstLocal(): mixed
{ {
return current($this->getLocalIps()); return current($this->getLocalIps());
} }
/** /**
* @return Logger * @return Logger
* @throws Exception * @throws Exception
*/ */
public function getLogger(): Logger public function getLogger(): Logger
{ {
return $this->get('logger'); return $this->get('logger');
} }
/** /**
* @return Producer * @return Producer
* @throws Exception * @throws Exception
*/ */
public function getKafka(): Producer public function getKafka(): Producer
{ {
return $this->get('kafka'); return $this->get('kafka');
} }
/** /**
* @return \Redis|Redis * @return \Redis|Redis
* @throws Exception * @throws Exception
*/ */
public function getRedis(): Redis|\Redis public function getRedis(): Redis|\Redis
{ {
return $this->get('redis'); return $this->get('redis');
} }
/** /**
* @param $ip * @param $ip
* @return bool * @return bool
*/ */
public function isLocal($ip): bool public function isLocal($ip): bool
{ {
return $this->getFirstLocal() == $ip; return $this->getFirstLocal() == $ip;
} }
/** /**
* @return ErrorHandler * @return ErrorHandler
* @throws Exception * @throws Exception
*/ */
public function getError(): ErrorHandler public function getError(): ErrorHandler
{ {
return $this->get('error'); return $this->get('error');
} }
/** /**
* @return Connection * @return Connection
* @throws ComponentException * @throws ComponentException
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
public function getMysqlFromPool(): Connection public function getMysqlFromPool(): Connection
{ {
return $this->get('pool')->getDb(); return $this->get('pool')->getDb();
} }
/** /**
* @return SRedis * @return SRedis
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws ComponentException * @throws ComponentException
*/ */
public function getRedisFromPool(): SRedis public function getRedisFromPool(): SRedis
{ {
return $this->get('pool')->getRedis(); return $this->get('pool')->getRedis();
} }
/** /**
* @return Response * @return Response
* @throws Exception * @throws Exception
*/ */
public function getResponse(): Response public function getResponse(): Response
{ {
return $this->get('response'); return $this->get('response');
} }
/** /**
* @return Request * @return Request
* @throws Exception * @throws Exception
*/ */
public function getRequest(): Request public function getRequest(): Request
{ {
return $this->get('request'); return $this->get('request');
} }
/** /**
* @param $name * @param $name
* @return Table * @return Table
* @throws Exception * @throws Exception
*/ */
public function getTable($name): Table public function getTable($name): Table
{ {
return $this->get($name); return $this->get($name);
} }
/** /**
* @return Config * @return Config
* @throws Exception * @throws Exception
*/ */
public function getConfig(): Config public function getConfig(): Config
{ {
return $this->get('config'); return $this->get('config');
} }
/** /**
* @return Router * @return Router
* @throws Exception * @throws Exception
*/ */
public function getRouter(): Router public function getRouter(): Router
{ {
return $this->get('router'); return $this->get('router');
} }
/** /**
* @return Event * @return Event
* @throws Exception * @throws Exception
*/ */
public function getEvent(): Event public function getEvent(): Event
{ {
return $this->get('event'); return $this->get('event');
} }
/** /**
* @return Jwt * @return Jwt
* @throws Exception * @throws Exception
*/ */
public function getJwt(): Jwt public function getJwt(): Jwt
{ {
return $this->get('jwt'); return $this->get('jwt');
} }
/** /**
* @return Server * @return Server
* @throws Exception * @throws Exception
*/ */
public function getServer(): Server public function getServer(): Server
{ {
return $this->get('server'); return $this->get('server');
} }
/** /**
* @return Http|Packet|Receive|Websocket|null * @return Http|Packet|Receive|Websocket|null
* @throws Exception * @throws Exception
*/ */
public function getSwoole(): Packet|Websocket|Receive|Http|null public function getSwoole(): Packet|Websocket|Receive|Http|null
{ {
return $this->getServer()->getServer(); return $this->getServer()->getServer();
} }
/** /**
* @return SAnnotation * @return SAnnotation
* @throws Exception * @throws Exception
*/ */
public function getAttributes(): SAnnotation public function getAttributes(): SAnnotation
{ {
return $this->get('attributes'); return $this->get('attributes');
} }
/** /**
* @return Async * @return Async
* @throws Exception * @throws Exception
*/ */
public function getAsync(): Async public function getAsync(): Async
{ {
return $this->get('async'); return $this->get('async');
} }
/** /**
* @return ObjectPool * @return ObjectPool
* @throws Exception * @throws Exception
*/ */
public function getObject(): ObjectPool public function getObject(): ObjectPool
{ {
return $this->get('object'); return $this->get('object');
} }
/** /**
* @return \Rpc\Producer * @return \Rpc\Producer
* @throws ComponentException * @throws ComponentException
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
public function getRpc(): \Rpc\Producer public function getRpc(): \Rpc\Producer
{ {
return $this->get('rpc'); return $this->get('rpc');
} }
/** /**
* @return Channel * @return Channel
* @throws ComponentException * @throws ComponentException
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
public function getChannel(): Channel public function getChannel(): Channel
{ {
return $this->get('channel'); return $this->get('channel');
} }
/** /**
* @throws Exception * @throws Exception
*/ */
protected function moreComponents(): void protected function moreComponents(): void
{ {
$this->setComponents([ $this->setComponents([
'error' => ['class' => ErrorHandler::class], 'error' => ['class' => ErrorHandler::class],
'event' => ['class' => Event::class], 'event' => ['class' => Event::class],
'connections' => ['class' => Connection::class], 'connections' => ['class' => Connection::class],
'redis_connections' => ['class' => SRedis::class], 'redis_connections' => ['class' => SRedis::class],
'pool' => ['class' => SPool::class], 'pool' => ['class' => SPool::class],
'response' => ['class' => Response::class], 'response' => ['class' => Response::class],
'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], '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],
'async' => ['class' => Async::class], 'async' => ['class' => Async::class],
'filter' => ['class' => HttpFilter::class], 'filter' => ['class' => HttpFilter::class],
'object' => ['class' => ObjectPool::class], 'object' => ['class' => ObjectPool::class],
'goto' => ['class' => BaseGoto::class], 'goto' => ['class' => BaseGoto::class],
'channel' => ['class' => Channel::class], 'channel' => ['class' => Channel::class],
'rpc' => ['class' => \Rpc\Producer::class], 'rpc' => ['class' => \Rpc\Producer::class],
'rpc-service' => ['class' => \Rpc\Service::class], 'rpc-service' => ['class' => \Rpc\Service::class],
'http2' => ['class' => Http2::class], 'http2' => ['class' => Http2::class],
]); 'shutdown' => ['class' => Shutdown::class],
} ]);
}
} }
+2
View File
@@ -14,6 +14,7 @@ use HttpServer\Http\Response;
use HttpServer\HttpFilter; use HttpServer\HttpFilter;
use HttpServer\Route\Router; use HttpServer\Route\Router;
use HttpServer\Server; use HttpServer\Server;
use HttpServer\Shutdown;
use Kafka\Producer; use Kafka\Producer;
use Snowflake\Async; use Snowflake\Async;
use Snowflake\Cache\Redis; use Snowflake\Cache\Redis;
@@ -50,6 +51,7 @@ use Rpc\Producer as RPCProducer;
* @property HttpFilter $filter * @property HttpFilter $filter
* @property RPCProducer $rpc * @property RPCProducer $rpc
* @property Channel $channel * @property Channel $channel
* @property Shutdown $shutdown
*/ */
trait TraitApplication trait TraitApplication
{ {
+1 -1
View File
@@ -34,7 +34,7 @@ abstract class Process extends \Swoole\Process implements SProcess
{ {
parent::__construct([$this, '_load'], false, 1, $enable_coroutine); parent::__construct([$this, '_load'], false, 1, $enable_coroutine);
$this->application = $application; $this->application = $application;
Snowflake::setWorkerId($this->pid); Snowflake::setProcessId($this->pid);
} }
/** /**
+484 -426
View File
@@ -37,432 +37,490 @@ defined('SOCKET_PATH') or define('SOCKET_PATH', APP_PATH . 'app/Websocket/');
class Snowflake class Snowflake
{ {
/** @var Container */ /** @var Container */
public static Container $container; public static Container $container;
/** @var ?Application */ /** @var ?Application */
private static ?Application $service = null; private static ?Application $service = null;
/** /**
* @param $service * @param $service
* *
* 初始化服务 * 初始化服务
*/ */
public static function init($service) public static function init($service)
{ {
static::$service = $service; static::$service = $service;
} }
/** /**
* @return Application|null * @return Application|null
*/ */
public static function app(): ?Application public static function app(): ?Application
{ {
return static::$service; return static::$service;
} }
/** /**
* @param $name * @param $name
* @return bool * @return bool
*/ */
public static function has($name): bool public static function has($name): bool
{ {
return static::$service->has($name); return static::$service->has($name);
} }
/** /**
* @param $className * @param $className
* @param $id * @param $id
*/ */
public static function setAlias($className, $id) public static function setAlias($className, $id)
{ {
static::$service->setAlias($className, $id); static::$service->setAlias($className, $id);
} }
/** /**
* @param $port * @param $port
* @return bool|array * @return bool|array
* @throws Exception * @throws Exception
*/ */
public static function port_already($port): bool public static function port_already($port): bool
{ {
if (empty($port)) { if (empty($port)) {
return false; return false;
} }
if (Snowflake::getPlatform()->isLinux()) { if (Snowflake::getPlatform()->isLinux()) {
exec('netstat -tunlp | grep ' . $port, $output); exec('netstat -tunlp | grep ' . $port, $output);
} else { } else {
exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output); exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output);
} }
return !empty($output); return !empty($output);
} }
/** /**
* @param $service * @param $service
* @return string * @return string
*/ */
#[Pure] public static function listen($service): string #[Pure] public static function listen($service): string
{ {
return sprintf('Check listen %s::%d -> ok', $service['host'], $service['port']); return sprintf('Check listen %s::%d -> ok', $service['host'], $service['port']);
} }
/** /**
* @param $className * @param $className
* @param array $construct * @param array $construct
* @return mixed * @return mixed
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
public static function createObject($className, $construct = []): mixed public static function createObject($className, $construct = []): mixed
{ {
if (is_object($className)) { if (is_object($className)) {
return $className; return $className;
} }
if (is_string($className)) { if (is_string($className)) {
return static::$container->get($className, $construct); return static::$container->get($className, $construct);
} else if (is_array($className)) { } else if (is_array($className)) {
if (!isset($className['class']) || empty($className['class'])) { if (!isset($className['class']) || empty($className['class'])) {
throw new Exception('Object configuration must be an array containing a "class" element.'); throw new Exception('Object configuration must be an array containing a "class" element.');
} }
$class = $className['class']; $class = $className['class'];
unset($className['class']); unset($className['class']);
return static::$container->get($class, $construct, $className); return static::$container->get($class, $construct, $className);
} else if (is_callable($className, TRUE)) { } else if (is_callable($className, TRUE)) {
return call_user_func($className, $construct); return call_user_func($className, $construct);
} else { } else {
throw new Exception('Unsupported configuration type: ' . gettype($className)); throw new Exception('Unsupported configuration type: ' . gettype($className));
} }
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public static function getStoragePath(): string 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);
if (!is_dir($path)) { if (!is_dir($path)) {
mkdir($path); mkdir($path, 0777, true);
} }
return $path; return $path;
} }
/** /**
* @return bool * @return bool
*/ */
public static function inCoroutine(): bool public static function inCoroutine(): bool
{ {
return Coroutine::getCid() > 0; return Coroutine::getCid() > 0;
} }
/** /**
* @return Container * @return Container
*/ */
public static function getDi(): Container public static function getDi(): Container
{ {
return static::$container; return static::$container;
} }
/** /**
* @param $workerId * @param $workerId
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function setProcessId($workerId): mixed public static function setManagerId($workerId): mixed
{ {
return self::writeFile(storage('socket.sock'), $workerId); return self::writeFile(storage($workerId . '.sock', 'pid/manager'), $workerId);
} }
/** /**
* @param $workerId * @param $workerId
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function setWorkerId($workerId): mixed public static function setProcessId($workerId): mixed
{ {
if (empty($workerId)) { return self::writeFile(storage($workerId . '.sock', 'pid/process'), $workerId);
return $workerId; }
}
return self::writeFile(storage($workerId . '.sock', 'worker'), $workerId);
} /**
* @param $workerId
* @return mixed
/** * @throws Exception
* @param $fileName */
* @param $content public static function setWorkerId($workerId): mixed
* @param null $is_append {
* @return mixed if (empty($workerId)) {
*/ return $workerId;
public static function writeFile($fileName, $content, $is_append = null): mixed }
{ return self::writeFile(storage($workerId . '.sock', 'pid/worker'), $workerId);
$params = [$fileName, (string)$content]; }
if ($is_append !== null) {
$params[] = $is_append;
} /**
return !self::inCoroutine() ? file_put_contents(...$params) : Coroutine::writeFile(...$params); * @param $workerId
} * @return mixed
* @throws Exception
*/
/** public static function setTaskId($workerId): mixed
* @param $object {
* @param $config if (empty($workerId)) {
* @return mixed return $workerId;
*/ }
public static function configure($object, $config): mixed return self::writeFile(storage($workerId . '.sock', 'pid/task'), $workerId);
{ }
foreach ($config as $key => $value) {
if (!property_exists($object, $key)) { /**
continue; * @param $fileName
} * @param $content
$object->$key = $value; * @param null $is_append
} * @return mixed
return $object; */
} public static function writeFile($fileName, $content, $is_append = null): mixed
{
$params = [$fileName, (string)$content];
/** if ($is_append !== null) {
* @param $workerId $params[] = $is_append;
* @throws Exception }
*/ return !self::inCoroutine() ? file_put_contents(...$params) : Coroutine::writeFile(...$params);
public static function clearProcessId($workerId) }
{
@unlink(storage($workerId . '.sock', 'worker'));
} /**
* @param $object
* @param $config
/** * @return mixed
* @return Server|null */
* @throws public static function configure($object, $config): mixed
*/ {
public static function getWebSocket(): ?Server foreach ($config as $key => $value) {
{ if (!property_exists($object, $key)) {
$server = static::app()->getSwoole(); continue;
if (!($server instanceof Server)) { }
return null; $object->$key = $value;
} }
return $server; return $object;
} }
/** /**
* @return false|string * @param $workerId
* @throws Exception * @param bool $isWorker
*/ * @throws Exception
public static function getMasterPid(): bool|string */
{ public static function clearProcessId($workerId, $isWorker = false)
$pid = Snowflake::app()->getSwoole()->setting['pid_file']; {
clearstatcache();
return file_get_contents($pid); $directory = $isWorker === true ? 'pid/worker' : 'pid/task';
} if (!file_exists($file = storage($workerId, $directory))) {
return;
}
/** shell_exec('rm -rf ' . $file);
* @param int $fd }
* @param $data
* @return mixed
* @throws Exception /**
*/ * @param string|null $taskPid
public static function push(int $fd, $data): mixed * @throws Exception
{ */
$server = static::getWebSocket(); public static function clearTaskPid(string $taskPid = null)
if (empty($server)) { {
return false; if (empty($taskPid)) {
} exec('rm -rf ' . storage(null, 'pid/task'));
if (!is_string($data)) { } else {
$data = Json::encode($data); static::clearProcessId($taskPid);
} }
return $server->push($fd, $data); }
}
/**
/** * @param $taskPid
* @return mixed * @throws Exception
*/ */
public static function localhost(): mixed public static function clearWorkerPid($taskPid = null)
{ {
return current(swoole_get_local_ip()); if (empty($taskPid)) {
} exec('rm -rf ' . storage(null, 'pid/worker'));
} else {
static::clearProcessId($taskPid, true);
/** }
* @param string $class }
* @param array $params
* @throws NotFindClassException
* @throws ReflectionException /**
* @throws Exception * @return Server|null
*/ * @throws
public static function async(string $class, array $params = []) */
{ public static function getWebSocket(): ?Server
$server = static::app()->getSwoole(); {
if (!isset($server->setting['task_worker_num']) || !class_exists($class)) { $server = static::app()->getSwoole();
return; if (!($server instanceof Server)) {
} return null;
}
/** @var Task $class */ return $server;
$class = static::createObject($class); }
$class->setParams($params);
$server->task(swoole_serialize($class)); /**
} * @return false|string
* @throws Exception
*/
/** public static function getMasterPid(): bool|string
* @param $v1 {
* @param $v2 $pid = Snowflake::app()->getSwoole()->setting['pid_file'];
* @return float
*/ return file_get_contents($pid);
#[Pure] public static function distance(array $v1, array $v2): float }
{
$maxX = max($v1['x'], $v2['x']);
$minX = min($v1['x'], $v2['x']); /**
* @param int $fd
$maxZ = max($v1['z'], $v2['z']); * @param $data
$minZ = min($v1['z'], $v2['z']); * @return mixed
* @throws Exception
$dx = abs($maxX - $minX); */
$dy = abs($maxZ - $minZ); public static function push(int $fd, $data): mixed
{
$sqrt = sqrt($dx * $dx + $dy * $dy); $server = static::getWebSocket();
if ($sqrt < 0) { if (empty($server)) {
$sqrt = abs($sqrt); return false;
} }
return (float)$sqrt; if (!is_string($data)) {
} $data = Json::encode($data);
}
return $server->push($fd, $data);
/** }
* @param $process
* @throws Exception
*/ /**
public static function shutdown($process): void * @return mixed
{ */
static::app()->getSwoole()->shutdown(); public static function localhost(): mixed
if ($process instanceof Process) { {
$process->exit(0); return current(swoole_get_local_ip());
} }
}
/**
/** * @param string $class
* @param $tmp * @param array $params
* @return string * @throws NotFindClassException
*/ * @throws ReflectionException
public static function rename($tmp): string * @throws Exception
{ */
$hash = md5_file($tmp['tmp_name']); public static function async(string $class, array $params = [])
{
$later = '.' . exif_imagetype($tmp['tmp_name']); $server = static::app()->getSwoole();
if (!isset($server->setting['task_worker_num']) || !class_exists($class)) {
$match = '/(\w{12})(\w{5})(\w{9})(\w{6})/'; return;
$tmp = preg_replace($match, '$1-$2-$3-$4', $hash); }
return strtoupper($tmp) . $later; /** @var Task $class */
} $class = static::createObject($class);
$class->setParams($params);
/** $server->task(swoole_serialize($class));
* @return Environmental }
* @throws Exception
*/
public static function getPlatform(): Environmental /**
{ * @param $v1
return Snowflake::createObject(Environmental::class); * @param $v2
} * @return float
*/
#[Pure] public static function distance(array $v1, array $v2): float
/** {
* @return mixed $maxX = max($v1['x'], $v2['x']);
* @throws Exception $minX = min($v1['x'], $v2['x']);
*/
public static function reload(): mixed $maxZ = max($v1['z'], $v2['z']);
{ $minZ = min($v1['z'], $v2['z']);
return Snowflake::app()->getSwoole()->reload();
} $dx = abs($maxX - $minX);
$dy = abs($maxZ - $minZ);
private static array $_autoload = []; $sqrt = sqrt($dx * $dx + $dy * $dy);
if ($sqrt < 0) {
$sqrt = abs($sqrt);
const PROCESS = 'process'; }
const TASK = 'task'; return (float)$sqrt;
const WORKER = 'worker'; }
/** /**
* @return string|null * @param $process
*/ * @throws Exception
#[Pure] public static function getEnvironmental(): ?string */
{ public static function shutdown($process): void
return env('environmental'); {
} static::app()->getSwoole()->shutdown();
if ($process instanceof Process) {
$process->exit(0);
/** }
* @return bool }
*/
#[Pure] public static function isTask(): bool
{ /**
return static::getEnvironmental() == static::TASK; * @param $tmp
} * @return string
*/
public static function rename($tmp): string
/** {
* @return bool $hash = md5_file($tmp['tmp_name']);
*/
#[Pure] public static function isWorker(): bool $later = '.' . exif_imagetype($tmp['tmp_name']);
{
return static::getEnvironmental() == static::WORKER; $match = '/(\w{12})(\w{5})(\w{9})(\w{6})/';
} $tmp = preg_replace($match, '$1-$2-$3-$4', $hash);
return strtoupper($tmp) . $later;
/** }
* @return bool
*/
#[Pure] public static function isProcess(): bool /**
{ * @return Environmental
return static::getEnvironmental() == static::PROCESS; * @throws Exception
} */
public static function getPlatform(): Environmental
{
/** return Snowflake::createObject(Environmental::class);
* @param $class }
* @param $file
*/
public static function setAutoload($class, $file) /**
{ * @return mixed
if (isset(static::$_autoload[$class])) { * @throws Exception
return; */
} public static function reload(): mixed
static::$_autoload[$class] = $file; {
include_once "$file"; return Snowflake::app()->getSwoole()->reload();
} }
/** private static array $_autoload = [];
* @param $className
*/
public static function autoload($className) const PROCESS = 'process';
{ const TASK = 'task';
if (!isset(static::$_autoload[$className])) { const WORKER = 'worker';
return;
}
$file = static::$_autoload[$className]; /**
require_once "$file"; * @return string|null
} */
#[Pure] public static function getEnvironmental(): ?string
{
return env('environmental');
}
/**
* @return bool
*/
#[Pure] public static function isTask(): bool
{
return static::getEnvironmental() == static::TASK;
}
/**
* @return bool
*/
#[Pure] public static function isWorker(): bool
{
return static::getEnvironmental() == static::WORKER;
}
/**
* @return bool
*/
#[Pure] public static function isProcess(): bool
{
return static::getEnvironmental() == static::PROCESS;
}
/**
* @param $class
* @param $file
*/
public static function setAutoload($class, $file)
{
if (isset(static::$_autoload[$class])) {
return;
}
static::$_autoload[$class] = $file;
include_once "$file";
}
/**
* @param $className
*/
public static function autoload($className)
{
if (!isset(static::$_autoload[$className])) {
return;
}
$file = static::$_autoload[$className];
require_once "$file";
}
} }
+31 -20
View File
@@ -9,6 +9,10 @@ use HttpServer\Http\HttpParams;
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\Service\Http;
use HttpServer\Service\Packet;
use HttpServer\Service\Receive;
use HttpServer\Service\Websocket;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Error\Logger; use Snowflake\Error\Logger;
@@ -467,6 +471,20 @@ if (!function_exists('Input')) {
} }
if (!function_exists('Server')) {
/**
* @return Http|Packet|Receive|Websocket|null
* @throws Exception
*/
function Server(): Http|Packet|Receive|Websocket|null
{
return Snowflake::app()->getSwoole();
}
}
if (!function_exists('storage')) { if (!function_exists('storage')) {
/** /**
@@ -477,14 +495,18 @@ if (!function_exists('storage')) {
*/ */
function storage($fileName = '', $path = ''): string function storage($fileName = '', $path = ''): string
{ {
$basePath = Snowflake::getStoragePath();
if (empty($path)) { $basePath = rtrim(Snowflake::getStoragePath(), '/');
$fileName = rtrim($basePath, '/') . '/' . $fileName; if (!empty($path)) {
} else if (empty($fileName)) { $path = ltrim($path, '/');
return rtrim(initDir($basePath, $path)); if (!is_dir($basePath . '/' . $path)) {
} else { mkdir($basePath . '/' . $path, 0777, true);
$fileName = rtrim(initDir($basePath, $path)) . '/' . $fileName; }
} }
if (empty($fileName)) {
return $basePath . '/' . $path . '/';
}
$fileName = $basePath . '/' . $path . '/' . $fileName;
if (!file_exists($fileName)) { if (!file_exists($fileName)) {
touch($fileName); touch($fileName);
} }
@@ -498,20 +520,9 @@ if (!function_exists('storage')) {
* @return false|string * @return false|string
* @throws Exception * @throws Exception
*/ */
function initDir($basePath, $path): bool|string function initDir($path): bool|string
{ {
$explode = array_filter(explode('/', $path)); return mkdir($path, 0777, true);
$_path = '/' . trim($basePath, '/') . '/';
foreach ($explode as $value) {
$_path .= $value . '/';
if (!is_dir(rtrim($_path, '/'))) {
mkdir(rtrim($_path, '/'));
}
if (!is_dir($_path)) {
throw new Exception('System error, directory ' . $_path . ' is not writable');
}
}
return realpath($_path);
} }