Framework Update

This commit is contained in:
2024-01-31 22:15:08 +08:00
parent b5ff5e8b5f
commit 20678a6a0c
1459 changed files with 25954 additions and 16153 deletions
+2 -1
View File
@@ -25,7 +25,8 @@
},
"require": {
"php": ">=7.2",
"workerman/workerman": "^4.0.4",
"ext-json": "*",
"workerman/workerman": "^4.0.4 || ^5.0.0",
"nikic/fast-route": "^1.3",
"psr/container": ">=1.0"
},
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -21,8 +21,8 @@ interface Bootstrap
/**
* onWorkerStart
*
* @param Worker $worker
* @param Worker|null $worker
* @return mixed
*/
public static function start($worker);
public static function start(?Worker $worker);
}
+79 -59
View File
@@ -14,79 +14,95 @@
namespace Webman;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use function array_replace_recursive;
use function array_reverse;
use function count;
use function explode;
use function in_array;
use function is_array;
use function is_dir;
use function is_file;
use function key;
use function str_replace;
class Config
{
/**
* @var array
*/
protected static $_config = [];
protected static $config = [];
/**
* @var string
*/
protected static $_configPath = '';
protected static $configPath = '';
/**
* @var bool
*/
protected static $_loaded = false;
protected static $loaded = false;
/**
* @param string $config_path
* @param array $exclude_file
* Load.
* @param string $configPath
* @param array $excludeFile
* @param string|null $key
* @return void
*/
public static function load(string $config_path, array $exclude_file = [], string $key = null)
public static function load(string $configPath, array $excludeFile = [], string $key = null)
{
static::$_configPath = $config_path;
if (!$config_path) {
static::$configPath = $configPath;
if (!$configPath) {
return;
}
static::$_loaded = false;
$config = static::loadFromDir($config_path, $exclude_file);
static::$loaded = false;
$config = static::loadFromDir($configPath, $excludeFile);
if (!$config) {
static::$_loaded = true;
static::$loaded = true;
return;
}
if ($key !== null) {
foreach (\array_reverse(\explode('.', $key)) as $k) {
foreach (array_reverse(explode('.', $key)) as $k) {
$config = [$k => $config];
}
}
static::$_config = \array_replace_recursive(static::$_config, $config);
static::$config = array_replace_recursive(static::$config, $config);
static::formatConfig();
static::$_loaded = true;
static::$loaded = true;
}
/**
* This deprecated method will certainly be removed in the future
*
* @deprecated
* @param string $config_path
* @param array $exclude_file
* This deprecated method will certainly be removed in the future.
* @param string $configPath
* @param array $excludeFile
* @return void
* @deprecated
*/
public static function reload(string $config_path, array $exclude_file = [])
public static function reload(string $configPath, array $excludeFile = [])
{
static::load($config_path, $exclude_file);
static::load($configPath, $excludeFile);
}
/**
* Clear.
* @return void
*/
public static function clear()
{
static::$_config = [];
static::$config = [];
}
/**
* FormatConfig.
* @return void
*/
protected static function formatConfig()
{
$config = static::$_config;
$config = static::$config;
// Merge log config
foreach ($config['plugin'] ?? [] as $firm => $projects) {
if (isset($projects['app'])) {
@@ -95,7 +111,7 @@ class Config
}
}
foreach ($projects as $name => $project) {
if (!\is_array($project)) {
if (!is_array($project)) {
continue;
}
foreach ($project['log'] ?? [] as $key => $item) {
@@ -111,7 +127,7 @@ class Config
}
}
foreach ($projects as $name => $project) {
if (!\is_array($project)) {
if (!is_array($project)) {
continue;
}
foreach ($project['database']['connections'] ?? [] as $key => $connection) {
@@ -130,7 +146,7 @@ class Config
}
}
foreach ($projects as $name => $project) {
if (!\is_array($project)) {
if (!is_array($project)) {
continue;
}
foreach ($project['thinkorm']['connections'] ?? [] as $key => $connection) {
@@ -139,7 +155,7 @@ class Config
}
}
if (!empty($config['thinkorm']['connections'])) {
$config['thinkorm']['default'] = $config['thinkorm']['default'] ?? \key($config['thinkorm']['connections']);
$config['thinkorm']['default'] = $config['thinkorm']['default'] ?? key($config['thinkorm']['connections']);
}
// Merge redis config
foreach ($config['plugin'] ?? [] as $firm => $projects) {
@@ -149,7 +165,7 @@ class Config
}
}
foreach ($projects as $name => $project) {
if (!\is_array($project)) {
if (!is_array($project)) {
continue;
}
foreach ($project['redis'] ?? [] as $key => $connection) {
@@ -157,33 +173,34 @@ class Config
}
}
}
static::$_config = $config;
static::$config = $config;
}
/**
* @param string $config_path
* @param array $exclude_file
* LoadFromDir.
* @param string $configPath
* @param array $excludeFile
* @return array
*/
public static function loadFromDir(string $config_path, array $exclude_file = [])
public static function loadFromDir(string $configPath, array $excludeFile = []): array
{
$all_config = [];
$dir_iterator = new \RecursiveDirectoryIterator($config_path, \FilesystemIterator::FOLLOW_SYMLINKS);
$iterator = new \RecursiveIteratorIterator($dir_iterator);
$allConfig = [];
$dirIterator = new RecursiveDirectoryIterator($configPath, FilesystemIterator::FOLLOW_SYMLINKS);
$iterator = new RecursiveIteratorIterator($dirIterator);
foreach ($iterator as $file) {
/** var SplFileInfo $file */
if (\is_dir($file) || $file->getExtension() != 'php' || \in_array($file->getBaseName('.php'), $exclude_file)) {
if (is_dir($file) || $file->getExtension() != 'php' || in_array($file->getBaseName('.php'), $excludeFile)) {
continue;
}
$app_config_file = $file->getPath() . '/app.php';
if (!\is_file($app_config_file)) {
$appConfigFile = $file->getPath() . '/app.php';
if (!is_file($appConfigFile)) {
continue;
}
$relative_path = \str_replace($config_path . DIRECTORY_SEPARATOR, '', substr($file, 0, -4));
$explode = \array_reverse(\explode(DIRECTORY_SEPARATOR, $relative_path));
if (\count($explode) >= 2) {
$app_config = include $app_config_file;
if (empty($app_config['enable'])) {
$relativePath = str_replace($configPath . DIRECTORY_SEPARATOR, '', substr($file, 0, -4));
$explode = array_reverse(explode(DIRECTORY_SEPARATOR, $relativePath));
if (count($explode) >= 2) {
$appConfig = include $appConfigFile;
if (empty($appConfig['enable'])) {
continue;
}
}
@@ -193,12 +210,13 @@ class Config
$tmp[$section] = $config;
$config = $tmp;
}
$all_config = \array_replace_recursive($all_config, $config);
$allConfig = array_replace_recursive($allConfig, $config);
}
return $all_config;
return $allConfig;
}
/**
* Get.
* @param string|null $key
* @param mixed $default
* @return array|mixed|void|null
@@ -206,14 +224,14 @@ class Config
public static function get(string $key = null, $default = null)
{
if ($key === null) {
return static::$_config;
return static::$config;
}
$key_array = \explode('.', $key);
$value = static::$_config;
$keyArray = explode('.', $key);
$value = static::$config;
$found = true;
foreach ($key_array as $index) {
foreach ($keyArray as $index) {
if (!isset($value[$index])) {
if (static::$_loaded) {
if (static::$loaded) {
return $default;
}
$found = false;
@@ -228,24 +246,25 @@ class Config
}
/**
* Read.
* @param string $key
* @param mixed $default
* @return array|mixed|null
*/
protected static function read(string $key, $default = null)
{
$path = static::$_configPath;
$path = static::$configPath;
if ($path === '') {
return $default;
}
$keys = $key_array = \explode('.', $key);
foreach ($key_array as $index => $section) {
$keys = $keyArray = explode('.', $key);
foreach ($keyArray as $index => $section) {
unset($keys[$index]);
if (\is_file($file = "$path/$section.php")) {
if (is_file($file = "$path/$section.php")) {
$config = include $file;
return static::find($keys, $config, $default);
}
if (!\is_dir($path = "$path/$section")) {
if (!is_dir($path = "$path/$section")) {
return $default;
}
}
@@ -253,18 +272,19 @@ class Config
}
/**
* @param array $key_array
* Find.
* @param array $keyArray
* @param mixed $stack
* @param mixed $default
* @return array|mixed
*/
protected static function find(array $key_array, $stack, $default)
protected static function find(array $keyArray, $stack, $default)
{
if (!\is_array($stack)) {
if (!is_array($stack)) {
return $default;
}
$value = $stack;
foreach ($key_array as $index) {
foreach ($keyArray as $index) {
if (!isset($value[$index])) {
return $default;
}
+20 -14
View File
@@ -4,6 +4,8 @@ namespace Webman;
use Psr\Container\ContainerInterface;
use Webman\Exception\NotFoundException;
use function array_key_exists;
use function class_exists;
/**
* Class Container
@@ -15,43 +17,46 @@ class Container implements ContainerInterface
/**
* @var array
*/
protected $_instances = [];
protected $instances = [];
/**
* @var array
* @var array
*/
protected $_definitions = [];
protected $definitions = [];
/**
* Get.
* @param string $name
* @return mixed
* @throws NotFoundException
*/
public function get(string $name)
{
if (!isset($this->_instances[$name])) {
if (isset($this->_definitions[$name])) {
$this->_instances[$name] = call_user_func($this->_definitions[$name], $this);
if (!isset($this->instances[$name])) {
if (isset($this->definitions[$name])) {
$this->instances[$name] = call_user_func($this->definitions[$name], $this);
} else {
if (!\class_exists($name)) {
if (!class_exists($name)) {
throw new NotFoundException("Class '$name' not found");
}
$this->_instances[$name] = new $name();
$this->instances[$name] = new $name();
}
}
return $this->_instances[$name];
return $this->instances[$name];
}
/**
* Has.
* @param string $name
* @return bool
*/
public function has(string $name): bool
{
return \array_key_exists($name, $this->_instances)
|| array_key_exists($name, $this->_definitions);
return array_key_exists($name, $this->instances)
|| array_key_exists($name, $this->definitions);
}
/**
* Make.
* @param string $name
* @param array $constructor
* @return mixed
@@ -59,19 +64,20 @@ class Container implements ContainerInterface
*/
public function make(string $name, array $constructor = [])
{
if (!\class_exists($name)) {
if (!class_exists($name)) {
throw new NotFoundException("Class '$name' not found");
}
return new $name(... array_values($constructor));
}
/**
* AddDefinitions.
* @param array $definitions
* @return $this
*/
public function addDefinitions(array $definitions)
public function addDefinitions(array $definitions): Container
{
$this->_definitions = array_merge($this->_definitions, $definitions);
$this->definitions = array_merge($this->definitions, $definitions);
return $this;
}
+129
View File
@@ -0,0 +1,129 @@
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Webman;
use Fiber;
use SplObjectStorage;
use StdClass;
use Swow\Coroutine;
use WeakMap;
use Workerman\Events\Revolt;
use Workerman\Events\Swoole;
use Workerman\Events\Swow;
use Workerman\Worker;
use function property_exists;
/**
* Class Context
* @package Webman
*/
class Context
{
/**
* @var SplObjectStorage|WeakMap
*/
protected static $objectStorage;
/**
* @var StdClass
*/
protected static $object;
/**
* @return StdClass
*/
protected static function getObject(): StdClass
{
if (!static::$objectStorage) {
static::$objectStorage = class_exists(WeakMap::class) ? new WeakMap() : new SplObjectStorage();
static::$object = new StdClass;
}
$key = static::getKey();
if (!isset(static::$objectStorage[$key])) {
static::$objectStorage[$key] = new StdClass;
}
return static::$objectStorage[$key];
}
/**
* @return mixed
*/
protected static function getKey()
{
switch (Worker::$eventLoopClass) {
case Revolt::class:
return Fiber::getCurrent();
case Swoole::class:
return \Swoole\Coroutine::getContext();
case Swow::class:
return Coroutine::getCurrent();
}
return static::$object;
}
/**
* @param string|null $key
* @return mixed
*/
public static function get(string $key = null)
{
$obj = static::getObject();
if ($key === null) {
return $obj;
}
return $obj->$key ?? null;
}
/**
* @param string $key
* @param $value
* @return void
*/
public static function set(string $key, $value): void
{
$obj = static::getObject();
$obj->$key = $value;
}
/**
* @param string $key
* @return void
*/
public static function delete(string $key): void
{
$obj = static::getObject();
unset($obj->$key);
}
/**
* @param string $key
* @return bool
*/
public static function has(string $key): bool
{
$obj = static::getObject();
return property_exists($obj, $key);
}
/**
* @return void
*/
public static function destroy(): void
{
unset(static::$objectStorage[static::getKey()]);
}
}
@@ -18,6 +18,9 @@ use Psr\Log\LoggerInterface;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
use function json_encode;
use function nl2br;
use function trim;
/**
* Class Handler
@@ -28,12 +31,12 @@ class ExceptionHandler implements ExceptionHandlerInterface
/**
* @var LoggerInterface
*/
protected $_logger = null;
protected $logger = null;
/**
* @var bool
*/
protected $_debug = false;
protected $debug = false;
/**
* @var array
@@ -47,8 +50,8 @@ class ExceptionHandler implements ExceptionHandlerInterface
*/
public function __construct($logger, $debug)
{
$this->_logger = $logger;
$this->_debug = $debug;
$this->logger = $logger;
$this->debug = $debug;
}
/**
@@ -62,9 +65,9 @@ class ExceptionHandler implements ExceptionHandlerInterface
}
$logs = '';
if ($request = \request()) {
$logs = $request->getRealIp() . ' ' . $request->method() . ' ' . \trim($request->fullUrl(), '/');
$logs = $request->getRealIp() . ' ' . $request->method() . ' ' . trim($request->fullUrl(), '/');
}
$this->_logger->error($logs . PHP_EOL . $exception);
$this->logger->error($logs . PHP_EOL . $exception);
}
/**
@@ -76,12 +79,12 @@ class ExceptionHandler implements ExceptionHandlerInterface
{
$code = $exception->getCode();
if ($request->expectsJson()) {
$json = ['code' => $code ? $code : 500, 'msg' => $this->_debug ? $exception->getMessage() : 'Server internal error'];
$this->_debug && $json['traces'] = (string)$exception;
$json = ['code' => $code ?: 500, 'msg' => $this->debug ? $exception->getMessage() : 'Server internal error'];
$this->debug && $json['traces'] = (string)$exception;
return new Response(200, ['Content-Type' => 'application/json'],
\json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
$error = $this->_debug ? \nl2br((string)$exception) : 'Server internal error';
$error = $this->debug ? nl2br((string)$exception) : 'Server internal error';
return new Response(500, [], $error);
}
@@ -89,7 +92,7 @@ class ExceptionHandler implements ExceptionHandlerInterface
* @param Throwable $e
* @return bool
*/
protected function shouldntReport(Throwable $e)
protected function shouldntReport(Throwable $e): bool
{
foreach ($this->dontReport as $type) {
if ($e instanceof $type) {
@@ -98,4 +101,18 @@ class ExceptionHandler implements ExceptionHandlerInterface
}
return false;
}
/**
* Compatible $this->_debug
*
* @param string $name
* @return bool|null
*/
public function __get(string $name)
{
if ($name === '_debug') {
return $this->debug;
}
return null;
}
}
@@ -21,15 +21,15 @@ use Webman\Http\Response;
interface ExceptionHandlerInterface
{
/**
* @param Throwable $e
* @param Throwable $exception
* @return mixed
*/
public function report(Throwable $e);
public function report(Throwable $exception);
/**
* @param Request $request
* @param Throwable $e
* @param Throwable $exception
* @return Response
*/
public function render(Request $request, Throwable $e): Response;
public function render(Request $request, Throwable $exception): Response;
}
+22 -11
View File
@@ -14,31 +14,42 @@
namespace Webman;
use SplFileInfo;
use Webman\Exception\FileException;
use function chmod;
use function is_dir;
use function mkdir;
use function pathinfo;
use function restore_error_handler;
use function set_error_handler;
use function sprintf;
use function strip_tags;
use function umask;
class File extends \SplFileInfo
class File extends SplFileInfo
{
/**
* Move.
* @param string $destination
* @return File
*/
public function move(string $destination)
public function move(string $destination): File
{
\set_error_handler(function ($type, $msg) use (&$error) {
set_error_handler(function ($type, $msg) use (&$error) {
$error = $msg;
});
$path = \pathinfo($destination, PATHINFO_DIRNAME);
if (!\is_dir($path) && !\mkdir($path, 0777, true)) {
\restore_error_handler();
throw new FileException(\sprintf('Unable to create the "%s" directory (%s)', $path, \strip_tags($error)));
$path = pathinfo($destination, PATHINFO_DIRNAME);
if (!is_dir($path) && !mkdir($path, 0777, true)) {
restore_error_handler();
throw new FileException(sprintf('Unable to create the "%s" directory (%s)', $path, strip_tags($error)));
}
if (!rename($this->getPathname(), $destination)) {
\restore_error_handler();
throw new FileException(\sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $destination, \strip_tags($error)));
restore_error_handler();
throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $destination, strip_tags($error)));
}
\restore_error_handler();
@\chmod($destination, 0666 & ~\umask());
restore_error_handler();
@chmod($destination, 0666 & ~umask());
return new self($destination);
}
+75 -48
View File
@@ -14,8 +14,16 @@
namespace Webman\Http;
use Webman\App;
use Webman\Route\Route;
use function current;
use function filter_var;
use function ip2long;
use function is_array;
use function strpos;
use const FILTER_FLAG_IPV4;
use const FILTER_FLAG_NO_PRIV_RANGE;
use const FILTER_FLAG_NO_RES_RANGE;
use const FILTER_VALIDATE_IP;
/**
* Class Request
@@ -57,25 +65,27 @@ class Request extends \Workerman\Protocols\Http\Request
}
/**
* Input
* @param string $name
* @param string|null $default
* @param mixed $default
* @return mixed|null
*/
public function input($name, $default = null)
public function input(string $name, $default = null)
{
$post = $this->post();
if (isset($post[$name])) {
return $post[$name];
}
$get = $this->get();
return isset($get[$name]) ? $get[$name] : $default;
return $get[$name] ?? $default;
}
/**
* Only
* @param array $keys
* @return array
*/
public function only(array $keys)
public function only(array $keys): array
{
$all = $this->all();
$result = [];
@@ -88,6 +98,7 @@ class Request extends \Workerman\Protocols\Http\Request
}
/**
* Except
* @param array $keys
* @return mixed|null
*/
@@ -101,6 +112,7 @@ class Request extends \Workerman\Protocols\Http\Request
}
/**
* File
* @param string|null $name
* @return null|UploadFile[]|UploadFile
*/
@@ -112,164 +124,179 @@ class Request extends \Workerman\Protocols\Http\Request
}
if ($name !== null) {
// Multi files
if (\is_array(\current($files))) {
if (is_array(current($files))) {
return $this->parseFiles($files);
}
return $this->parseFile($files);
}
$upload_files = [];
$uploadFiles = [];
foreach ($files as $name => $file) {
// Multi files
if (\is_array(\current($file))) {
$upload_files[$name] = $this->parseFiles($file);
if (is_array(current($file))) {
$uploadFiles[$name] = $this->parseFiles($file);
} else {
$upload_files[$name] = $this->parseFile($file);
$uploadFiles[$name] = $this->parseFile($file);
}
}
return $upload_files;
return $uploadFiles;
}
/**
* ParseFile
* @param array $file
* @return UploadFile
*/
protected function parseFile(array $file)
protected function parseFile(array $file): UploadFile
{
return new UploadFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
}
/**
* ParseFiles
* @param array $files
* @return array
*/
protected function parseFiles(array $files)
protected function parseFiles(array $files): array
{
$upload_files = [];
$uploadFiles = [];
foreach ($files as $key => $file) {
if (\is_array(\current($file))) {
$upload_files[$key] = $this->parseFiles($file);
if (is_array(current($file))) {
$uploadFiles[$key] = $this->parseFiles($file);
} else {
$upload_files[$key] = $this->parseFile($file);
$uploadFiles[$key] = $this->parseFile($file);
}
}
return $upload_files;
return $uploadFiles;
}
/**
* GetRemoteIp
* @return string
*/
public function getRemoteIp()
public function getRemoteIp(): string
{
return App::connection()->getRemoteIp();
return $this->connection->getRemoteIp();
}
/**
* GetRemotePort
* @return int
*/
public function getRemotePort()
public function getRemotePort(): int
{
return App::connection()->getRemotePort();
return $this->connection->getRemotePort();
}
/**
* GetLocalIp
* @return string
*/
public function getLocalIp()
public function getLocalIp(): string
{
return App::connection()->getLocalIp();
return $this->connection->getLocalIp();
}
/**
* GetLocalPort
* @return int
*/
public function getLocalPort()
public function getLocalPort(): int
{
return App::connection()->getLocalPort();
return $this->connection->getLocalPort();
}
/**
* @param bool $safe_mode
* GetRealIp
* @param bool $safeMode
* @return string
*/
public function getRealIp(bool $safe_mode = true)
public function getRealIp(bool $safeMode = true): string
{
$remote_ip = $this->getRemoteIp();
if ($safe_mode && !static::isIntranetIp($remote_ip)) {
return $remote_ip;
$remoteIp = $this->getRemoteIp();
if ($safeMode && !static::isIntranetIp($remoteIp)) {
return $remoteIp;
}
return $this->header('x-real-ip', $this->header('x-forwarded-for',
$ip = $this->header('x-real-ip', $this->header('x-forwarded-for',
$this->header('client-ip', $this->header('x-client-ip',
$this->header('via', $remote_ip)))));
$this->header('via', $remoteIp)))));
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : $remoteIp;
}
/**
* Url
* @return string
*/
public function url()
public function url(): string
{
return '//' . $this->host() . $this->path();
}
/**
* FullUrl
* @return string
*/
public function fullUrl()
public function fullUrl(): string
{
return '//' . $this->host() . $this->uri();
}
/**
* IsAjax
* @return bool
*/
public function isAjax()
public function isAjax(): bool
{
return $this->header('X-Requested-With') === 'XMLHttpRequest';
}
/**
* IsPjax
* @return bool
*/
public function isPjax()
public function isPjax(): bool
{
return (bool)$this->header('X-PJAX');
}
/**
* ExpectsJson
* @return bool
*/
public function expectsJson()
public function expectsJson(): bool
{
return ($this->isAjax() && !$this->isPjax()) || $this->acceptJson();
}
/**
* AcceptJson
* @return bool
*/
public function acceptJson()
public function acceptJson(): bool
{
return false !== \strpos($this->header('accept', ''), 'json');
return false !== strpos($this->header('accept', ''), 'json');
}
/**
* IsIntranetIp
* @param string $ip
* @return bool
*/
public static function isIntranetIp(string $ip)
public static function isIntranetIp(string $ip): bool
{
// Not validate ip .
if (!\filter_var($ip, \FILTER_VALIDATE_IP)) {
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
return false;
}
// Is intranet ip ? For IPv4, the result of false may not be accurate, so we need to check it manually later .
if (!\filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE)) {
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return true;
}
// Manual check only for IPv4 .
if (!\filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return false;
}
// Manual check .
$reserved_ips = [
$reservedIps = [
1681915904 => 1686110207, // 100.64.0.0 - 100.127.255.255
3221225472 => 3221225727, // 192.0.0.0 - 192.0.0.255
3221225984 => 3221226239, // 192.0.2.0 - 192.0.2.255
@@ -279,9 +306,9 @@ class Request extends \Workerman\Protocols\Http\Request
3405803776 => 3405804031, // 203.0.113.0 - 203.0.113.255
3758096384 => 4026531839, // 224.0.0.0 - 239.255.255.255
];
$ip_long = \ip2long($ip);
foreach ($reserved_ips as $ip_start => $ip_end) {
if (($ip_long >= $ip_start) && ($ip_long <= $ip_end)) {
$ipLong = ip2long($ip);
foreach ($reservedIps as $ipStart => $ipEnd) {
if (($ipLong >= $ipStart) && ($ipLong <= $ipEnd)) {
return true;
}
}
+22 -16
View File
@@ -14,8 +14,10 @@
namespace Webman\Http;
use Webman\App;
use Throwable;
use Webman\App;
use function filemtime;
use function gmdate;
/**
* Class Response
@@ -26,13 +28,14 @@ class Response extends \Workerman\Protocols\Http\Response
/**
* @var Throwable
*/
protected $_exception = null;
protected $exception = null;
/**
* File
* @param string $file
* @return $this
*/
public function file(string $file)
public function file(string $file): Response
{
if ($this->notModifiedSince($file)) {
return $this->withStatus(304);
@@ -41,41 +44,44 @@ class Response extends \Workerman\Protocols\Http\Response
}
/**
* Download
* @param string $file
* @param string $download_name
* @param string $downloadName
* @return $this
*/
public function download(string $file, string $download_name = '')
public function download(string $file, string $downloadName = ''): Response
{
$this->withFile($file);
if ($download_name) {
$this->header('Content-Disposition', "attachment; filename=\"$download_name\"");
if ($downloadName) {
$this->header('Content-Disposition', "attachment; filename=\"$downloadName\"");
}
return $this;
}
/**
* NotModifiedSince
* @param string $file
* @return bool
*/
protected function notModifiedSince(string $file)
protected function notModifiedSince(string $file): bool
{
$if_modified_since = App::request()->header('if-modified-since');
if ($if_modified_since === null || !($mtime = \filemtime($file))) {
$ifModifiedSince = App::request()->header('if-modified-since');
if ($ifModifiedSince === null || !is_file($file) || !($mtime = filemtime($file))) {
return false;
}
return $if_modified_since === \gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
return $ifModifiedSince === gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
}
/**
* @param Throwable $exception
* @return Throwable
* Exception
* @param Throwable|null $exception
* @return Throwable|null
*/
public function exception($exception = null)
public function exception(Throwable $exception = null): ?Throwable
{
if ($exception) {
$this->_exception = $exception;
$this->exception = $exception;
}
return $this->_exception;
return $this->exception;
}
}
+33 -26
View File
@@ -15,6 +15,7 @@
namespace Webman\Http;
use Webman\File;
use function pathinfo;
/**
* Class UploadFile
@@ -25,80 +26,86 @@ class UploadFile extends File
/**
* @var string
*/
protected $_uploadName = null;
protected $uploadName = null;
/**
* @var string
*/
protected $_uploadMimeType = null;
protected $uploadMimeType = null;
/**
* @var int
*/
protected $_uploadErrorCode = null;
protected $uploadErrorCode = null;
/**
* UploadFile constructor.
*
* @param string $file_name
* @param string $upload_name
* @param string $upload_mime_type
* @param int $upload_error_code
* @param string $fileName
* @param string $uploadName
* @param string $uploadMimeType
* @param int $uploadErrorCode
*/
public function __construct(string $file_name, string $upload_name, string $upload_mime_type, int $upload_error_code)
public function __construct(string $fileName, string $uploadName, string $uploadMimeType, int $uploadErrorCode)
{
$this->_uploadName = $upload_name;
$this->_uploadMimeType = $upload_mime_type;
$this->_uploadErrorCode = $upload_error_code;
parent::__construct($file_name);
$this->uploadName = $uploadName;
$this->uploadMimeType = $uploadMimeType;
$this->uploadErrorCode = $uploadErrorCode;
parent::__construct($fileName);
}
/**
* GetUploadName
* @return string
*/
public function getUploadName()
public function getUploadName(): ?string
{
return $this->_uploadName;
return $this->uploadName;
}
/**
* GetUploadMimeType
* @return string
*/
public function getUploadMimeType()
public function getUploadMimeType(): ?string
{
return $this->_uploadMimeType;
return $this->uploadMimeType;
}
/**
* @return mixed
* GetUploadExtension
* @return string
*/
public function getUploadExtension()
public function getUploadExtension(): string
{
return \pathinfo($this->_uploadName, PATHINFO_EXTENSION);
return pathinfo($this->uploadName, PATHINFO_EXTENSION);
}
/**
* GetUploadErrorCode
* @return int
*/
public function getUploadErrorCode()
public function getUploadErrorCode(): ?int
{
return $this->_uploadErrorCode;
return $this->uploadErrorCode;
}
/**
* IsValid
* @return bool
*/
public function isValid()
public function isValid(): bool
{
return $this->_uploadErrorCode === UPLOAD_ERR_OK;
return $this->uploadErrorCode === UPLOAD_ERR_OK;
}
/**
* @deprecated
* GetUploadMineType
* @return string
* @deprecated
*/
public function getUploadMineType()
public function getUploadMineType(): ?string
{
return $this->_uploadMimeType;
return $this->uploadMimeType;
}
}
+8 -8
View File
@@ -35,23 +35,23 @@ class Install
}
/**
* installByRelation
* InstallByRelation
* @return void
*/
public static function installByRelation()
{
foreach (static::$pathRelation as $source => $dest) {
if ($pos = strrpos($dest, '/')) {
$parent_dir = base_path() . '/' . substr($dest, 0, $pos);
if (!is_dir($parent_dir)) {
mkdir($parent_dir, 0777, true);
$parentDir = base_path() . '/' . substr($dest, 0, $pos);
if (!is_dir($parentDir)) {
mkdir($parentDir, 0777, true);
}
}
$source_file = __DIR__ . "/$source";
copy_dir($source_file, base_path() . "/$dest", true);
$sourceFile = __DIR__ . "/$source";
copy_dir($sourceFile, base_path() . "/$dest", true);
echo "Create $dest\r\n";
if (is_file($source_file)) {
@unlink($source_file);
if (is_file($sourceFile)) {
@unlink($sourceFile);
}
}
}
+39 -23
View File
@@ -1,7 +1,4 @@
<?php
namespace Webman;
/**
* This file is part of webman.
*
@@ -14,34 +11,52 @@ namespace Webman;
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Webman;
use RuntimeException;
use function array_merge;
use function array_reverse;
use function is_array;
use function method_exists;
class Middleware
{
/**
* @var array
*/
protected static $_instances = [];
protected static $instances = [];
/**
* @param array $all_middlewares
* @param mixed $allMiddlewares
* @param string $plugin
* @return void
*/
public static function load($all_middlewares, string $plugin = '')
public static function load($allMiddlewares, string $plugin = '')
{
if (!\is_array($all_middlewares)) {
if (!is_array($allMiddlewares)) {
return;
}
foreach ($all_middlewares as $app_name => $middlewares) {
if (!\is_array($middlewares)) {
throw new \RuntimeException('Bad middleware config');
foreach ($allMiddlewares as $appName => $middlewares) {
if (!is_array($middlewares)) {
throw new RuntimeException('Bad middleware config');
}
foreach ($middlewares as $class_name) {
if (\method_exists($class_name, 'process')) {
static::$_instances[$plugin][$app_name][] = [$class_name, 'process'];
if ($appName === '@') {
$plugin = '';
}
if (strpos($appName, 'plugin.') !== false) {
$explode = explode('.', $appName, 4);
$plugin = $explode[1];
$appName = $explode[2] ?? '';
}
foreach ($middlewares as $className) {
if (method_exists($className, 'process')) {
static::$instances[$plugin][$appName][] = [$className, 'process'];
} else {
// @todo Log
echo "middleware $class_name::process not exsits\n";
echo "middleware $className::process not exsits\n";
}
}
}
@@ -49,23 +64,24 @@ class Middleware
/**
* @param string $plugin
* @param string $app_name
* @param bool $with_global_middleware
* @param string $appName
* @param bool $withGlobalMiddleware
* @return array|mixed
*/
public static function getMiddleware(string $plugin, string $app_name, bool $with_global_middleware = true)
public static function getMiddleware(string $plugin, string $appName, bool $withGlobalMiddleware = true)
{
$global_middleware = $with_global_middleware && isset(static::$_instances[$plugin]['']) ? static::$_instances[$plugin][''] : [];
if ($app_name === '') {
return \array_reverse($global_middleware);
$globalMiddleware = static::$instances['']['@'] ?? [];
$appGlobalMiddleware = $withGlobalMiddleware && isset(static::$instances[$plugin]['']) ? static::$instances[$plugin][''] : [];
if ($appName === '') {
return array_reverse(array_merge($globalMiddleware, $appGlobalMiddleware));
}
$app_middleware = static::$_instances[$plugin][$app_name] ?? [];
return \array_reverse(\array_merge($global_middleware, $app_middleware));
$appMiddleware = static::$instances[$plugin][$appName] ?? [];
return array_reverse(array_merge($globalMiddleware, $appGlobalMiddleware, $appMiddleware));
}
/**
* @deprecated
* @return void
* @deprecated
*/
public static function container($_)
{
+159 -108
View File
@@ -16,8 +16,24 @@ namespace Webman;
use FastRoute\Dispatcher\GroupCountBased;
use FastRoute\RouteCollector;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Webman\Route\Route as RouteObject;
use function array_diff;
use function array_values;
use function class_exists;
use function explode;
use function FastRoute\simpleDispatcher;
use function in_array;
use function is_array;
use function is_callable;
use function is_file;
use function is_scalar;
use function is_string;
use function json_encode;
use function method_exists;
use function strpos;
/**
* Class Route
@@ -28,124 +44,129 @@ class Route
/**
* @var Route
*/
protected static $_instance = null;
protected static $instance = null;
/**
* @var GroupCountBased
*/
protected static $_dispatcher = null;
protected static $dispatcher = null;
/**
* @var RouteCollector
*/
protected static $_collector = null;
protected static $collector = null;
/**
* @var null|callable
*/
protected static $_fallback = [];
protected static $fallback = [];
/**
* @var array
*/
protected static $_nameList = [];
protected static $nameList = [];
/**
* @var string
*/
protected static $_groupPrefix = '';
protected static $groupPrefix = '';
/**
* @var bool
*/
protected static $_disableDefaultRoute = [];
protected static $disableDefaultRoute = [];
/**
* @var RouteObject[]
*/
protected static $_allRoutes = [];
protected static $allRoutes = [];
/**
* @var RouteObject[]
*/
protected $_routes = [];
protected $routes = [];
/**
* @var Route[]
*/
protected $children = [];
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function get(string $path, $callback)
public static function get(string $path, $callback): RouteObject
{
return static::addRoute('GET', $path, $callback);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function post(string $path, $callback)
public static function post(string $path, $callback): RouteObject
{
return static::addRoute('POST', $path, $callback);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function put(string $path, $callback)
public static function put(string $path, $callback): RouteObject
{
return static::addRoute('PUT', $path, $callback);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function patch(string $path, $callback)
public static function patch(string $path, $callback): RouteObject
{
return static::addRoute('PATCH', $path, $callback);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function delete(string $path, $callback)
public static function delete(string $path, $callback): RouteObject
{
return static::addRoute('DELETE', $path, $callback);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function head(string $path, $callback)
public static function head(string $path, $callback): RouteObject
{
return static::addRoute('HEAD', $path, $callback);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function options(string $path, $callback)
public static function options(string $path, $callback): RouteObject
{
return static::addRoute('OPTIONS', $path, $callback);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function any(string $path, $callback)
public static function any(string $path, $callback): RouteObject
{
return static::addRoute(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'], $path, $callback);
}
@@ -153,10 +174,10 @@ class Route
/**
* @param $method
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
public static function add($method, string $path, $callback)
public static function add($method, string $path, $callback): RouteObject
{
return static::addRoute($method, $path, $callback);
}
@@ -166,18 +187,22 @@ class Route
* @param callable|null $callback
* @return static
*/
public static function group($path, callable $callback = null)
public static function group($path, callable $callback = null): Route
{
if ($callback === null) {
$callback = $path;
$path = '';
}
$previous_group_prefix = static::$_groupPrefix;
static::$_groupPrefix = $previous_group_prefix . $path;
$instance = static::$_instance = new static;
static::$_collector->addGroup($path, $callback);
static::$_instance = null;
static::$_groupPrefix = $previous_group_prefix;
$previousGroupPrefix = static::$groupPrefix;
static::$groupPrefix = $previousGroupPrefix . $path;
$previousInstance = static::$instance;
$instance = static::$instance = new static;
static::$collector->addGroup($path, $callback);
static::$groupPrefix = $previousGroupPrefix;
static::$instance = $previousInstance;
if ($previousInstance) {
$previousInstance->addChild($instance);
}
return $instance;
}
@@ -190,41 +215,41 @@ class Route
public static function resource(string $name, string $controller, array $options = [])
{
$name = trim($name, '/');
if (\is_array($options) && !empty($options)) {
$diff_options = \array_diff($options, ['index', 'create', 'store', 'update', 'show', 'edit', 'destroy', 'recovery']);
if (!empty($diff_options)) {
foreach ($diff_options as $action) {
static::any("/{$name}/{$action}[/{id}]", [$controller, $action])->name("{$name}.{$action}");
if (is_array($options) && !empty($options)) {
$diffOptions = array_diff($options, ['index', 'create', 'store', 'update', 'show', 'edit', 'destroy', 'recovery']);
if (!empty($diffOptions)) {
foreach ($diffOptions as $action) {
static::any("/$name/{$action}[/{id}]", [$controller, $action])->name("$name.{$action}");
}
}
// 注册路由 由于顺序不同会导致路由无效 因此不适用循环注册
if (\in_array('index', $options)) static::get("/{$name}", [$controller, 'index'])->name("{$name}.index");
if (\in_array('create', $options)) static::get("/{$name}/create", [$controller, 'create'])->name("{$name}.create");
if (\in_array('store', $options)) static::post("/{$name}", [$controller, 'store'])->name("{$name}.store");
if (\in_array('update', $options)) static::put("/{$name}/{id}", [$controller, 'update'])->name("{$name}.update");
if (\in_array('show', $options)) static::get("/{$name}/{id}", [$controller, 'show'])->name("{$name}.show");
if (\in_array('edit', $options)) static::get("/{$name}/{id}/edit", [$controller, 'edit'])->name("{$name}.edit");
if (\in_array('destroy', $options)) static::delete("/{$name}/{id}", [$controller, 'destroy'])->name("{$name}.destroy");
if (\in_array('recovery', $options)) static::put("/{$name}/{id}/recovery", [$controller, 'recovery'])->name("{$name}.recovery");
if (in_array('index', $options)) static::get("/$name", [$controller, 'index'])->name("$name.index");
if (in_array('create', $options)) static::get("/$name/create", [$controller, 'create'])->name("$name.create");
if (in_array('store', $options)) static::post("/$name", [$controller, 'store'])->name("$name.store");
if (in_array('update', $options)) static::put("/$name/{id}", [$controller, 'update'])->name("$name.update");
if (in_array('show', $options)) static::get("/$name/{id}", [$controller, 'show'])->name("$name.show");
if (in_array('edit', $options)) static::get("/$name/{id}/edit", [$controller, 'edit'])->name("$name.edit");
if (in_array('destroy', $options)) static::delete("/$name/{id}", [$controller, 'destroy'])->name("$name.destroy");
if (in_array('recovery', $options)) static::put("/$name/{id}/recovery", [$controller, 'recovery'])->name("$name.recovery");
} else {
//为空时自动注册所有常用路由
if (\method_exists($controller, 'index')) static::get("/{$name}", [$controller, 'index'])->name("{$name}.index");
if (\method_exists($controller, 'create')) static::get("/{$name}/create", [$controller, 'create'])->name("{$name}.create");
if (\method_exists($controller, 'store')) static::post("/{$name}", [$controller, 'store'])->name("{$name}.store");
if (\method_exists($controller, 'update')) static::put("/{$name}/{id}", [$controller, 'update'])->name("{$name}.update");
if (\method_exists($controller, 'show')) static::get("/{$name}/{id}", [$controller, 'show'])->name("{$name}.show");
if (\method_exists($controller, 'edit')) static::get("/{$name}/{id}/edit", [$controller, 'edit'])->name("{$name}.edit");
if (\method_exists($controller, 'destroy')) static::delete("/{$name}/{id}", [$controller, 'destroy'])->name("{$name}.destroy");
if (\method_exists($controller, 'recovery')) static::put("/{$name}/{id}/recovery", [$controller, 'recovery'])->name("{$name}.recovery");
if (method_exists($controller, 'index')) static::get("/$name", [$controller, 'index'])->name("$name.index");
if (method_exists($controller, 'create')) static::get("/$name/create", [$controller, 'create'])->name("$name.create");
if (method_exists($controller, 'store')) static::post("/$name", [$controller, 'store'])->name("$name.store");
if (method_exists($controller, 'update')) static::put("/$name/{id}", [$controller, 'update'])->name("$name.update");
if (method_exists($controller, 'show')) static::get("/$name/{id}", [$controller, 'show'])->name("$name.show");
if (method_exists($controller, 'edit')) static::get("/$name/{id}/edit", [$controller, 'edit'])->name("$name.edit");
if (method_exists($controller, 'destroy')) static::delete("/$name/{id}", [$controller, 'destroy'])->name("$name.destroy");
if (method_exists($controller, 'recovery')) static::put("/$name/{id}/recovery", [$controller, 'recovery'])->name("$name.recovery");
}
}
/**
* @return RouteObject[]
*/
public static function getRoutes()
public static function getRoutes(): array
{
return static::$_allRoutes;
return static::$allRoutes;
}
/**
@@ -234,26 +259,31 @@ class Route
*/
public static function disableDefaultRoute($plugin = '')
{
static::$_disableDefaultRoute[$plugin] = true;
static::$disableDefaultRoute[$plugin] = true;
}
/**
* @param string $plugin
* @return bool
*/
public static function hasDisableDefaultRoute($plugin = '')
public static function hasDisableDefaultRoute(string $plugin = ''): bool
{
return static::$_disableDefaultRoute[$plugin] ?? false;
return static::$disableDefaultRoute[$plugin] ?? false;
}
/**
* @param $middleware
* @return $this
*/
public function middleware($middleware)
public function middleware($middleware): Route
{
foreach ($this->_routes as $route) {
foreach ($this->routes as $route) {
$route->middleware($middleware);
}
foreach ($this->getChildren() as $child) {
$child->middleware($middleware);
}
return $this;
}
/**
@@ -261,59 +291,75 @@ class Route
*/
public function collect(RouteObject $route)
{
$this->_routes[] = $route;
$this->routes[] = $route;
}
/**
* @param $name
* @param string $name
* @param RouteObject $instance
*/
public static function setByName(string $name, RouteObject $instance)
{
static::$_nameList[$name] = $instance;
static::$nameList[$name] = $instance;
}
/**
* @param $name
* @param string $name
* @return null|RouteObject
*/
public static function getByName(string $name)
public static function getByName(string $name): ?RouteObject
{
return static::$_nameList[$name] ?? null;
return static::$nameList[$name] ?? null;
}
/**
* @param Route $route
* @return void
*/
public function addChild(Route $route)
{
$this->children[] = $route;
}
/**
* @return Route[]
*/
public function getChildren()
{
return $this->children;
}
/**
* @param string $method
* @param string $path
* @return array
*/
public static function dispatch($method, string $path)
public static function dispatch(string $method, string $path): array
{
return static::$_dispatcher->dispatch($method, $path);
return static::$dispatcher->dispatch($method, $path);
}
/**
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return callable|false|string[]
*/
public static function convertToCallable(string $path, $callback)
{
if (\is_string($callback) && \strpos($callback, '@')) {
$callback = \explode('@', $callback, 2);
if (is_string($callback) && strpos($callback, '@')) {
$callback = explode('@', $callback, 2);
}
if (!\is_array($callback)) {
if (!\is_callable($callback)) {
$call_str = \is_scalar($callback) ? $callback : 'Closure';
echo "Route $path $call_str is not callable\n";
if (!is_array($callback)) {
if (!is_callable($callback)) {
$callStr = is_scalar($callback) ? $callback : 'Closure';
echo "Route $path $callStr is not callable\n";
return false;
}
} else {
$callback = \array_values($callback);
if (!isset($callback[1]) || !\class_exists($callback[0]) || !\method_exists($callback[0], $callback[1])) {
echo "Route $path " . \json_encode($callback) . " is not callable\n";
$callback = array_values($callback);
if (!isset($callback[1]) || !class_exists($callback[0]) || !method_exists($callback[0], $callback[1])) {
echo "Route $path " . json_encode($callback) . " is not callable\n";
return false;
}
}
@@ -322,56 +368,57 @@ class Route
}
/**
* @param array $methods
* @param array|string $methods
* @param string $path
* @param callable $callback
* @param callable|mixed $callback
* @return RouteObject
*/
protected static function addRoute($methods, string $path, $callback)
protected static function addRoute($methods, string $path, $callback): RouteObject
{
$route = new RouteObject($methods, static::$_groupPrefix . $path, $callback);
static::$_allRoutes[] = $route;
$route = new RouteObject($methods, static::$groupPrefix . $path, $callback);
static::$allRoutes[] = $route;
if ($callback = static::convertToCallable($path, $callback)) {
static::$_collector->addRoute($methods, $path, ['callback' => $callback, 'route' => $route]);
static::$collector->addRoute($methods, $path, ['callback' => $callback, 'route' => $route]);
}
if (static::$_instance) {
static::$_instance->collect($route);
if (static::$instance) {
static::$instance->collect($route);
}
return $route;
}
/**
* @param array $paths
* Load.
* @param mixed $paths
* @return void
*/
public static function load($paths)
{
if (!\is_array($paths)) {
if (!is_array($paths)) {
return;
}
static::$_dispatcher = simpleDispatcher(function (RouteCollector $route) use ($paths) {
static::$dispatcher = simpleDispatcher(function (RouteCollector $route) use ($paths) {
Route::setCollector($route);
foreach ($paths as $config_path) {
$route_config_file = $config_path . '/route.php';
if (\is_file($route_config_file)) {
require_once $route_config_file;
foreach ($paths as $configPath) {
$routeConfigFile = $configPath . '/route.php';
if (is_file($routeConfigFile)) {
require_once $routeConfigFile;
}
if (!is_dir($plugin_config_path = $config_path . '/plugin')) {
if (!is_dir($pluginConfigPath = $configPath . '/plugin')) {
continue;
}
$dir_iterator = new \RecursiveDirectoryIterator($plugin_config_path, \FilesystemIterator::FOLLOW_SYMLINKS);
$iterator = new \RecursiveIteratorIterator($dir_iterator);
$dirIterator = new RecursiveDirectoryIterator($pluginConfigPath, FilesystemIterator::FOLLOW_SYMLINKS);
$iterator = new RecursiveIteratorIterator($dirIterator);
foreach ($iterator as $file) {
if ($file->getBaseName('.php') !== 'route') {
continue;
}
$app_config_file = pathinfo($file, PATHINFO_DIRNAME) . '/app.php';
if (!is_file($app_config_file)) {
$appConfigFile = pathinfo($file, PATHINFO_DIRNAME) . '/app.php';
if (!is_file($appConfigFile)) {
continue;
}
$app_config = include $app_config_file;
if (empty($app_config['enable'])) {
$appConfig = include $appConfigFile;
if (empty($appConfig['enable'])) {
continue;
}
require_once $file;
@@ -381,35 +428,39 @@ class Route
}
/**
* SetCollector.
* @param RouteCollector $route
* @return void
*/
public static function setCollector(RouteCollector $route)
{
static::$_collector = $route;
static::$collector = $route;
}
/**
* @param callable $callback
* Fallback.
* @param callable|mixed $callback
* @param string $plugin
* @return void
*/
public static function fallback(callable $callback, string $plugin = '')
{
static::$_fallback[$plugin] = $callback;
static::$fallback[$plugin] = $callback;
}
/**
* GetFallBack.
* @param string $plugin
* @return callable|null
*/
public static function getFallback(string $plugin = '')
public static function getFallback(string $plugin = ''): ?callable
{
return static::$_fallback[$plugin] ?? null;
return static::$fallback[$plugin] ?? null;
}
/**
* @deprecated
* @return void
* @deprecated
*/
public static function container()
{
+48 -37
View File
@@ -14,9 +14,11 @@
namespace Webman\Route;
use FastRoute\Dispatcher\GroupCountBased;
use FastRoute\RouteCollector;
use Webman\Route as Router;
use function array_merge;
use function count;
use function preg_replace_callback;
use function str_replace;
/**
* Class Route
@@ -27,112 +29,119 @@ class Route
/**
* @var string|null
*/
protected $_name = null;
protected $name = null;
/**
* @var array
*/
protected $_methods = [];
protected $methods = [];
/**
* @var string
*/
protected $_path = '';
protected $path = '';
/**
* @var callable
*/
protected $_callback = null;
protected $callback = null;
/**
* @var array
*/
protected $_middlewares = [];
protected $middlewares = [];
/**
* @var array
*/
protected $_params = [];
protected $params = [];
/**
* Route constructor.
*
* @param array $methods
* @param string $path
* @param callable $callback
*/
public function __construct($methods, string $path, $callback)
{
$this->_methods = (array)$methods;
$this->_path = $path;
$this->_callback = $callback;
$this->methods = (array)$methods;
$this->path = $path;
$this->callback = $callback;
}
/**
* @return mixed|null
* Get name.
* @return string|null
*/
public function getName()
public function getName(): ?string
{
return $this->_name ?? null;
return $this->name ?? null;
}
/**
* Name.
* @param string $name
* @return $this
*/
public function name(string $name)
public function name(string $name): Route
{
$this->_name = $name;
$this->name = $name;
Router::setByName($name, $this);
return $this;
}
/**
* Middleware.
* @param mixed $middleware
* @return $this|array
*/
public function middleware($middleware = null)
{
if ($middleware === null) {
return $this->_middlewares;
return $this->middlewares;
}
$this->_middlewares = \array_merge($this->_middlewares, is_array($middleware) ? $middleware : [$middleware]);
$this->middlewares = array_merge($this->middlewares, is_array($middleware) ? array_reverse($middleware) : [$middleware]);
return $this;
}
/**
* GetPath.
* @return string
*/
public function getPath()
public function getPath(): string
{
return $this->_path;
return $this->path;
}
/**
* GetMethods.
* @return array
*/
public function getMethods()
public function getMethods(): array
{
return $this->_methods;
return $this->methods;
}
/**
* @return callable
* GetCallback.
* @return callable|null
*/
public function getCallback()
{
return $this->_callback;
return $this->callback;
}
/**
* GetMiddleware.
* @return array
*/
public function getMiddleware()
public function getMiddleware(): array
{
return $this->_middlewares;
return $this->middlewares;
}
/**
* Param.
* @param string|null $name
* @param $default
* @return array|mixed|null
@@ -140,32 +149,34 @@ class Route
public function param(string $name = null, $default = null)
{
if ($name === null) {
return $this->_params;
return $this->params;
}
return $this->_params[$name] ?? $default;
return $this->params[$name] ?? $default;
}
/**
* SetParams.
* @param array $params
* @return $this
*/
public function setParams(array $params)
public function setParams(array $params): Route
{
$this->_params = \array_merge($this->_params, $params);
$this->params = array_merge($this->params, $params);
return $this;
}
/**
* @param $parameters
* Url.
* @param array $parameters
* @return string
*/
public function url($parameters = [])
public function url(array $parameters = []): string
{
if (empty($parameters)) {
return $this->_path;
return $this->path;
}
$path = \str_replace(['[', ']'], '', $this->_path);
$path = \preg_replace_callback('/\{(.*?)(?:\:[^\}]*?)*?\}/', function ($matches) use (&$parameters) {
$path = str_replace(['[', ']'], '', $this->path);
$path = preg_replace_callback('/\{(.*?)(?:\:[^\}]*?)*?\}/', function ($matches) use (&$parameters) {
if (!$parameters) {
return $matches[0];
}
@@ -182,7 +193,7 @@ class Route
}
return $matches[0];
}, $path);
return \count($parameters) > 0 ? $path . '?' . http_build_query($parameters) : $path;
return count($parameters) > 0 ? $path . '?' . http_build_query($parameters) : $path;
}
}
@@ -14,8 +14,6 @@
namespace Webman\Session;
use FastRoute\Dispatcher\GroupCountBased;
use FastRoute\RouteCollector;
use Workerman\Protocols\Http\Session\FileSessionHandler as FileHandler;
/**
@@ -14,8 +14,6 @@
namespace Webman\Session;
use FastRoute\Dispatcher\GroupCountBased;
use FastRoute\RouteCollector;
use Workerman\Protocols\Http\Session\RedisSessionHandler as RedisHandler;
/**
+12 -6
View File
@@ -14,6 +14,10 @@
namespace Webman;
use function array_diff;
use function array_map;
use function scandir;
/**
* Class Util
* @package Webman
@@ -21,17 +25,19 @@ namespace Webman;
class Util
{
/**
* @param string $path
* ScanDir.
* @param string $basePath
* @param bool $withBasePath
* @return array
*/
public static function scanDir(string $base_path, $with_base_path = true): array
public static function scanDir(string $basePath, bool $withBasePath = true): array
{
if (!is_dir($base_path)) {
if (!is_dir($basePath)) {
return [];
}
$paths = \array_diff(\scandir($base_path), array('.', '..')) ?: [];
return $with_base_path ? \array_map(function($path) use ($base_path) {
return $base_path . DIRECTORY_SEPARATOR . $path;
$paths = array_diff(scandir($basePath), array('.', '..')) ?: [];
return $withBasePath ? array_map(static function ($path) use ($basePath) {
return $basePath . DIRECTORY_SEPARATOR . $path;
}, $paths) : $paths;
}
+5 -4
View File
@@ -17,10 +17,11 @@ namespace Webman;
interface View
{
/**
* @param $template
* @param $vars
* @param null $app
* Render.
* @param string $template
* @param array $vars
* @param string|null $app
* @return string
*/
static function render(string $template, array $vars, string $app = null);
public static function render(string $template, array $vars, string $app = null): string;
}
+34 -26
View File
@@ -3,15 +3,22 @@
namespace support;
use Dotenv\Dotenv;
use RuntimeException;
use Webman\Config;
use Webman\Util;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http;
use Workerman\Worker;
use function base_path;
use function call_user_func;
use function is_dir;
use function opcache_get_status;
use function opcache_invalidate;
use const DIRECTORY_SEPARATOR;
class App
{
/**
* Run.
* @return void
*/
public static function run()
@@ -29,34 +36,34 @@ class App
static::loadAllConfig(['route', 'container']);
$error_reporting = config('app.error_reporting');
if (isset($error_reporting)) {
error_reporting($error_reporting);
$errorReporting = config('app.error_reporting');
if (isset($errorReporting)) {
error_reporting($errorReporting);
}
if ($timezone = config('app.default_timezone')) {
date_default_timezone_set($timezone);
}
$runtime_logs_path = runtime_path() . DIRECTORY_SEPARATOR . 'logs';
if (!file_exists($runtime_logs_path) || !is_dir($runtime_logs_path)) {
if (!mkdir($runtime_logs_path, 0777, true)) {
throw new \RuntimeException("Failed to create runtime logs directory. Please check the permission.");
$runtimeLogsPath = runtime_path() . DIRECTORY_SEPARATOR . 'logs';
if (!file_exists($runtimeLogsPath) || !is_dir($runtimeLogsPath)) {
if (!mkdir($runtimeLogsPath, 0777, true)) {
throw new RuntimeException("Failed to create runtime logs directory. Please check the permission.");
}
}
$runtime_views_path = runtime_path() . DIRECTORY_SEPARATOR . 'views';
if (!file_exists($runtime_views_path) || !is_dir($runtime_views_path)) {
if (!mkdir($runtime_views_path, 0777, true)) {
throw new \RuntimeException("Failed to create runtime views directory. Please check the permission.");
$runtimeViewsPath = runtime_path() . DIRECTORY_SEPARATOR . 'views';
if (!file_exists($runtimeViewsPath) || !is_dir($runtimeViewsPath)) {
if (!mkdir($runtimeViewsPath, 0777, true)) {
throw new RuntimeException("Failed to create runtime views directory. Please check the permission.");
}
}
Worker::$onMasterReload = function () {
if (function_exists('opcache_get_status')) {
if ($status = \opcache_get_status()) {
if ($status = opcache_get_status()) {
if (isset($status['scripts']) && $scripts = $status['scripts']) {
foreach (array_keys($scripts) as $file) {
\opcache_invalidate($file, true);
opcache_invalidate($file, true);
}
}
}
@@ -78,7 +85,7 @@ class App
if ($config['listen']) {
$worker = new Worker($config['listen'], $config['context']);
$property_map = [
$propertyMap = [
'name',
'count',
'user',
@@ -87,36 +94,36 @@ class App
'transport',
'protocol'
];
foreach ($property_map as $property) {
foreach ($propertyMap as $property) {
if (isset($config[$property])) {
$worker->$property = $config[$property];
}
}
$worker->onWorkerStart = function ($worker) {
require_once \base_path() . '/support/bootstrap.php';
require_once base_path() . '/support/bootstrap.php';
$app = new \Webman\App(config('app.request_class', Request::class), Log::channel('default'), app_path(), public_path());
$worker->onMessage = [$app, 'onMessage'];
\call_user_func([$app, 'onWorkerStart'], $worker);
call_user_func([$app, 'onWorkerStart'], $worker);
};
}
// Windows does not support custom processes.
if (\DIRECTORY_SEPARATOR === '/') {
foreach (config('process', []) as $process_name => $config) {
worker_start($process_name, $config);
if (DIRECTORY_SEPARATOR === '/') {
foreach (config('process', []) as $processName => $config) {
worker_start($processName, $config);
}
foreach (config('plugin', []) as $firm => $projects) {
foreach ($projects as $name => $project) {
if (!is_array($project)) {
continue;
}
foreach ($project['process'] ?? [] as $process_name => $config) {
worker_start("plugin.$firm.$name.$process_name", $config);
foreach ($project['process'] ?? [] as $processName => $config) {
worker_start("plugin.$firm.$name.$processName", $config);
}
}
foreach ($projects['process'] ?? [] as $process_name => $config) {
worker_start("plugin.$firm.$process_name", $config);
foreach ($projects['process'] ?? [] as $processName => $config) {
worker_start("plugin.$firm.$processName", $config);
}
}
}
@@ -125,6 +132,7 @@ class App
}
/**
* LoadAllConfig.
* @param array $excludes
* @return void
*/
@@ -134,7 +142,7 @@ class App
$directory = base_path() . '/plugin';
foreach (Util::scanDir($directory, false) as $name) {
$dir = "$directory/$name/config";
if (\is_dir($dir)) {
if (is_dir($dir)) {
Config::load($dir, $excludes, "plugin.$name");
}
}
+4 -4
View File
@@ -24,18 +24,18 @@ class Cache
/**
* @var Psr16Cache
*/
public static $_instance = null;
public static $instance = null;
/**
* @return Psr16Cache
*/
public static function instance()
{
if (!static::$_instance) {
if (!static::$instance) {
$adapter = new RedisAdapter(Redis::connection()->client());
self::$_instance = new Psr16Cache($adapter);
self::$instance = new Psr16Cache($adapter);
}
return static::$_instance;
return static::$instance;
}
/**
@@ -14,7 +14,6 @@
namespace support;
use Psr\Container\ContainerInterface;
use Webman\Config;
/**
@@ -27,7 +26,9 @@ use Webman\Config;
class Container
{
/**
* @return ContainerInterface
* Instance
* @param string $plugin
* @return array|mixed|void|null
*/
public static function instance(string $plugin = '')
{
@@ -0,0 +1,25 @@
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace support;
/**
* Class Context
* @package Webman
*/
class Context extends \Webman\Context
{
}
+2 -1
View File
@@ -14,6 +14,7 @@
namespace support;
use Closure;
use Illuminate\Database\Capsule\Manager;
/**
@@ -24,7 +25,7 @@ use Illuminate\Database\Capsule\Manager;
* @method static int update(string $query, $bindings = [])
* @method static int delete(string $query, $bindings = [])
* @method static bool statement(string $query, $bindings = [])
* @method static mixed transaction(\Closure $callback, $attempts = 1)
* @method static mixed transaction(Closure $callback, $attempts = 1)
* @method static void beginTransaction()
* @method static void rollBack($toLevel = null)
* @method static void commit()
+18 -11
View File
@@ -18,6 +18,9 @@ use Monolog\Formatter\FormatterInterface;
use Monolog\Handler\FormattableHandlerInterface;
use Monolog\Handler\HandlerInterface;
use Monolog\Logger;
use function array_values;
use function config;
use function is_array;
/**
* Class Log
@@ -38,24 +41,26 @@ class Log
/**
* @var array
*/
protected static $_instance = [];
protected static $instance = [];
/**
* Channel.
* @param string $name
* @return Logger
*/
public static function channel(string $name = 'default')
public static function channel(string $name = 'default'): Logger
{
if (!isset(static::$_instance[$name])) {
$config = \config('log', [])[$name];
if (!isset(static::$instance[$name])) {
$config = config('log', [])[$name];
$handlers = self::handlers($config);
$processors = self::processors($config);
static::$_instance[$name] = new Logger($name, $handlers, $processors);
static::$instance[$name] = new Logger($name, $handlers, $processors);
}
return static::$_instance[$name];
return static::$instance[$name];
}
/**
* Handlers.
* @param array $config
* @return array
*/
@@ -76,6 +81,7 @@ class Log
}
/**
* Handler.
* @param string $class
* @param array $constructor
* @param array $formatterConfig
@@ -84,14 +90,14 @@ class Log
protected static function handler(string $class, array $constructor, array $formatterConfig): HandlerInterface
{
/** @var HandlerInterface $handler */
$handler = new $class(... \array_values($constructor));
$handler = new $class(... array_values($constructor));
if ($handler instanceof FormattableHandlerInterface && $formatterConfig) {
$formatterClass = $formatterConfig['class'];
$formatterConstructor = $formatterConfig['constructor'];
/** @var FormatterInterface $formatter */
$formatter = new $formatterClass(... \array_values($formatterConstructor));
$formatter = new $formatterClass(... array_values($formatterConstructor));
$handler->setFormatter($formatter);
}
@@ -100,6 +106,7 @@ class Log
}
/**
* Processors.
* @param array $config
* @return array
*/
@@ -111,8 +118,8 @@ class Log
}
foreach ($config['processors'] ?? [] as $value) {
if (\is_array($value) && isset($value['class'])) {
$value = new $value['class'](... \array_values($value['constructor'] ?? []));;
if (is_array($value) && isset($value['class'])) {
$value = new $value['class'](... array_values($value['constructor'] ?? []));
}
$result[] = $value;
}
@@ -127,6 +134,6 @@ class Log
*/
public static function __callStatic(string $name, array $arguments)
{
return static::channel('default')->{$name}(... $arguments);
return static::channel()->{$name}(... $arguments);
}
}
+145 -135
View File
@@ -14,10 +14,20 @@
namespace support;
use Closure;
use Illuminate\Contracts\Pagination\CursorPaginator;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Processors\Processor;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
/**
* @method static \Illuminate\Database\Eloquent\Model make($attributes = [])
* @method static BaseModel make($attributes = [])
* @method static \Illuminate\Database\Eloquent\Builder withGlobalScope($identifier, $scope)
* @method static \Illuminate\Database\Eloquent\Builder withoutGlobalScope($scope)
* @method static \Illuminate\Database\Eloquent\Builder withoutGlobalScopes($scopes = null)
@@ -25,53 +35,53 @@ use Illuminate\Database\Eloquent\Model as BaseModel;
* @method static \Illuminate\Database\Eloquent\Builder whereKey($id)
* @method static \Illuminate\Database\Eloquent\Builder whereKeyNot($id)
* @method static \Illuminate\Database\Eloquent\Builder where($column, $operator = null, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Eloquent\Model|null firstWhere($column, $operator = null, $value = null, $boolean = 'and')
* @method static BaseModel|null firstWhere($column, $operator = null, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Eloquent\Builder orWhere($column, $operator = null, $value = null)
* @method static \Illuminate\Database\Eloquent\Builder latest($column = null)
* @method static \Illuminate\Database\Eloquent\Builder oldest($column = null)
* @method static \Illuminate\Database\Eloquent\Collection hydrate($items)
* @method static \Illuminate\Database\Eloquent\Collection fromQuery($query, $bindings = [])
* @method static \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null find($id, $columns = [])
* @method static BaseModel|\Illuminate\Database\Eloquent\Collection|static[]|static|null find($id, $columns = [])
* @method static \Illuminate\Database\Eloquent\Collection findMany($ids, $columns = [])
* @method static \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static|static[] findOrFail($id, $columns = [])
* @method static \Illuminate\Database\Eloquent\Model|static findOrNew($id, $columns = [])
* @method static \Illuminate\Database\Eloquent\Model|static firstOrNew($attributes = [], $values = [])
* @method static \Illuminate\Database\Eloquent\Model|static firstOrCreate($attributes = [], $values = [])
* @method static \Illuminate\Database\Eloquent\Model|static updateOrCreate($attributes, $values = [])
* @method static \Illuminate\Database\Eloquent\Model|static firstOrFail($columns = [])
* @method static \Illuminate\Database\Eloquent\Model|static|mixed firstOr($columns = [], $callback = null)
* @method static \Illuminate\Database\Eloquent\Model sole($columns = [])
* @method static BaseModel|\Illuminate\Database\Eloquent\Collection|static|static[] findOrFail($id, $columns = [])
* @method static BaseModel|static findOrNew($id, $columns = [])
* @method static BaseModel|static firstOrNew($attributes = [], $values = [])
* @method static BaseModel|static firstOrCreate($attributes = [], $values = [])
* @method static BaseModel|static updateOrCreate($attributes, $values = [])
* @method static BaseModel|static firstOrFail($columns = [])
* @method static BaseModel|static|mixed firstOr($columns = [], $callback = null)
* @method static BaseModel sole($columns = [])
* @method static mixed value($column)
* @method static \Illuminate\Database\Eloquent\Collection[]|static[] get($columns = [])
* @method static \Illuminate\Database\Eloquent\Model[]|static[] getModels($columns = [])
* @method static BaseModel[]|static[] getModels($columns = [])
* @method static array eagerLoadRelations($models)
* @method static \Illuminate\Support\LazyCollection cursor()
* @method static \Illuminate\Support\Collection pluck($column, $key = null)
* @method static \Illuminate\Contracts\Pagination\LengthAwarePaginator paginate($perPage = null, $columns = [], $pageName = 'page', $page = null)
* @method static \Illuminate\Contracts\Pagination\Paginator simplePaginate($perPage = null, $columns = [], $pageName = 'page', $page = null)
* @method static \Illuminate\Contracts\Pagination\CursorPaginator cursorPaginate($perPage = null, $columns = [], $cursorName = 'cursor', $cursor = null)
* @method static \Illuminate\Database\Eloquent\Model|$this create($attributes = [])
* @method static \Illuminate\Database\Eloquent\Model|$this forceCreate($attributes)
* @method static LazyCollection cursor()
* @method static Collection pluck($column, $key = null)
* @method static LengthAwarePaginator paginate($perPage = null, $columns = [], $pageName = 'page', $page = null)
* @method static Paginator simplePaginate($perPage = null, $columns = [], $pageName = 'page', $page = null)
* @method static CursorPaginator cursorPaginate($perPage = null, $columns = [], $cursorName = 'cursor', $cursor = null)
* @method static BaseModel|$this create($attributes = [])
* @method static BaseModel|$this forceCreate($attributes)
* @method static int upsert($values, $uniqueBy, $update = null)
* @method static void onDelete($callback)
* @method static static|mixed scopes($scopes)
* @method static static applyScopes()
* @method static \Illuminate\Database\Eloquent\Builder without($relations)
* @method static \Illuminate\Database\Eloquent\Builder withOnly($relations)
* @method static \Illuminate\Database\Eloquent\Model newModelInstance($attributes = [])
* @method static BaseModel newModelInstance($attributes = [])
* @method static \Illuminate\Database\Eloquent\Builder withCasts($casts)
* @method static \Illuminate\Database\Query\Builder getQuery()
* @method static Builder getQuery()
* @method static \Illuminate\Database\Eloquent\Builder setQuery($query)
* @method static \Illuminate\Database\Query\Builder toBase()
* @method static Builder toBase()
* @method static array getEagerLoads()
* @method static \Illuminate\Database\Eloquent\Builder setEagerLoads($eagerLoad)
* @method static \Illuminate\Database\Eloquent\Model getModel()
* @method static BaseModel getModel()
* @method static \Illuminate\Database\Eloquent\Builder setModel($model)
* @method static \Closure getMacro($name)
* @method static Closure getMacro($name)
* @method static bool hasMacro($name)
* @method static \Closure getGlobalMacro($name)
* @method static Closure getGlobalMacro($name)
* @method static bool hasGlobalMacro($name)
* @method static static clone()
* @method static static clone ()
* @method static \Illuminate\Database\Eloquent\Builder has($relation, $operator = '>=', $count = 1, $boolean = 'and', $callback = null)
* @method static \Illuminate\Database\Eloquent\Builder orHas($relation, $operator = '>=', $count = 1)
* @method static \Illuminate\Database\Eloquent\Builder doesntHave($relation, $boolean = 'and', $callback = null)
@@ -96,116 +106,116 @@ use Illuminate\Database\Eloquent\Model as BaseModel;
* @method static \Illuminate\Database\Eloquent\Builder withAvg($relation, $column)
* @method static \Illuminate\Database\Eloquent\Builder withExists($relation)
* @method static \Illuminate\Database\Eloquent\Builder mergeConstraintsFrom($from)
* @method static \Illuminate\Support\Collection explain()
* @method static Collection explain()
* @method static bool chunk($count, $callback)
* @method static \Illuminate\Support\Collection chunkMap($callback, $count = 1000)
* @method static Collection chunkMap($callback, $count = 1000)
* @method static bool each($callback, $count = 1000)
* @method static bool chunkById($count, $callback, $column = null, $alias = null)
* @method static bool eachById($callback, $count = 1000, $column = null, $alias = null)
* @method static \Illuminate\Support\LazyCollection lazy($chunkSize = 1000)
* @method static \Illuminate\Support\LazyCollection lazyById($chunkSize = 1000, $column = null, $alias = null)
* @method static \Illuminate\Database\Eloquent\Model|object|static|null first($columns = [])
* @method static \Illuminate\Database\Eloquent\Model|object|null baseSole($columns = [])
* @method static LazyCollection lazy($chunkSize = 1000)
* @method static LazyCollection lazyById($chunkSize = 1000, $column = null, $alias = null)
* @method static BaseModel|object|static|null first($columns = [])
* @method static BaseModel|object|null baseSole($columns = [])
* @method static \Illuminate\Database\Eloquent\Builder tap($callback)
* @method static mixed when($value, $callback, $default = null)
* @method static mixed unless($value, $callback, $default = null)
* @method static \Illuminate\Database\Query\Builder select($columns = [])
* @method static \Illuminate\Database\Query\Builder selectSub($query, $as)
* @method static \Illuminate\Database\Query\Builder selectRaw($expression, $bindings = [])
* @method static \Illuminate\Database\Query\Builder fromSub($query, $as)
* @method static \Illuminate\Database\Query\Builder fromRaw($expression, $bindings = [])
* @method static \Illuminate\Database\Query\Builder addSelect($column)
* @method static \Illuminate\Database\Query\Builder distinct()
* @method static \Illuminate\Database\Query\Builder from($table, $as = null)
* @method static \Illuminate\Database\Query\Builder join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false)
* @method static \Illuminate\Database\Query\Builder joinWhere($table, $first, $operator, $second, $type = 'inner')
* @method static \Illuminate\Database\Query\Builder joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)
* @method static \Illuminate\Database\Query\Builder leftJoin($table, $first, $operator = null, $second = null)
* @method static \Illuminate\Database\Query\Builder leftJoinWhere($table, $first, $operator, $second)
* @method static \Illuminate\Database\Query\Builder leftJoinSub($query, $as, $first, $operator = null, $second = null)
* @method static \Illuminate\Database\Query\Builder rightJoin($table, $first, $operator = null, $second = null)
* @method static \Illuminate\Database\Query\Builder rightJoinWhere($table, $first, $operator, $second)
* @method static \Illuminate\Database\Query\Builder rightJoinSub($query, $as, $first, $operator = null, $second = null)
* @method static \Illuminate\Database\Query\Builder crossJoin($table, $first = null, $operator = null, $second = null)
* @method static \Illuminate\Database\Query\Builder crossJoinSub($query, $as)
* @method static Builder select($columns = [])
* @method static Builder selectSub($query, $as)
* @method static Builder selectRaw($expression, $bindings = [])
* @method static Builder fromSub($query, $as)
* @method static Builder fromRaw($expression, $bindings = [])
* @method static Builder addSelect($column)
* @method static Builder distinct()
* @method static Builder from($table, $as = null)
* @method static Builder join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false)
* @method static Builder joinWhere($table, $first, $operator, $second, $type = 'inner')
* @method static Builder joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)
* @method static Builder leftJoin($table, $first, $operator = null, $second = null)
* @method static Builder leftJoinWhere($table, $first, $operator, $second)
* @method static Builder leftJoinSub($query, $as, $first, $operator = null, $second = null)
* @method static Builder rightJoin($table, $first, $operator = null, $second = null)
* @method static Builder rightJoinWhere($table, $first, $operator, $second)
* @method static Builder rightJoinSub($query, $as, $first, $operator = null, $second = null)
* @method static Builder crossJoin($table, $first = null, $operator = null, $second = null)
* @method static Builder crossJoinSub($query, $as)
* @method static void mergeWheres($wheres, $bindings)
* @method static array prepareValueAndOperator($value, $operator, $useDefault = false)
* @method static \Illuminate\Database\Query\Builder whereColumn($first, $operator = null, $second = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereColumn($first, $operator = null, $second = null)
* @method static \Illuminate\Database\Query\Builder whereRaw($sql, $bindings = [], $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereRaw($sql, $bindings = [])
* @method static \Illuminate\Database\Query\Builder whereIn($column, $values, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder orWhereIn($column, $values)
* @method static \Illuminate\Database\Query\Builder whereNotIn($column, $values, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereNotIn($column, $values)
* @method static \Illuminate\Database\Query\Builder whereIntegerInRaw($column, $values, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder orWhereIntegerInRaw($column, $values)
* @method static \Illuminate\Database\Query\Builder whereIntegerNotInRaw($column, $values, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereIntegerNotInRaw($column, $values)
* @method static \Illuminate\Database\Query\Builder whereNull($columns, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder orWhereNull($column)
* @method static \Illuminate\Database\Query\Builder whereNotNull($columns, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder whereBetween($column, $values, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder whereBetweenColumns($column, $values, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder orWhereBetween($column, $values)
* @method static \Illuminate\Database\Query\Builder orWhereBetweenColumns($column, $values)
* @method static \Illuminate\Database\Query\Builder whereNotBetween($column, $values, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder whereNotBetweenColumns($column, $values, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereNotBetween($column, $values)
* @method static \Illuminate\Database\Query\Builder orWhereNotBetweenColumns($column, $values)
* @method static \Illuminate\Database\Query\Builder orWhereNotNull($column)
* @method static \Illuminate\Database\Query\Builder whereDate($column, $operator, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereDate($column, $operator, $value = null)
* @method static \Illuminate\Database\Query\Builder whereTime($column, $operator, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereTime($column, $operator, $value = null)
* @method static \Illuminate\Database\Query\Builder whereDay($column, $operator, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereDay($column, $operator, $value = null)
* @method static \Illuminate\Database\Query\Builder whereMonth($column, $operator, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereMonth($column, $operator, $value = null)
* @method static \Illuminate\Database\Query\Builder whereYear($column, $operator, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereYear($column, $operator, $value = null)
* @method static \Illuminate\Database\Query\Builder whereNested($callback, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder forNestedWhere()
* @method static \Illuminate\Database\Query\Builder addNestedWhereQuery($query, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder whereExists($callback, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder orWhereExists($callback, $not = false)
* @method static \Illuminate\Database\Query\Builder whereNotExists($callback, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereNotExists($callback)
* @method static \Illuminate\Database\Query\Builder addWhereExistsQuery($query, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder whereRowValues($columns, $operator, $values, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereRowValues($columns, $operator, $values)
* @method static \Illuminate\Database\Query\Builder whereJsonContains($column, $value, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder orWhereJsonContains($column, $value)
* @method static \Illuminate\Database\Query\Builder whereJsonDoesntContain($column, $value, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereJsonDoesntContain($column, $value)
* @method static \Illuminate\Database\Query\Builder whereJsonLength($column, $operator, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orWhereJsonLength($column, $operator, $value = null)
* @method static \Illuminate\Database\Query\Builder dynamicWhere($method, $parameters)
* @method static \Illuminate\Database\Query\Builder groupBy(...$groups)
* @method static \Illuminate\Database\Query\Builder groupByRaw($sql, $bindings = [])
* @method static \Illuminate\Database\Query\Builder having($column, $operator = null, $value = null, $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orHaving($column, $operator = null, $value = null)
* @method static \Illuminate\Database\Query\Builder havingBetween($column, $values, $boolean = 'and', $not = false)
* @method static \Illuminate\Database\Query\Builder havingRaw($sql, $bindings = [], $boolean = 'and')
* @method static \Illuminate\Database\Query\Builder orHavingRaw($sql, $bindings = [])
* @method static \Illuminate\Database\Query\Builder orderBy($column, $direction = 'asc')
* @method static \Illuminate\Database\Query\Builder orderByDesc($column)
* @method static \Illuminate\Database\Query\Builder inRandomOrder($seed = '')
* @method static \Illuminate\Database\Query\Builder orderByRaw($sql, $bindings = [])
* @method static \Illuminate\Database\Query\Builder skip($value)
* @method static \Illuminate\Database\Query\Builder offset($value)
* @method static \Illuminate\Database\Query\Builder take($value)
* @method static \Illuminate\Database\Query\Builder limit($value)
* @method static \Illuminate\Database\Query\Builder forPage($page, $perPage = 15)
* @method static \Illuminate\Database\Query\Builder forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id')
* @method static \Illuminate\Database\Query\Builder forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')
* @method static \Illuminate\Database\Query\Builder reorder($column = null, $direction = 'asc')
* @method static \Illuminate\Database\Query\Builder union($query, $all = false)
* @method static \Illuminate\Database\Query\Builder unionAll($query)
* @method static \Illuminate\Database\Query\Builder lock($value = true)
* @method static \Illuminate\Database\Query\Builder lockForUpdate()
* @method static \Illuminate\Database\Query\Builder sharedLock()
* @method static \Illuminate\Database\Query\Builder beforeQuery($callback)
* @method static Builder whereColumn($first, $operator = null, $second = null, $boolean = 'and')
* @method static Builder orWhereColumn($first, $operator = null, $second = null)
* @method static Builder whereRaw($sql, $bindings = [], $boolean = 'and')
* @method static Builder orWhereRaw($sql, $bindings = [])
* @method static Builder whereIn($column, $values, $boolean = 'and', $not = false)
* @method static Builder orWhereIn($column, $values)
* @method static Builder whereNotIn($column, $values, $boolean = 'and')
* @method static Builder orWhereNotIn($column, $values)
* @method static Builder whereIntegerInRaw($column, $values, $boolean = 'and', $not = false)
* @method static Builder orWhereIntegerInRaw($column, $values)
* @method static Builder whereIntegerNotInRaw($column, $values, $boolean = 'and')
* @method static Builder orWhereIntegerNotInRaw($column, $values)
* @method static Builder whereNull($columns, $boolean = 'and', $not = false)
* @method static Builder orWhereNull($column)
* @method static Builder whereNotNull($columns, $boolean = 'and')
* @method static Builder whereBetween($column, $values, $boolean = 'and', $not = false)
* @method static Builder whereBetweenColumns($column, $values, $boolean = 'and', $not = false)
* @method static Builder orWhereBetween($column, $values)
* @method static Builder orWhereBetweenColumns($column, $values)
* @method static Builder whereNotBetween($column, $values, $boolean = 'and')
* @method static Builder whereNotBetweenColumns($column, $values, $boolean = 'and')
* @method static Builder orWhereNotBetween($column, $values)
* @method static Builder orWhereNotBetweenColumns($column, $values)
* @method static Builder orWhereNotNull($column)
* @method static Builder whereDate($column, $operator, $value = null, $boolean = 'and')
* @method static Builder orWhereDate($column, $operator, $value = null)
* @method static Builder whereTime($column, $operator, $value = null, $boolean = 'and')
* @method static Builder orWhereTime($column, $operator, $value = null)
* @method static Builder whereDay($column, $operator, $value = null, $boolean = 'and')
* @method static Builder orWhereDay($column, $operator, $value = null)
* @method static Builder whereMonth($column, $operator, $value = null, $boolean = 'and')
* @method static Builder orWhereMonth($column, $operator, $value = null)
* @method static Builder whereYear($column, $operator, $value = null, $boolean = 'and')
* @method static Builder orWhereYear($column, $operator, $value = null)
* @method static Builder whereNested($callback, $boolean = 'and')
* @method static Builder forNestedWhere()
* @method static Builder addNestedWhereQuery($query, $boolean = 'and')
* @method static Builder whereExists($callback, $boolean = 'and', $not = false)
* @method static Builder orWhereExists($callback, $not = false)
* @method static Builder whereNotExists($callback, $boolean = 'and')
* @method static Builder orWhereNotExists($callback)
* @method static Builder addWhereExistsQuery($query, $boolean = 'and', $not = false)
* @method static Builder whereRowValues($columns, $operator, $values, $boolean = 'and')
* @method static Builder orWhereRowValues($columns, $operator, $values)
* @method static Builder whereJsonContains($column, $value, $boolean = 'and', $not = false)
* @method static Builder orWhereJsonContains($column, $value)
* @method static Builder whereJsonDoesntContain($column, $value, $boolean = 'and')
* @method static Builder orWhereJsonDoesntContain($column, $value)
* @method static Builder whereJsonLength($column, $operator, $value = null, $boolean = 'and')
* @method static Builder orWhereJsonLength($column, $operator, $value = null)
* @method static Builder dynamicWhere($method, $parameters)
* @method static Builder groupBy(...$groups)
* @method static Builder groupByRaw($sql, $bindings = [])
* @method static Builder having($column, $operator = null, $value = null, $boolean = 'and')
* @method static Builder orHaving($column, $operator = null, $value = null)
* @method static Builder havingBetween($column, $values, $boolean = 'and', $not = false)
* @method static Builder havingRaw($sql, $bindings = [], $boolean = 'and')
* @method static Builder orHavingRaw($sql, $bindings = [])
* @method static Builder orderBy($column, $direction = 'asc')
* @method static Builder orderByDesc($column)
* @method static Builder inRandomOrder($seed = '')
* @method static Builder orderByRaw($sql, $bindings = [])
* @method static Builder skip($value)
* @method static Builder offset($value)
* @method static Builder take($value)
* @method static Builder limit($value)
* @method static Builder forPage($page, $perPage = 15)
* @method static Builder forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id')
* @method static Builder forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')
* @method static Builder reorder($column = null, $direction = 'asc')
* @method static Builder union($query, $all = false)
* @method static Builder unionAll($query)
* @method static Builder lock($value = true)
* @method static Builder lockForUpdate()
* @method static Builder sharedLock()
* @method static Builder beforeQuery($callback)
* @method static void applyBeforeQueryCallbacks()
* @method static string toSql()
* @method static int getCountForPagination($columns = [])
@@ -228,19 +238,19 @@ use Illuminate\Database\Eloquent\Model as BaseModel;
* @method static int insertUsing($columns, $query)
* @method static bool updateOrInsert($attributes, $values = [])
* @method static void truncate()
* @method static \Illuminate\Database\Query\Expression raw($value)
* @method static Expression raw($value)
* @method static array getBindings()
* @method static array getRawBindings()
* @method static \Illuminate\Database\Query\Builder setBindings($bindings, $type = 'where')
* @method static \Illuminate\Database\Query\Builder addBinding($value, $type = 'where')
* @method static \Illuminate\Database\Query\Builder mergeBindings($query)
* @method static Builder setBindings($bindings, $type = 'where')
* @method static Builder addBinding($value, $type = 'where')
* @method static Builder mergeBindings($query)
* @method static array cleanBindings($bindings)
* @method static \Illuminate\Database\Query\Processors\Processor getProcessor()
* @method static \Illuminate\Database\Query\Grammars\Grammar getGrammar()
* @method static \Illuminate\Database\Query\Builder useWritePdo()
* @method static Processor getProcessor()
* @method static Grammar getGrammar()
* @method static Builder useWritePdo()
* @method static static cloneWithout($properties)
* @method static static cloneWithoutBindings($except)
* @method static \Illuminate\Database\Query\Builder dump()
* @method static Builder dump()
* @method static void dd()
* @method static void macro($name, $macro)
* @method static void mixin($mixin, $replace = true)
+71 -35
View File
@@ -2,71 +2,107 @@
namespace support;
use function defined;
use function is_callable;
use function is_file;
use function method_exists;
class Plugin
{
/**
* @param $event
* Install.
* @param mixed $event
* @return void
*/
public static function install($event)
{
static::findHepler();
$operation = $event->getOperation();
$autoload = \method_exists($operation, 'getPackage') ? $operation->getPackage()->getAutoload() : $operation->getTargetPackage()->getAutoload();
if (!isset($autoload['psr-4'])) {
return;
}
foreach ($autoload['psr-4'] as $namespace => $path) {
$install_function = "\\{$namespace}Install::install";
$plugin_const = "\\{$namespace}Install::WEBMAN_PLUGIN";
if (\defined($plugin_const) && \is_callable($install_function)) {
$install_function();
static::findHelper();
$psr4 = static::getPsr4($event);
foreach ($psr4 as $namespace => $path) {
$pluginConst = "\\{$namespace}Install::WEBMAN_PLUGIN";
if (!defined($pluginConst)) {
continue;
}
$installFunction = "\\{$namespace}Install::install";
if (is_callable($installFunction)) {
$installFunction(true);
}
}
}
/**
* @param $event
* Update.
* @param mixed $event
* @return void
*/
public static function update($event)
{
static::install($event);
}
/**
* @param $event
* @return void
*/
public static function uninstall($event)
{
static::findHepler();
$autoload = $event->getOperation()->getPackage()->getAutoload();
if (!isset($autoload['psr-4'])) {
return;
}
foreach ($autoload['psr-4'] as $namespace => $path) {
$uninstall_function = "\\{$namespace}Install::uninstall";
$plugin_const = "\\{$namespace}Install::WEBMAN_PLUGIN";
if (defined($plugin_const) && is_callable($uninstall_function)) {
$uninstall_function();
static::findHelper();
$psr4 = static::getPsr4($event);
foreach ($psr4 as $namespace => $path) {
$pluginConst = "\\{$namespace}Install::WEBMAN_PLUGIN";
if (!defined($pluginConst)) {
continue;
}
$updateFunction = "\\{$namespace}Install::update";
if (is_callable($updateFunction)) {
$updateFunction();
continue;
}
$installFunction = "\\{$namespace}Install::install";
if (is_callable($installFunction)) {
$installFunction(false);
}
}
}
/**
* Uninstall.
* @param mixed $event
* @return void
*/
protected static function findHepler()
public static function uninstall($event)
{
static::findHelper();
$psr4 = static::getPsr4($event);
foreach ($psr4 as $namespace => $path) {
$pluginConst = "\\{$namespace}Install::WEBMAN_PLUGIN";
if (!defined($pluginConst)) {
continue;
}
$uninstallFunction = "\\{$namespace}Install::uninstall";
if (is_callable($uninstallFunction)) {
$uninstallFunction();
}
}
}
/**
* Get psr-4 info
*
* @param mixed $event
* @return array
*/
protected static function getPsr4($event)
{
$operation = $event->getOperation();
$autoload = method_exists($operation, 'getPackage') ? $operation->getPackage()->getAutoload() : $operation->getTargetPackage()->getAutoload();
return $autoload['psr-4'] ?? [];
}
/**
* FindHelper.
* @return void
*/
protected static function findHelper()
{
// Plugin.php in vendor
$file = __DIR__ . '/../../../../../support/helpers.php';
if (\is_file($file)) {
if (is_file($file)) {
require_once $file;
return;
}
// Plugin.php in webman
require_once __DIR__ . '/helpers.php';
}
}
+17 -13
View File
@@ -15,10 +15,13 @@
namespace support;
use Illuminate\Events\Dispatcher;
use Illuminate\Redis\Events\CommandExecuted;
use Illuminate\Redis\Connections\Connection;
use Illuminate\Redis\RedisManager;
use Workerman\Timer;
use Workerman\Worker;
use function class_exists;
use function config;
use function in_array;
/**
@@ -209,7 +212,7 @@ class Redis
/**
* @var RedisManager
*/
protected static $_instance = null;
protected static $instance = null;
/**
* need to install phpredis extension
@@ -225,7 +228,7 @@ class Redis
/**
* Support client collection
*/
static $_allowClient = [
static $allowClient = [
self::PHPREDIS_CLIENT,
self::PREDIS_CLIENT
];
@@ -233,26 +236,27 @@ class Redis
/**
* @return RedisManager
*/
public static function instance()
public static function instance(): ?RedisManager
{
if (!static::$_instance) {
$config = \config('redis');
if (!static::$instance) {
$config = config('redis');
$client = $config['client'] ?? self::PHPREDIS_CLIENT;
if (!\in_array($client, static::$_allowClient)) {
if (!in_array($client, static::$allowClient)) {
$client = self::PHPREDIS_CLIENT;
}
static::$_instance = new RedisManager('', $client, $config);
static::$instance = new RedisManager('', $client, $config);
}
return static::$_instance;
return static::$instance;
}
/**
* Connection.
* @param string $name
* @return \Illuminate\Redis\Connections\Connection
* @return Connection
*/
public static function connection(string $name = 'default')
public static function connection(string $name = 'default'): Connection
{
static $timers = [];
$connection = static::instance()->connection($name);
@@ -260,7 +264,7 @@ class Redis
$timers[$name] = Worker::getAllWorkers() ? Timer::add(55, function () use ($connection) {
$connection->get('ping');
}) : 1;
if (\class_exists(Dispatcher::class)) {
if (class_exists(Dispatcher::class)) {
$connection->setEventDispatcher(new Dispatcher());
}
}
@@ -274,6 +278,6 @@ class Redis
*/
public static function __callStatic(string $name, array $arguments)
{
return static::connection('default')->{$name}(... $arguments);
return static::connection()->{$name}(... $arguments);
}
}
+27 -12
View File
@@ -14,8 +14,18 @@
namespace support;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use Symfony\Component\Translation\Translator;
use Webman\Exception\NotFoundException;
use function basename;
use function config;
use function get_realpath;
use function pathinfo;
use function request;
use function substr;
/**
* Class Translation
@@ -30,22 +40,24 @@ class Translation
/**
* @var Translator[]
*/
protected static $_instance = [];
protected static $instance = [];
/**
* Instance.
* @param string $plugin
* @return Translator
* @throws NotFoundException
*/
public static function instance(string $plugin = '')
public static function instance(string $plugin = ''): Translator
{
if (!isset(static::$_instance[$plugin])) {
$config = \config($plugin ? "plugin.$plugin.translation" : 'translation', []);
if (!isset(static::$instance[$plugin])) {
$config = config($plugin ? "plugin.$plugin.translation" : 'translation', []);
// Phar support. Compatible with the 'realpath' function in the phar file.
if (!$translations_path = \get_realpath($config['path'])) {
if (!$translationsPath = get_realpath($config['path'])) {
throw new NotFoundException("File {$config['path']} not found");
}
static::$_instance[$plugin] = $translator = new Translator($config['locale']);
static::$instance[$plugin] = $translator = new Translator($config['locale']);
$translator->setFallbackLocales($config['fallback_locale']);
$classes = [
@@ -61,17 +73,20 @@ class Translation
foreach ($classes as $class => $opts) {
$translator->addLoader($opts['format'], new $class);
foreach (\glob($translations_path . DIRECTORY_SEPARATOR . '*' . DIRECTORY_SEPARATOR . '*' . $opts['extension']) as $file) {
$domain = \basename($file, $opts['extension']);
$dir_name = \pathinfo($file, PATHINFO_DIRNAME);
$locale = \substr(strrchr($dir_name, DIRECTORY_SEPARATOR), 1);
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($translationsPath, FilesystemIterator::SKIP_DOTS));
$files = new RegexIterator($iterator, '/^.+' . preg_quote($opts['extension']) . '$/i', RegexIterator::GET_MATCH);
foreach ($files as $file) {
$file = $file[0];
$domain = basename($file, $opts['extension']);
$dirName = pathinfo($file, PATHINFO_DIRNAME);
$locale = substr(strrchr($dirName, DIRECTORY_SEPARATOR), 1);
if ($domain && $locale) {
$translator->addResource($opts['format'], $file, $locale, $domain);
}
}
}
}
return static::$_instance[$plugin];
return static::$instance[$plugin];
}
/**
@@ -82,7 +97,7 @@ class Translation
*/
public static function __callStatic(string $name, array $arguments)
{
$request = \request();
$request = request();
$plugin = $request->plugin ?? '';
return static::instance($plugin)->{$name}(... $arguments);
}
+7 -3
View File
@@ -14,18 +14,22 @@
namespace support;
use function config;
use function request;
class View
{
/**
* Assign.
* @param mixed $name
* @param mixed $value
* @return void
*/
public static function assign($name, $value = null)
{
$request = \request();
$plugin = $request->plugin ?? '';
$handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler');
$request = request();
$plugin = $request->plugin ?? '';
$handler = config($plugin ? "plugin.$plugin.view.handler" : 'view.handler');
$handler::assign($name, $value);
}
}
@@ -14,17 +14,22 @@
namespace support\bootstrap;
use Illuminate\Container\Container;
use Illuminate\Container\Container as IlluminateContainer;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Connection;
use Illuminate\Database\MySqlConnection;
use Illuminate\Events\Dispatcher;
use Illuminate\Pagination\Paginator;
use Jenssegers\Mongodb\Connection as MongodbConnection;
use support\Db;
use Illuminate\Pagination\CursorPaginator;
use Illuminate\Pagination\Cursor;
use Jenssegers\Mongodb\Connection as JenssegersMongodbConnection;
use MongoDB\Laravel\Connection as LaravelMongodbConnection;
use support\Container;
use Throwable;
use Webman\Bootstrap;
use Workerman\Timer;
use Workerman\Worker;
use function class_exists;
use function config;
/**
* Class Laravel
@@ -33,41 +38,41 @@ use Workerman\Worker;
class LaravelDb implements Bootstrap
{
/**
* @param Worker $worker
* @param Worker|null $worker
*
* @return void
*/
public static function start($worker)
public static function start(?Worker $worker)
{
if (!class_exists(Capsule::class)) {
return;
}
$config = \config('database', []);
$config = config('database', []);
$connections = $config['connections'] ?? [];
if (!$connections) {
return;
}
$capsule = new Capsule;
$capsule = new Capsule(IlluminateContainer::getInstance());
$capsule->getDatabaseManager()->extend('mongodb', function ($config, $name) {
$config['name'] = $name;
return new MongodbConnection($config);
return class_exists(LaravelMongodbConnection::class) ? new LaravelMongodbConnection($config) : new JenssegersMongodbConnection($config);
});
$default = $config['default'] ?? false;
if ($default) {
$default_config = $connections[$config['default']];
$capsule->addConnection($default_config);
$defaultConfig = $connections[$config['default']];
$capsule->addConnection($defaultConfig);
}
foreach ($connections as $name => $config) {
$capsule->addConnection($config, $name);
}
if (\class_exists(Dispatcher::class)) {
$capsule->setEventDispatcher(new Dispatcher(new Container));
if (class_exists(Dispatcher::class) && !$capsule->getEventDispatcher()) {
$capsule->setEventDispatcher(Container::make(Dispatcher::class, [IlluminateContainer::getInstance()]));
}
$capsule->setAsGlobal();
@@ -78,7 +83,7 @@ class LaravelDb implements Bootstrap
if ($worker) {
Timer::add(55, function () use ($default, $connections, $capsule) {
foreach ($capsule->getDatabaseManager()->getConnections() as $connection) {
/* @var \Illuminate\Database\MySqlConnection $connection **/
/* @var MySqlConnection $connection **/
if ($connection->getConfig('driver') == 'mysql') {
try {
$connection->select('select 1');
@@ -100,14 +105,19 @@ class LaravelDb implements Bootstrap
$request = request();
return $request ? $request->path(): '/';
});
Paginator::currentPageResolver(function ($page_name = 'page') {
Paginator::currentPageResolver(function ($pageName = 'page') {
$request = request();
if (!$request) {
return 1;
}
$page = (int)($request->input($page_name, 1));
$page = (int)($request->input($pageName, 1));
return $page > 0 ? $page : 1;
});
if (class_exists(CursorPaginator::class)) {
CursorPaginator::currentCursorResolver(function ($cursorName = 'cursor') {
return Cursor::fromEncoded(request()->input($cursorName));
});
}
}
}
}
@@ -18,6 +18,8 @@ use Webman\Bootstrap;
use Workerman\Protocols\Http;
use Workerman\Protocols\Http\Session as SessionBase;
use Workerman\Worker;
use function config;
use function property_exists;
/**
* Class Session
@@ -27,13 +29,13 @@ class Session implements Bootstrap
{
/**
* @param Worker $worker
* @param Worker|null $worker
* @return void
*/
public static function start($worker)
public static function start(?Worker $worker)
{
$config = \config('session');
if (\property_exists(SessionBase::class, 'name')) {
$config = config('session');
if (property_exists(SessionBase::class, 'name')) {
SessionBase::$name = $config['session_name'];
} else {
Http::sessionName($config['session_name']);
@@ -51,7 +53,7 @@ class Session implements Bootstrap
'secure' => 'secure',
];
foreach ($map as $key => $name) {
if (isset($config[$key]) && \property_exists(SessionBase::class, $name)) {
if (isset($config[$key]) && property_exists(SessionBase::class, $name)) {
SessionBase::${$name} = $config[$key];
}
}
@@ -15,8 +15,9 @@
namespace support\exception;
use Exception;
use Webman\Http\Response;
use Webman\Http\Request;
use Webman\Http\Response;
use function json_encode;
/**
* Class BusinessException
@@ -28,9 +29,9 @@ class BusinessException extends Exception
{
if ($request->expectsJson()) {
$code = $this->getCode();
$json = ['code' => $code ? $code : 500, 'msg' => $this->getMessage()];
$json = ['code' => $code ?: 500, 'msg' => $this->getMessage()];
return new Response(200, ['Content-Type' => 'application/json'],
\json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
return new Response(200, [], $this->getMessage());
}
+23 -13
View File
@@ -16,6 +16,13 @@ namespace support\view;
use Jenssegers\Blade\Blade as BladeView;
use Webman\View;
use function app_path;
use function array_merge;
use function base_path;
use function config;
use function is_array;
use function request;
use function runtime_path;
/**
* Class Blade
@@ -27,43 +34,46 @@ class Blade implements View
/**
* @var array
*/
protected static $_vars = [];
protected static $vars = [];
/**
* Assign.
* @param string|array $name
* @param mixed $value
*/
public static function assign($name, $value = null)
{
static::$_vars = \array_merge(static::$_vars, \is_array($name) ? $name : [$name => $value]);
static::$vars = array_merge(static::$vars, is_array($name) ? $name : [$name => $value]);
}
/**
* Render.
* @param string $template
* @param array $vars
* @param string|null $app
* @param string|null $plugin
* @return string
*/
public static function render(string $template, array $vars, string $app = null)
public static function render(string $template, array $vars, string $app = null, string $plugin = null): string
{
static $views = [];
$request = \request();
$plugin = $request->plugin ?? '';
$request = request();
$plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
$app = $app === null ? $request->app : $app;
$config_prefix = $plugin ? "plugin.$plugin." : '';
$base_view_path = $plugin ? \base_path() . "/plugin/$plugin/app" : \app_path();
$key = "{$plugin}-{$request->app}";
$configPrefix = $plugin ? "plugin.$plugin." : '';
$baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path();
$key = "$plugin-$app";
if (!isset($views[$key])) {
$view_path = $app === '' ? "$base_view_path/view" : "$base_view_path/$app/view";
$views[$key] = new BladeView($view_path, \runtime_path() . '/views');
$extension = \config("{$config_prefix}view.extension");
$viewPath = $app === '' ? "$baseViewPath/view" : "$baseViewPath/$app/view";
$views[$key] = new BladeView($viewPath, runtime_path() . '/views');
$extension = config("{$configPrefix}view.extension");
if ($extension) {
$extension($views[$key]);
}
}
$vars = \array_merge(static::$_vars, $vars);
$vars = array_merge(static::$vars, $vars);
$content = $views[$key]->render($template, $vars);
static::$_vars = [];
static::$vars = [];
return $content;
}
}
+30 -17
View File
@@ -14,8 +14,18 @@
namespace support\view;
use Webman\View;
use Throwable;
use Webman\View;
use function app_path;
use function array_merge;
use function base_path;
use function config;
use function extract;
use function is_array;
use function ob_end_clean;
use function ob_get_clean;
use function ob_start;
use function request;
/**
* Class Raw
@@ -26,46 +36,49 @@ class Raw implements View
/**
* @var array
*/
protected static $_vars = [];
protected static $vars = [];
/**
* Assign.
* @param string|array $name
* @param mixed $value
*/
public static function assign($name, $value = null)
{
static::$_vars = \array_merge(static::$_vars, \is_array($name) ? $name : [$name => $value]);
static::$vars = array_merge(static::$vars, is_array($name) ? $name : [$name => $value]);
}
/**
* Render.
* @param string $template
* @param array $vars
* @param string|null $app
* @param string|null $plugin
* @return false|string
*/
public static function render(string $template, array $vars, string $app = null)
public static function render(string $template, array $vars, string $app = null, string $plugin = null): string
{
$request = \request();
$plugin = $request->plugin ?? '';
$config_prefix = $plugin ? "plugin.$plugin." : '';
$view_suffix = \config("{$config_prefix}view.options.view_suffix", 'html');
$request = request();
$plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
$configPrefix = $plugin ? "plugin.$plugin." : '';
$viewSuffix = config("{$configPrefix}view.options.view_suffix", 'html');
$app = $app === null ? $request->app : $app;
$base_view_path = $plugin ? \base_path() . "/plugin/$plugin/app" : \app_path();
$__template_path__ = $app === '' ? "$base_view_path/view/$template.$view_suffix" : "$base_view_path/$app/view/$template.$view_suffix";
$baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path();
$__template_path__ = $app === '' ? "$baseViewPath/view/$template.$viewSuffix" : "$baseViewPath/$app/view/$template.$viewSuffix";
\extract(static::$_vars);
\extract($vars);
\ob_start();
extract(static::$vars);
extract($vars);
ob_start();
// Try to include php file.
try {
include $__template_path__;
} catch (Throwable $e) {
static::$_vars = [];
\ob_end_clean();
static::$vars = [];
ob_end_clean();
throw $e;
}
static::$_vars = [];
return \ob_get_clean();
static::$vars = [];
return ob_get_clean();
}
}
@@ -16,6 +16,15 @@ namespace support\view;
use think\Template;
use Webman\View;
use function app_path;
use function array_merge;
use function base_path;
use function config;
use function is_array;
use function ob_get_clean;
use function ob_start;
use function request;
use function runtime_path;
/**
* Class Blade
@@ -26,44 +35,47 @@ class ThinkPHP implements View
/**
* @var array
*/
protected static $_vars = [];
protected static $vars = [];
/**
* Assign.
* @param string|array $name
* @param mixed $value
*/
public static function assign($name, $value = null)
{
static::$_vars = \array_merge(static::$_vars, \is_array($name) ? $name : [$name => $value]);
static::$vars = array_merge(static::$vars, is_array($name) ? $name : [$name => $value]);
}
/**
* Render.
* @param string $template
* @param array $vars
* @param string|null $app
* @param string|null $plugin
* @return false|string
*/
public static function render(string $template, array $vars, string $app = null)
public static function render(string $template, array $vars, string $app = null, string $plugin = null): string
{
$request = \request();
$plugin = $request->plugin ?? '';
$request = request();
$plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
$app = $app === null ? $request->app : $app;
$config_prefix = $plugin ? "plugin.$plugin." : '';
$view_suffix = \config("{$config_prefix}view.options.view_suffix", 'html');
$base_view_path = $plugin ? \base_path() . "/plugin/$plugin/app" : \app_path();
$view_path = $app === '' ? "$base_view_path/view/" : "$base_view_path/$app/view/";
$default_options = [
'view_path' => $view_path,
'cache_path' => \runtime_path() . '/views/',
'view_suffix' => $view_suffix
$configPrefix = $plugin ? "plugin.$plugin." : '';
$viewSuffix = config("{$configPrefix}view.options.view_suffix", 'html');
$baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path();
$viewPath = $app === '' ? "$baseViewPath/view/" : "$baseViewPath/$app/view/";
$defaultOptions = [
'view_path' => $viewPath,
'cache_path' => runtime_path() . '/views/',
'view_suffix' => $viewSuffix
];
$options = $default_options + \config("{$config_prefix}view.options", []);
$options = array_merge($defaultOptions, config("{$configPrefix}view.options", []));
$views = new Template($options);
\ob_start();
$vars = \array_merge(static::$_vars, $vars);
ob_start();
$vars = array_merge(static::$vars, $vars);
$views->fetch($template, $vars);
$content = \ob_get_clean();
static::$_vars = [];
$content = ob_get_clean();
static::$vars = [];
return $content;
}
}
+27 -15
View File
@@ -15,8 +15,17 @@
namespace support\view;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
use Webman\View;
use function app_path;
use function array_merge;
use function base_path;
use function config;
use function is_array;
use function request;
/**
* Class Blade
@@ -27,44 +36,47 @@ class Twig implements View
/**
* @var array
*/
protected static $_vars = [];
protected static $vars = [];
/**
* Assign.
* @param string|array $name
* @param mixed $value
*/
public static function assign($name, $value = null)
{
static::$_vars = \array_merge(static::$_vars, \is_array($name) ? $name : [$name => $value]);
static::$vars = array_merge(static::$vars, is_array($name) ? $name : [$name => $value]);
}
/**
* Render.
* @param string $template
* @param array $vars
* @param string|null $app
* @param string|null $plugin
* @return string
*/
public static function render(string $template, array $vars, string $app = null)
public static function render(string $template, array $vars, string $app = null, string $plugin = null): string
{
static $views = [];
$request = \request();
$plugin = $request->plugin ?? '';
$request = request();
$plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
$app = $app === null ? $request->app : $app;
$config_prefix = $plugin ? "plugin.$plugin." : '';
$view_suffix = \config("{$config_prefix}view.options.view_suffix", 'html');
$key = "{$plugin}-{$request->app}";
$configPrefix = $plugin ? "plugin.$plugin." : '';
$viewSuffix = config("{$configPrefix}view.options.view_suffix", 'html');
$key = "$plugin-$app";
if (!isset($views[$key])) {
$base_view_path = $plugin ? \base_path() . "/plugin/$plugin/app" : \app_path();
$view_path = $app === '' ? "$base_view_path/view/" : "$base_view_path/$app/view/";
$views[$key] = new Environment(new FilesystemLoader($view_path), \config("{$config_prefix}view.options", []));
$extension = \config("{$config_prefix}view.extension");
$baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path();
$viewPath = $app === '' ? "$baseViewPath/view/" : "$baseViewPath/$app/view/";
$views[$key] = new Environment(new FilesystemLoader($viewPath), config("{$configPrefix}view.options", []));
$extension = config("{$configPrefix}view.extension");
if ($extension) {
$extension($views[$key]);
}
}
$vars = \array_merge(static::$_vars, $vars);
$content = $views[$key]->render("$template.$view_suffix", $vars);
static::$_vars = [];
$vars = array_merge(static::$vars, $vars);
$content = $views[$key]->render("$template.$viewSuffix", $vars);
static::$vars = [];
return $content;
}
}