This commit is contained in:
as2252258@163.com
2021-05-03 04:22:47 +08:00
32 changed files with 1440 additions and 1431 deletions
+7 -10
View File
@@ -28,23 +28,20 @@ defined('ASPECT_ERROR') or define('ASPECT_ERROR', 'Aspect annotation must implem
} }
/**
* @param array $handler
* @return mixed public function execute(mixed $class, mixed $method = ''): mixed
* @throws Exception
*/
public function execute(array $handler): mixed
{ {
// TODO: Change the autogenerated stub // TODO: Change the autogenerated stub
if (!in_array(IAspect::class, class_implements($this->aspect))) { if (!in_array(IAspect::class, class_implements($this->aspect))) {
throw new Exception(ASPECT_ERROR . IAspect::class); throw new Exception(ASPECT_ERROR . IAspect::class);
} }
/** @var Aop $aop */ /** @var Aop $aop */
$aop = Snowflake::app()->get('aop'); $aop = Snowflake::app()->get('aop');
$aop->aop_add($handler, $this->aspect); $aop->aop_add([$class, $method], $this->aspect);
return parent::execute($handler); return true;
} }
+3 -2
View File
@@ -5,6 +5,7 @@ namespace Annotation;
use Exception; use Exception;
use HttpServer\IInterface\Task;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -32,10 +33,10 @@ use Snowflake\Snowflake;
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): bool public function execute(mixed $class, mixed $method = null): mixed
{ {
$async = Snowflake::app()->getAsync(); $async = Snowflake::app()->getAsync();
$async->addAsync($this->name, current($handler)); $async->addAsync($this->name, $class);
return true; return true;
} }
+5 -8
View File
@@ -22,14 +22,11 @@ abstract class Attribute implements IAnnotation
{ {
/**
* @param array $handler
* @return mixed
*/
public function execute(array $handler): mixed
{
return $this;
}
public function execute(mixed $class, mixed $method = ''): mixed
{
// TODO: Implement execute() method.
return true;
}
} }
+2 -2
View File
@@ -33,10 +33,10 @@ use Snowflake\Event as SEvent;
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): bool public function execute(mixed $class, mixed $method = null): mixed
{ {
// TODO: Implement execute() method. // TODO: Implement execute() method.
SEvent::on($this->name, $handler, $this->params); SEvent::on($this->name, [$class, $method], $this->params);
return true; return true;
} }
-80
View File
@@ -1,80 +0,0 @@
<?php
namespace Annotation;
class FileTree
{
private array $files = [];
private array $childes = [];
private string $_filePath = '';
/**
* @param $path
* @return $this|null
*/
public function getChild($path): ?static
{
if (!isset($this->childes[$path])) {
$this->addChild($path, new FileTree());
}
return $this->childes[$path];
}
/**
* @param string $path
* @param FileTree $fileTree
*/
public function addChild(string $path, FileTree $fileTree)
{
$this->childes[$path] = $fileTree;
}
/**
* @param string $className
* @param string $path
*/
public function addFile(string $className, string $path)
{
$this->files[] = $className;
$this->_filePath = $path;
}
/**
* @return array
*/
public function getFiles(): array
{
return $this->files;
}
/**
* @return string
*/
public function getDirPath(): string
{
return $this->_filePath;
}
/**
* @return array
*/
public function getChildes(): array
{
return $this->childes;
}
}
+5 -5
View File
@@ -9,11 +9,11 @@ use Closure;
interface IAnnotation interface IAnnotation
{ {
/** /**
* @param array $handler * @param array $handler
* @return mixed * @return mixed
*/ */
public function execute(array $handler): mixed; public function execute(mixed $class, mixed $method = ''): mixed;
} }
+46 -46
View File
@@ -16,59 +16,59 @@ use Snowflake\Snowflake;
{ {
/** /**
* Inject constructor. * Inject constructor.
* @param string $className * @param string $className
* @param array $args * @param array $args
*/ */
public function __construct(private string $className, private array $args = []) public function __construct(private string $className, private array $args = [])
{ {
} }
/** /**
* @param array $handler * @param array $handler
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): mixed public function execute(mixed $class, mixed $method = null): mixed
{ {
$injectValue = $this->parseInjectValue(); $injectValue = $this->parseInjectValue();
if (!($handler[1] instanceof ReflectionProperty)) { if (!($method instanceof ReflectionProperty)) {
$handler[1] = new ReflectionProperty($handler[0], $handler[1]); $method = new ReflectionProperty($class, $method);
} }
/** @var ReflectionProperty $handler [1] */ /** @var ReflectionProperty $class */
if ($handler[1]->isPrivate() || $handler[1]->isProtected()) { if ($method->isPrivate() || $method->isProtected()) {
$method = 'set' . ucfirst($handler[1]->getName()); $method = 'set' . ucfirst($class->getName());
if (!method_exists($handler[0], $method)) { if (!method_exists($class, $method)) {
return false; return false;
} }
$handler[0]->$method($injectValue); $class->$method($injectValue);
} else { } else {
$handler[0]->{$handler[1]->getName()} = $injectValue; $class->{$method->getName()} = $injectValue;
} }
return $handler[0]; return true;
} }
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function parseInjectValue(): mixed private function parseInjectValue(): mixed
{ {
if (class_exists($this->className)) { if (class_exists($this->className)) {
$injectValue = Snowflake::createObject($this->className, $this->args); $injectValue = Snowflake::createObject($this->className, $this->args);
} else if (Snowflake::app()->has($this->className)) { } else if (Snowflake::app()->has($this->className)) {
$injectValue = Snowflake::app()->get($this->className); $injectValue = Snowflake::app()->get($this->className);
} else { } else {
$injectValue = $this->className; $injectValue = $this->className;
} }
// if (!empty($this->args) && is_object($injectValue)) { // if (!empty($this->args) && is_object($injectValue)) {
// Snowflake::configure($injectValue, $this->args); // Snowflake::configure($injectValue, $this->args);
// } // }
return $injectValue; return $injectValue;
} }
} }
+4 -4
View File
@@ -30,17 +30,17 @@ use Snowflake\Snowflake;
* @param array $handler * @param array $handler
* @return mixed * @return mixed
*/ */
public function execute(array $handler): mixed public function execute(mixed $class, mixed $method = null): mixed
{ {
if (!($handler[0] instanceof ConsumerInterface)) { if (!($class instanceof ConsumerInterface)) {
return false; return false;
} }
/** @var TaskContainer $container */ /** @var TaskContainer $container */
$container = Snowflake::app()->get('kafka-container'); $container = Snowflake::app()->get('kafka-container');
$container->addConsumer($this->topic, [$handler[0], 'onHandler']); $container->addConsumer($this->topic, [$class, 'onHandler']);
return parent::execute($handler); // TODO: Change the autogenerated stub return true;
} }
+105 -49
View File
@@ -33,9 +33,6 @@ class Loader extends BaseObject
private array $_directory = []; private array $_directory = [];
private FileTree $files;
/** /**
* @return array * @return array
*/ */
@@ -44,13 +41,6 @@ class Loader extends BaseObject
return $this->_directory; return $this->_directory;
} }
public function init()
{
$this->files = new FileTree();
}
/** /**
* @param $path * @param $path
* @param $namespace * @param $namespace
@@ -102,7 +92,7 @@ class Loader extends BaseObject
} }
foreach ($properties as $property => $attributes) { foreach ($properties as $property => $attributes) {
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {
$attribute->execute([$handler, $property]); $attribute->execute($handler, $property);
} }
} }
return $this; return $this;
@@ -173,47 +163,20 @@ class Loader extends BaseObject
if ($path->getExtension() !== 'php') { if ($path->getExtension() !== 'php') {
return; return;
} }
$replace = Snowflake::getDi()->getReflect($this->explodeFileName($path, $namespace)); $replace = $this->getReflect($path, $namespace);
if (empty($replace) || count($replace->getAttributes(Target::class)) < 1) { if (empty($replace) || count($replace->getAttributes(Target::class)) < 1) {
return; return;
} }
$this->appendFileToDirectory($path->getRealPath(), $replace->getName()); $this->appendFileToDirectory($path->getRealPath(), $replace->getName());
$_array = ['handler' => $replace->newInstance(), 'target' => [], 'methods' => [], 'property' => []]; $_array['handler'] = $replace->getName();
foreach ($replace->getAttributes() as $attribute) { $_array['target'] = [];
if ($attribute->getName() == Attribute::class) { $_array['methods'] = [];
continue; $_array['property'] = [];
}
if ($attribute->getName() == Target::class) {
continue;
}
$_array['target'][] = $attribute->newInstance();
}
$methods = $replace->getMethods(ReflectionMethod::IS_PUBLIC); $_array = $this->_targets($replace, $_array);
foreach ($methods as $method) { $_array = $this->_methods($replace, $_array);
$_method = []; $_array = $this->_properties($replace, $_array);
foreach ($method->getAttributes() as $attribute) {
if (!class_exists($attribute->getName())) {
continue;
}
$_method[] = $attribute->newInstance();
}
$_array['methods'][$method->getName()] = $_method;
}
$methods = $replace->getProperties();
foreach ($methods as $method) {
$_property = [];
if ($method->isStatic()) continue;
foreach ($method->getAttributes() as $attribute) {
if (!class_exists($attribute->getName())) {
continue;
}
$_property[] = $attribute->newInstance();
}
$_array['property'][$method->getName()] = $_property;
}
$this->_fileMap[$replace->getFileName()] = $replace->getName(); $this->_fileMap[$replace->getFileName()] = $replace->getName();
@@ -224,6 +187,84 @@ class Loader extends BaseObject
} }
/**
* @param string $path
* @param string $namespace
* @return \ReflectionClass|null
* @throws \ReflectionException
* @throws \Snowflake\Exception\NotFindClassException
*/
private function getReflect(DirectoryIterator $path, string $namespace): ?\ReflectionClass
{
return Snowflake::getDi()->getReflect($this->explodeFileName($path, $namespace));
}
/**
* @param \ReflectionClass $replace
* @param array $_array
* @return array
*/
private function _targets(\ReflectionClass $replace, array $_array): array
{
foreach ($replace->getAttributes() as $attribute) {
if ($attribute->getName() == Attribute::class) {
continue;
}
if ($attribute->getName() == Target::class) {
continue;
}
$_array['target'][] = $attribute->newInstance();
}
return $_array;
}
/**
* @param \ReflectionClass $replace
* @param array $_array
* @return array
*/
private function _methods(\ReflectionClass $replace, array $_array): array
{
$methods = $replace->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
$_method = [];
foreach ($method->getAttributes() as $attribute) {
if (!class_exists($attribute->getName())) {
continue;
}
$_method[] = $attribute->newInstance();
}
$_array['methods'][$method->getName()] = $_method;
}
return $_array;
}
/**
* @param \ReflectionClass $replace
* @param array $_array
* @return array
*/
private function _properties(\ReflectionClass $replace, array $_array): array
{
$methods = $replace->getProperties();
foreach ($methods as $method) {
$_property = [];
if ($method->isStatic()) continue;
foreach ($method->getAttributes() as $attribute) {
if (!class_exists($attribute->getName())) {
continue;
}
$_property[] = $attribute->newInstance();
}
$_array['property'][$method->getName()] = $_property;
}
return $_array;
}
/** /**
* @param string $path * @param string $path
* @param string|array $outPath * @param string|array $outPath
@@ -301,14 +342,17 @@ class Loader extends BaseObject
return; return;
} }
$annotation = Snowflake::getAnnotation(); $annotation = Snowflake::getAnnotation();
foreach ($classes as $className) { foreach ($classes as $className) {
$annotations = $this->_classes[$className] ?? null; $annotations = $this->_classes[$className] ?? null;
if ($annotations === null) { if ($annotations === null) {
continue; continue;
} }
$class = clone $annotations['handler'];
$class = $this->newInstance($annotations['handler']);
/** @var \Annotation\Attribute $value */
foreach ($annotations['target'] ?? [] as $value) { foreach ($annotations['target'] ?? [] as $value) {
$value->execute([$class]); $value->execute($class);
} }
foreach ($annotations['methods'] as $name => $attribute) { foreach ($annotations['methods'] as $name => $attribute) {
foreach ($attribute as $value) { foreach ($attribute as $value) {
@@ -319,7 +363,7 @@ class Loader extends BaseObject
} else if ($value instanceof Set) { } else if ($value instanceof Set) {
$annotation->addSets($class::class, $value->name, $name); $annotation->addSets($class::class, $value->name, $name);
} else { } else {
$value->execute([$class, $name]); $value->execute($class, $name);
} }
} }
} }
@@ -327,4 +371,16 @@ class Loader extends BaseObject
} }
/**
* @param $class
* @return object
* @throws \ReflectionException
* @throws \Snowflake\Exception\NotFindClassException
*/
private function newInstance($class)
{
$reflection = Snowflake::getDi()->getReflect($class);
return $reflection?->newInstance();
}
} }
+15 -16
View File
@@ -34,22 +34,21 @@ use Snowflake\Snowflake;
} }
/** /**
* @param array $handler * @param object $class
* @return mixed * @param string $method
* @throws Exception * @return mixed
*/ * @throws \Exception
public function execute(array $handler): mixed */
{ public function execute(mixed $class, mixed $method = null): mixed
$class = ['class' => $handler[0]::class]; {
if (!empty($this->args)) { $class = ['class' => $class::class];
$class = array_merge($class, $this->args); if (!empty($this->args)) {
} $class = array_merge($class, $this->args);
}
Snowflake::set($this->service, $class);
return parent::execute($handler); // TODO: Change the autogenerated stub
}
Snowflake::set($this->service, $class);
return true; // TODO: Change the autogenerated stub
}
} }
+18 -20
View File
@@ -7,6 +7,7 @@ namespace Annotation\Model;
use Annotation\Annotation; use Annotation\Annotation;
use Attribute; use Attribute;
use Database\ActiveRecord; use Database\ActiveRecord;
use Snowflake\Snowflake;
/** /**
@@ -17,28 +18,25 @@ use Database\ActiveRecord;
{ {
/** /**
* Get constructor. * Get constructor.
* @param string $name * @param string $name
*/ */
public function __construct( public function __construct(public string $name)
public string $name {
) }
{
}
/** /**
* @param array $handler * @param array $handler
* @return ActiveRecord * @return ActiveRecord
*/ */
public function execute(array $handler): ActiveRecord public function execute(mixed $class, mixed $method = null): bool
{ {
/** @var ActiveRecord $activeRecord */ $annotation = Snowflake::getAnnotation();
[$activeRecord, $method] = $handler; $annotation->addGets($class::class, $this->name, $method);
return true;
return $activeRecord->addGets($this->name, $method); }
}
} }
+5 -7
View File
@@ -7,6 +7,7 @@ namespace Annotation\Model;
use Annotation\Attribute; use Annotation\Attribute;
use Database\ActiveRecord; use Database\ActiveRecord;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Snowflake\Snowflake;
/** /**
@@ -30,14 +31,11 @@ use JetBrains\PhpStorm\Pure;
* @param array $handler * @param array $handler
* @return bool * @return bool
*/ */
public function execute(array $handler): bool public function execute(mixed $class, mixed $method = null): bool
{ {
/** @var ActiveRecord $activeRecord */ $annotation = Snowflake::getAnnotation();
[$activeRecord, $method] = $handler; $annotation->addRelate($class::class, $this->name, $method);
return true;
$activeRecord->setRelate($this->name, $method);
return true;
} }
} }
+11 -10
View File
@@ -6,6 +6,7 @@ namespace Annotation\Model;
use Annotation\Attribute; use Annotation\Attribute;
use Database\ActiveRecord; use Database\ActiveRecord;
use Snowflake\Snowflake;
#[\Attribute(\Attribute::TARGET_METHOD)] class Set extends Attribute #[\Attribute(\Attribute::TARGET_METHOD)] class Set extends Attribute
{ {
@@ -20,17 +21,17 @@ use Database\ActiveRecord;
} }
/**
/** * @param mixed $class
* @param array $handler * @param mixed|null $method
* @return ActiveRecord * @return bool
*/ * @throws \Exception
public function execute(array $handler): ActiveRecord */
public function execute(mixed $class, mixed $method = null): bool
{ {
/** @var ActiveRecord $activeRecord */ $annotation = Snowflake::getAnnotation();
[$activeRecord, $method] = $handler; $annotation->addSets($class::class, $this->name, $method);
return true;
return $activeRecord->addSets($this->name, $method);
} }
+4 -4
View File
@@ -31,14 +31,14 @@ use Snowflake\Snowflake;
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): mixed public function execute(mixed $class, mixed $method = null): mixed
{ {
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
if (!($handler[0] instanceof Porters)) { if (!($class instanceof Porters)) {
return true; return true;
} }
$router->addPortListen($this->port, [$handler[0], 'process']); $router->addPortListen($this->port, [$class, 'process']);
return parent::execute($handler); return true;
} }
} }
+1 -1
View File
@@ -38,7 +38,7 @@ use Snowflake\Snowflake;
* @param array $handler * @param array $handler
* @return After * @return After
*/ */
public function execute(array $handler): static public function execute(mixed $class, mixed $method = null): static
{ {
return $this; return $this;
} }
+1 -1
View File
@@ -38,7 +38,7 @@ use Annotation\Attribute;
* @param array $handler * @param array $handler
* @return array * @return array
*/ */
public function execute(array $handler): array public function execute(mixed $class, mixed $method = null): array
{ {
// TODO: Implement execute() method. // TODO: Implement execute() method.
return [$this->request, $this->response]; return [$this->request, $this->response];
+1 -1
View File
@@ -33,7 +33,7 @@ use Snowflake\Snowflake;
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): bool public function execute(mixed $class, mixed $method = null): bool
{ {
return true; return true;
} }
+1 -1
View File
@@ -43,7 +43,7 @@ use Snowflake\Snowflake;
* @param array $handler * @param array $handler
* @return Interceptor * @return Interceptor
*/ */
public function execute(array $handler): static public function execute(mixed $class, mixed $method = null): static
{ {
return $this; return $this;
} }
+1 -1
View File
@@ -42,7 +42,7 @@ use Snowflake\Snowflake;
* @param array $handler * @param array $handler
* @return Limits * @return Limits
*/ */
public function execute(array $handler): static public function execute(mixed $class, mixed $method = null): static
{ {
return $this; return $this;
} }
+1 -1
View File
@@ -43,7 +43,7 @@ use HttpServer\IInterface\Middleware as IMiddleware;
* @param array $handler * @param array $handler
* @return Middleware * @return Middleware
*/ */
public function execute(array $handler): static public function execute(mixed $class, mixed $method = null): static
{ {
return $this; return $this;
} }
+2 -2
View File
@@ -34,12 +34,12 @@ use Snowflake\Snowflake;
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): Router public function execute(mixed $class, mixed $method = null): Router
{ {
// TODO: Implement setHandler() method. // TODO: Implement setHandler() method.
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
$router->addRoute($this->uri, $handler, $this->method); $router->addRoute($this->uri, [$class, $method], $this->method);
return $router; return $router;
} }
+2 -2
View File
@@ -42,12 +42,12 @@ use Snowflake\Snowflake;
* @return Router * @return Router
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): Router public function execute(mixed $class, mixed $method = null): Router
{ {
// TODO: Implement setHandler() method. // TODO: Implement setHandler() method.
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
$router->addRoute($this->uri, $handler, Request::HTTP_CMD) $router->addRoute($this->uri, [$class, $method], Request::HTTP_CMD)
->setDataType($this->protocol); ->setDataType($this->protocol);
return $router; return $router;
+3 -3
View File
@@ -44,14 +44,14 @@ use Snowflake\Snowflake;
* @return Router * @return Router
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): Router public function execute(mixed $class, mixed $method = null): Router
{ {
// TODO: Implement setHandler() method. // TODO: Implement setHandler() method.
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
$method = $this->event . '::' . (is_null($this->uri) ? 'event' : $this->uri); $path = $this->event . '::' . (is_null($this->uri) ? 'event' : $this->uri);
$router->addRoute($method, $handler, 'sw::socket'); $router->addRoute($path, [$class, $method], 'sw::socket');
return $router; return $router;
} }
+3 -3
View File
@@ -32,11 +32,11 @@ use Snowflake\Snowflake;
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): mixed public function execute(mixed $class, mixed $method = ''): mixed
{ {
$rpc = Snowflake::app()->getRpc(); $rpc = Snowflake::app()->getRpc();
$rpc->addConsumer($this->cmd, $handler); $rpc->addConsumer($this->cmd, [$class, $method]);
return parent::execute($handler); // TODO: Change the autogenerated stub return true; // TODO: Change the autogenerated stub
} }
+28 -28
View File
@@ -16,39 +16,39 @@ use Snowflake\Snowflake;
#[\Attribute(\Attribute::TARGET_CLASS)] class RpcClient extends Attribute #[\Attribute(\Attribute::TARGET_CLASS)] class RpcClient extends Attribute
{ {
private array $config; private array $config;
/** /**
* RpcClient constructor. * RpcClient constructor.
* @param string $cmd * @param string $cmd
* @param int $port * @param int $port
* @param int $timeout * @param int $timeout
* @param int $mode * @param int $mode
*/ */
public function __construct( public function __construct(
public string $cmd, public string $cmd,
public int $port, public int $port,
public int $timeout, public int $timeout,
public int $mode public int $mode
) )
{ {
$this->config = ['port' => $port, 'mode' => $mode, 'timeout' => $timeout]; $this->config = ['port' => $port, 'mode' => $mode, 'timeout' => $timeout];
} }
/** /**
* @param array $handler * @param array $handler
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function execute(array $handler): mixed public function execute(mixed $class, mixed $method = ''): mixed
{ {
$rpc = Snowflake::app()->getRpc(); $rpc = Snowflake::app()->getRpc();
$rpc->addProducer($this->cmd, $handler, $this->config); $rpc->addProducer($this->cmd, [$class, $method], $this->config);
return parent::execute($handler); return true;
} }
} }
+6 -6
View File
@@ -431,19 +431,19 @@ abstract class BaseActiveRecord extends Component implements IOrm, ArrayAccess
[$sql, $param] = SqlBuilder::builder(static::find())->insert($param); [$sql, $param] = SqlBuilder::builder(static::find())->insert($param);
$trance = $dbConnection->beginTransaction(); // $trance = $dbConnection->beginTransaction();
try { try {
if (!($lastId = (int)$dbConnection->createCommand($sql, $param)->save(true, $this))) { if (!($lastId = (int)$dbConnection->createCommand($sql, $param)->save(true, $this))) {
throw new Exception('保存失败.'); throw new Exception('保存失败.');
} }
$trance->commit(); // $trance->commit();
$lastId = $this->setPrimary($lastId, $param); $lastId = $this->setPrimary($lastId, $param);
$this->refresh(); $this->refresh();
SEvent::trigger(self::AFTER_SAVE, [$attributes, $param]); SEvent::trigger(self::AFTER_SAVE, [$attributes, $param]);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$trance->rollback(); // $trance->rollback();
$lastId = $this->addError($exception, 'mysql'); $lastId = $this->addError($exception, 'mysql');
} }
return $lastId; return $lastId;
@@ -498,13 +498,13 @@ abstract class BaseActiveRecord extends Component implements IOrm, ArrayAccess
return $generate; return $generate;
} }
$trance = $command->beginTransaction(); // $trance = $command->beginTransaction();
if (!$command->createCommand(...$generate)->save(false, $this)) { if (!$command->createCommand(...$generate)->save(false, $this)) {
$trance->rollback(); // $trance->rollback();
return false; return false;
} }
$trance->commit(); // $trance->commit();
$this->refresh(); $this->refresh();
+257 -215
View File
@@ -22,249 +22,291 @@ use Swoole\Coroutine;
*/ */
class Command extends Component class Command extends Component
{ {
const ROW_COUNT = 'ROW_COUNT'; const ROW_COUNT = 'ROW_COUNT';
const FETCH = 'FETCH'; const FETCH = 'FETCH';
const FETCH_ALL = 'FETCH_ALL'; const FETCH_ALL = 'FETCH_ALL';
const EXECUTE = 'EXECUTE'; const EXECUTE = 'EXECUTE';
const FETCH_COLUMN = 'FETCH_COLUMN'; const FETCH_COLUMN = 'FETCH_COLUMN';
const DB_ERROR_MESSAGE = 'The system is busy, please try again later.'; const DB_ERROR_MESSAGE = 'The system is busy, please try again later.';
/** @var Connection */ /** @var Connection */
public Connection $db; public Connection $db;
/** @var ?string */ /** @var ?string */
public ?string $sql = ''; public ?string $sql = '';
/** @var array */ /** @var array */
public array $params = []; public array $params = [];
/** @var string */ /** @var string */
private string $_modelName; private string $_modelName;
private ?PDOStatement $prepare = null; private ?PDOStatement $prepare = null;
/** /**
* @return array|bool|int|string|PDOStatement|null * @return array|bool|int|string|PDOStatement|null
* @throws Exception * @throws Exception
*/ */
public function incrOrDecr(): array|bool|int|string|PDOStatement|null public function incrOrDecr(): array|bool|int|string|PDOStatement|null
{ {
return $this->execute(static::EXECUTE); return $this->execute(static::EXECUTE);
} }
/** /**
* @param bool $isInsert * @param bool $isInsert
* @param bool $hasAutoIncrement * @param bool $hasAutoIncrement
* @return int|bool|array|string|null * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function save($isInsert = TRUE, $hasAutoIncrement = null): int|bool|array|string|null public function save($isInsert = TRUE, $hasAutoIncrement = null): int|bool|array|string|null
{ {
return $this->execute(static::EXECUTE, $isInsert, $hasAutoIncrement); return $this->execute(static::EXECUTE, $isInsert, $hasAutoIncrement);
} }
/** /**
* @return int|bool|array|string|null * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function all(): int|bool|array|string|null public function all(): int|bool|array|string|null
{ {
return $this->execute(static::FETCH_ALL); return $this->execute(static::FETCH_ALL);
} }
/** /**
* @return array|bool|int|string|null * @return array|bool|int|string|null
* @throws Exception * @throws Exception
*/ */
public function one(): null|array|bool|int|string public function one(): null|array|bool|int|string
{ {
return $this->execute(static::FETCH); return $this->execute(static::FETCH);
} }
/** /**
* @return int|bool|array|string|null * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function fetchColumn(): int|bool|array|string|null public function fetchColumn(): int|bool|array|string|null
{ {
return $this->execute(static::FETCH_COLUMN); return $this->execute(static::FETCH_COLUMN);
} }
/** /**
* @return int|bool|array|string|null * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function rowCount(): int|bool|array|string|null public function rowCount(): int|bool|array|string|null
{ {
return $this->execute(static::ROW_COUNT); return $this->execute(static::ROW_COUNT);
} }
/** /**
* @return int|bool|array|string|null * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function flush(): int|bool|array|string|null public function flush(): int|bool|array|string|null
{ {
return $this->execute(static::EXECUTE); return $this->execute(static::EXECUTE);
} }
/** /**
* @param $type * @param $type
* @param null $isInsert * @param null $isInsert
* @param bool $hasAutoIncrement * @param bool $hasAutoIncrement
* @return int|bool|array|string|null * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
private function execute($type, $isInsert = null, $hasAutoIncrement = null): int|bool|array|string|null private function execute($type, $isInsert = null, $hasAutoIncrement = null): int|bool|array|string|null
{ {
try { try {
if ($type === static::EXECUTE) { if ($type === static::EXECUTE) {
$result = $this->insert_or_change($isInsert, $hasAutoIncrement); $result = $this->insert_or_change($isInsert, $hasAutoIncrement);
} else { } else {
$result = $this->search($type); $result = $this->search($type);
} }
return $result; if ($this->prepare) {
} catch (\Throwable $exception) { $this->prepare->closeCursor();
return $this->addError($this->sql . '. error: ' . $exception->getMessage(), 'mysql'); }
} return $result;
} } catch (\Throwable $exception) {
return $this->addError($this->sql . '. error: ' . $exception->getMessage(), 'mysql');
}
}
/** /**
* @param $type * @param $type
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function search($type): mixed private function search($type): mixed
{ {
$connect = $this->db->getConnect($this->sql); if (($prepare = $this->prepare()) == false) {
if (!($query = $connect?->query($this->sql))) { return false;
return $this->addError($connect->errorInfo()[2] ?? '数据库异常, 请稍后再试.'); }
} if ($type === static::FETCH_COLUMN) {
defer(fn() => $query->closeCursor()); $data = $prepare->fetchAll(PDO::FETCH_ASSOC);
if ($type === static::FETCH_COLUMN) { } else if ($type === static::ROW_COUNT) {
return $query->fetchAll(PDO::FETCH_ASSOC); $data = $prepare->rowCount();
} else if ($type === static::ROW_COUNT) { } else if ($type === static::FETCH_ALL) {
return $query->rowCount(); $data = $prepare->fetchAll(PDO::FETCH_ASSOC);
} else if ($type === static::FETCH_ALL) { } else {
return $query->fetchAll(PDO::FETCH_ASSOC); $data = $prepare->fetch(PDO::FETCH_ASSOC);
} else { }
return $query->fetch(PDO::FETCH_ASSOC); $prepare->closeCursor();
} return $data;
} }
/** /**
* @param $isInsert * @param $isInsert
* @param $hasAutoIncrement * @param $hasAutoIncrement
* @return bool|string|int * @return bool|string|int
* @throws Exception * @throws Exception
*/ */
private function insert_or_change($isInsert, $hasAutoIncrement): bool|string|int private function insert_or_change($isInsert, $hasAutoIncrement): bool|string|int
{ {
if (($result = $this->initPDOStatement()) === false) { if (($result = $this->getPdoStatement()) === false) {
return $result; return $result;
} }
if ($isInsert === false) { if ($isInsert === false) {
return true; return true;
} }
if ($result == 0 && $hasAutoIncrement->isAutoIncrement()) { if ($result == 0 && $hasAutoIncrement->isAutoIncrement()) {
return $this->addError(static::DB_ERROR_MESSAGE, 'mysql'); return $this->addError(static::DB_ERROR_MESSAGE, 'mysql');
} }
return $result == 0 ? true : $result; return $result == 0 ? true : $result;
} }
/** /**
* 重新构建 * 重新构建
* @throws * @throws
*/ */
private function initPDOStatement(): bool|int private function getPdoStatement(): bool|int
{ {
if (empty($this->sql)) { if (empty($this->sql)) {
return $this->addError('no sql.', 'mysql'); return $this->addError('no sql.', 'mysql');
} }
if (!(($connect = $this->db->getConnect($this->sql)) instanceof PDO)) { if (!(($connect = $this->db->getConnect($this->sql)) instanceof PDO)) {
return $this->addError('get client error.', 'mysql'); return $this->addError('get client error.', 'mysql');
} }
if (!(($prepare = $connect->prepare($this->sql)) instanceof PDOStatement)) { if (!(($prepare = $connect->prepare($this->sql)) instanceof PDOStatement)) {
$error = $prepare->errorInfo()[2] ?? static::DB_ERROR_MESSAGE; return $this->addError($this->errorMessage($prepare), 'mysql');
}
$result = $this->checkResponse($prepare, $connect);
$prepare->closeCursor();
return $result;
}
return $this->addError($this->sql . ':' . $error, 'mysql');
}
$result = $prepare->execute($this->params);
defer(fn() => $prepare->closeCursor());
if ($result === false) {
return $this->addError($connect->errorInfo()[2], 'mysql');
}
return (int)$connect->lastInsertId();
}
/** /**
* @param $modelName * @param $prepare
* @return $this * @return string
*/ */
public function setModelName($modelName): static private function errorMessage($prepare)
{ {
$this->_modelName = $modelName; return $this->sql . ':' . ($prepare->errorInfo()[2] ?? static::DB_ERROR_MESSAGE);
return $this; }
}
/**
* @return string
*/
public function getModelName(): string
{
return $this->_modelName;
}
/** /**
* @return int|bool|array|string|null * @return bool|\PDOStatement
* @throws Exception * @throws \Exception
*/ */
public function delete(): int|bool|array|string|null private function prepare(): bool|PDOStatement
{ {
return $this->execute(static::EXECUTE); if (!(($connect = $this->db->getConnect($this->sql)) instanceof PDO)) {
} return $this->addError('get client error.', 'mysql');
}
if (!(($prepare = $connect->query($this->sql)) instanceof PDOStatement)) {
$error = $prepare->errorInfo()[2] ?? static::DB_ERROR_MESSAGE;
return $this->addError($this->sql . ':' . $error, 'mysql');
}
return $prepare;
}
/**
* @param null $scope
* @param bool $insert
* @return int|bool|array|string|null
* @throws Exception
*/
public function exec($scope = null, $insert = false): int|bool|array|string|null
{
return $this->execute(static::EXECUTE, $insert, $scope);
}
/** /**
* @param array|null $data * @param $prepare
* @return $this * @param $connect
*/ * @return bool|int
public function bindValues(array $data = NULL): static * @throws \Exception
{ */
if (!is_array($this->params)) { private function checkResponse($prepare, $connect)
$this->params = []; {
} $result = $prepare->execute($this->params);
if (!empty($data)) { if ($result === false) {
$this->params = array_merge($this->params, $data); return $this->addError($connect->errorInfo()[2], 'mysql');
} }
return $this; return (int)$connect->lastInsertId();
} }
/**
* @param $sql /**
* @return $this * @param $modelName
* @throws Exception * @return $this
*/ */
public function setSql($sql): static public function setModelName($modelName): static
{ {
$this->sql = $sql; $this->_modelName = $modelName;
return $this; return $this;
} }
/**
* @return string
*/
public function getModelName(): string
{
return $this->_modelName;
}
/**
* @return int|bool|array|string|null
* @throws Exception
*/
public function delete(): int|bool|array|string|null
{
return $this->execute(static::EXECUTE);
}
/**
* @param null $scope
* @param bool $insert
* @return int|bool|array|string|null
* @throws Exception
*/
public function exec($scope = null, $insert = false): int|bool|array|string|null
{
return $this->execute(static::EXECUTE, $insert, $scope);
}
/**
* @param array $data
* @return $this
*/
public function bindValues(array $data = []): static
{
if (!is_array($this->params)) {
$this->params = [];
}
if (!empty($data)) {
$this->params = array_merge($this->params, $data);
}
return $this;
}
/**
* @param $sql
* @return $this
* @throws Exception
*/
public function setSql($sql): static
{
$this->sql = $sql;
return $this;
}
} }
+248 -248
View File
@@ -27,293 +27,293 @@ use Snowflake\Snowflake;
*/ */
class Connection extends Component class Connection extends Component
{ {
const TRANSACTION_COMMIT = 'transaction::commit'; const TRANSACTION_COMMIT = 'transaction::commit';
const TRANSACTION_ROLLBACK = 'transaction::rollback'; const TRANSACTION_ROLLBACK = 'transaction::rollback';
public string $id = 'db'; public string $id = 'db';
public string $cds = ''; public string $cds = '';
public string $password = ''; public string $password = '';
public string $username = ''; public string $username = '';
public string $charset = 'utf-8'; public string $charset = 'utf-8';
public string $tablePrefix = ''; public string $tablePrefix = '';
public int $timeout = 1900; public int $timeout = 1900;
public int $maxNumber = 200; public int $maxNumber = 200;
/** /**
* @var bool * @var bool
* enable database cache * enable database cache
*/ */
public bool $enableCache = false; public bool $enableCache = false;
public string $cacheDriver = 'redis'; public string $cacheDriver = 'redis';
/** /**
* @var array * @var array
* *
* @example [ * @example [
* 'cds' => 'mysql:dbname=dbname;host=127.0.0.1', * 'cds' => 'mysql:dbname=dbname;host=127.0.0.1',
* 'username' => 'root', * 'username' => 'root',
* 'password' => 'root' * 'password' => 'root'
* ] * ]
*/ */
public array $slaveConfig = []; public array $slaveConfig = [];
private ?Schema $_schema = null; private ?Schema $_schema = null;
/** /**
* @throws Exception * @throws Exception
*/ */
public function init() public function init()
{ {
Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'disconnect']); Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'disconnect']);
Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'clear_connection']); Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'clear_connection']);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function enablingTransactions() public function enablingTransactions()
{ {
if (!Db::transactionsActive()) { if (!Db::transactionsActive()) {
return; return;
} }
$this->beginTransaction(); $this->beginTransaction();
Event::on(Connection::TRANSACTION_COMMIT, [$this, 'commit'], false, true); Event::on(Connection::TRANSACTION_COMMIT, [$this, 'commit'], false, true);
Event::on(Connection::TRANSACTION_ROLLBACK, [$this, 'rollback'], false, true); Event::on(Connection::TRANSACTION_ROLLBACK, [$this, 'rollback'], false, true);
} }
/** /**
* @param null $sql * @param null $sql
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function getConnect($sql = NULL): PDO public function getConnect($sql = NULL): PDO
{ {
return $this->getPdo($sql); return $this->getPdo($sql);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function fill() public function fill()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->initConnections('mysql', $this->cds, true, $this->maxNumber); $connections->initConnections('mysql', $this->cds, true, $this->maxNumber);
if (!empty($this->slaveConfig)) { if (!empty($this->slaveConfig)) {
$connections->initConnections('mysql', $this->slaveConfig['cds'], false, $this->maxNumber); $connections->initConnections('mysql', $this->slaveConfig['cds'], false, $this->maxNumber);
} }
} }
/** /**
* @param $sql * @param $sql
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
private function getPdo($sql): PDO private function getPdo($sql): PDO
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->setTimeout($this->timeout); $connections->setTimeout($this->timeout);
if ($this->isWrite($sql)) { if ($this->isWrite($sql)) {
$connect = $connections->get(['cds' => $this->cds, 'username' => $this->username, 'password' => $this->password], true); $connect = $connections->get(['cds' => $this->cds, 'username' => $this->username, 'password' => $this->password], true);
} else { } else {
$connect = $connections->get(['cds' => $this->slaveConfig['cds'], 'username' => $this->username, 'password' => $this->password], false); $connect = $connections->get(['cds' => $this->slaveConfig['cds'], 'username' => $this->username, 'password' => $this->password], false);
} }
return $connect; return $connect;
} }
/** /**
* @return mixed * @return mixed
* @throws ReflectionException * @throws ReflectionException
* @throws NotFindClassException * @throws NotFindClassException
*/ */
public function getSchema(): Schema public function getSchema(): Schema
{ {
if ($this->_schema === null) { if ($this->_schema === null) {
$this->_schema = Snowflake::createObject([ $this->_schema = Snowflake::createObject([
'class' => Schema::class, 'class' => Schema::class,
'db' => $this 'db' => $this
]); ]);
} }
return $this->_schema; return $this->_schema;
} }
/** /**
* @param $sql * @param $sql
* @return bool * @return bool
*/ */
#[Pure] public function isWrite($sql): bool #[Pure] public function isWrite($sql): bool
{ {
if (empty($sql)) return false; if (empty($sql)) return false;
if (str_starts_with(strtolower($sql), 'select')) { if (str_starts_with(strtolower($sql), 'select')) {
return false; return false;
} }
return true; return true;
} }
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function getCacheDriver(): mixed public function getCacheDriver(): mixed
{ {
if (!$this->enableCache) { if (!$this->enableCache) {
return null; return null;
} }
return Snowflake::app()->get($this->cacheDriver); return Snowflake::app()->get($this->cacheDriver);
} }
/** /**
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function masterInstance(): PDO public function masterInstance(): PDO
{ {
return $this->connections()->get([ return $this->connections()->get([
'cds' => $this->cds, 'username' => $this->username, 'password' => $this->password 'cds' => $this->cds, 'username' => $this->username, 'password' => $this->password
], true); ], true);
} }
/** /**
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function slaveInstance(): PDO public function slaveInstance(): PDO
{ {
if ($this->inTransaction() || empty($this->slaveConfig)) { if (empty($this->slaveConfig)) {
return $this->masterInstance(); $this->slaveConfig = ['cds' => $this->cds, 'username' => $this->username, 'password' => $this->password];
} }
return $this->connections()->get($this->slaveConfig, false); return $this->connections()->get($this->slaveConfig, false);
} }
/** /**
* @return \Snowflake\Pool\Connection * @return \Snowflake\Pool\Connection
* @throws Exception * @throws Exception
*/ */
private function connections(): \Snowflake\Pool\Connection private function connections(): \Snowflake\Pool\Connection
{ {
return Snowflake::app()->getMysqlFromPool(); return Snowflake::app()->getMysqlFromPool();
} }
/** /**
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function beginTransaction(): static public function beginTransaction(): static
{ {
$this->connections()->beginTransaction($this->cds); $this->connections()->beginTransaction($this->cds);
return $this; return $this;
} }
/** /**
* @return $this|bool * @return $this|bool
* @throws Exception * @throws Exception
*/ */
public function inTransaction(): bool|static public function inTransaction(): bool|static
{ {
return $this->connections()->inTransaction($this->cds); return $this->connections()->inTransaction($this->cds);
} }
/** /**
* @throws Exception * @throws Exception
* 事务回滚 * 事务回滚
*/ */
public function rollback() public function rollback()
{ {
$this->connections()->rollback($this->cds); $this->connections()->rollback($this->cds);
} }
/** /**
* @throws Exception * @throws Exception
* 事务提交 * 事务提交
*/ */
public function commit() public function commit()
{ {
$this->connections()->commit($this->cds); $this->connections()->commit($this->cds);
} }
/** /**
* @param $sql * @param $sql
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function refresh($sql): PDO public function refresh($sql): PDO
{ {
if ($this->isWrite($sql)) { if ($this->isWrite($sql)) {
$instance = $this->masterInstance(); $instance = $this->masterInstance();
} else { } else {
$instance = $this->slaveInstance(); $instance = $this->slaveInstance();
} }
return $instance; return $instance;
} }
/** /**
* @param $sql * @param $sql
* @param array $attributes * @param array $attributes
* @return Command * @return Command
* @throws * @throws
*/ */
public function createCommand($sql = null, $attributes = []): Command public function createCommand($sql = null, $attributes = []): Command
{ {
$command = new Command(['db' => $this, 'sql' => $sql]); $command = new Command(['db' => $this, 'sql' => $sql]);
return $command->bindValues($attributes); return $command->bindValues($attributes);
} }
/** /**
* *
* 回收链接 * 回收链接
* @throws * @throws
*/ */
public function release() public function release()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->release($this->cds, true); $connections->release($this->cds, true);
$connections->release($this->slaveConfig['cds'], false); $connections->release($this->slaveConfig['cds'], false);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function recovery() public function recovery()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->release($this->cds, true); $connections->release($this->cds, true);
$connections->release($this->slaveConfig['cds'], false); $connections->release($this->slaveConfig['cds'], false);
} }
/** /**
* *
* 回收链接 * 回收链接
* @throws * @throws
*/ */
public function clear_connection() public function clear_connection()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->release($this->cds, true); $connections->release($this->cds, true);
$connections->release($this->slaveConfig['cds'], false); $connections->release($this->slaveConfig['cds'], false);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function disconnect() public function disconnect()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->disconnect($this->cds, true); $connections->disconnect($this->cds, true);
$connections->disconnect($this->slaveConfig['cds'], false); $connections->disconnect($this->slaveConfig['cds'], false);
} }
} }
+150 -150
View File
@@ -17,186 +17,186 @@ use Swoole\Coroutine;
class Pagination extends Component class Pagination extends Component
{ {
/** @var ActiveQuery */ /** @var ActiveQuery */
private ActiveQuery $activeQuery; private ActiveQuery $activeQuery;
/** @var int 从第几个开始查 */ /** @var int 从第几个开始查 */
private int $_offset = 0; private int $_offset = 0;
/** @var int 每页数量 */ /** @var int 每页数量 */
private int $_limit = 100; private int $_limit = 100;
/** @var int 最大查询数量 */ /** @var int 最大查询数量 */
private int $_max = 0; private int $_max = 0;
/** @var int 当前已查询数量 */ /** @var int 当前已查询数量 */
private int $_length = 0; private int $_length = 0;
/** @var Closure */ /** @var Closure */
private Closure $_callback; private Closure $_callback;
/** /**
* PaginationIteration constructor. * PaginationIteration constructor.
* @param ActiveQuery $activeQuery * @param ActiveQuery $activeQuery
* @param array $config * @param array $config
* @throws Exception * @throws Exception
*/ */
public function __construct(ActiveQuery $activeQuery, array $config = []) public function __construct(ActiveQuery $activeQuery, array $config = [])
{ {
parent::__construct($config); parent::__construct($config);
$this->activeQuery = $activeQuery; $this->activeQuery = $activeQuery;
} }
public function clean() public function clean()
{ {
unset($this->activeQuery, $this->_callback, $this->_group); unset($this->activeQuery, $this->_callback, $this->_group);
$this->_offset = 0; $this->_offset = 0;
$this->_limit = 100; $this->_limit = 100;
$this->_max = 0; $this->_max = 0;
$this->_length = 0;; $this->_length = 0;;
} }
/** /**
* recover class by clone * recover class by clone
*/ */
public function __clone() public function __clone()
{ {
$this->clean(); $this->clean();
} }
/** /**
* @param array|Closure $callback * @param array|Closure $callback
* @throws Exception * @throws Exception
*/ */
public function setCallback(array|Closure $callback) public function setCallback(array|Closure $callback)
{ {
if (!is_callable($callback, true)) { if (!is_callable($callback, true)) {
throw new Exception('非法回调函数~'); throw new Exception('非法回调函数~');
} }
$this->_callback = $callback; $this->_callback = $callback;
} }
/** /**
* @param int $number * @param int $number
* @return Pagination * @return Pagination
*/ */
public function setOffset(int $number): static public function setOffset(int $number): static
{ {
if ($number < 0) { if ($number < 0) {
$number = 0; $number = 0;
} }
$this->_offset = $number; $this->_offset = $number;
return $this; return $this;
} }
/** /**
* @param int $number * @param int $number
* @return Pagination * @return Pagination
*/ */
public function setLimit(int $number): static public function setLimit(int $number): static
{ {
if ($number < 1) { if ($number < 1) {
$number = 100; $number = 100;
} else if ($number > 5000) { } else if ($number > 5000) {
$number = 5000; $number = 5000;
} }
$this->_limit = $number; $this->_limit = $number;
return $this; return $this;
} }
/** /**
* @param int $number * @param int $number
* @return Pagination * @return Pagination
*/ */
public function setMax(int $number): static public function setMax(int $number): static
{ {
if ($number < 0) { if ($number < 0) {
return $this; return $this;
} }
$this->_max = $number; $this->_max = $number;
return $this; return $this;
} }
/** /**
* @param array $param * @param array $param
* @return void * @return void
* @throws Exception * @throws Exception
*/ */
public function plunk($param = []) public function plunk($param = [])
{ {
$this->loop($param); $this->loop($param);
} }
/** /**
* 轮训 * 轮训
* @param $param * @param $param
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function loop($param): array public function loop($param): array
{ {
if ($this->_max > 0 && $this->_length >= $this->_max) { if ($this->_max > 0 && $this->_length >= $this->_max) {
return $this->output(); return $this->output();
} }
[$length, $data] = $this->get(); [$length, $data] = $this->get();
$this->executed($data, $param); $this->executed($data, $param);
unset($data); unset($data);
if ($length < $this->_limit) { if ($length < $this->_limit) {
return $this->output(); return $this->output();
} }
return $this->loop($param); return $this->loop($param);
} }
/** /**
* @return array * @return array
*/ */
public function output(): array public function output(): array
{ {
return []; return [];
} }
/** /**
* @param $data * @param $data
* @param $param * @param $param
* @throws Exception * @throws Exception
*/ */
private function executed($data, $param): void private function executed($data, $param): void
{ {
try { try {
call_user_func($this->_callback, $data, $param); call_user_func($this->_callback, $data, $param);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$this->addError($exception, 'throwable'); $this->addError($exception, 'throwable');
} finally { } finally {
fire(Event::SYSTEM_RESOURCE_RELEASES); logger()->insert();
} }
} }
/** /**
* @return array|Collection * @return array|Collection
*/ */
private function get(): Collection|array private function get(): Collection|array
{ {
if ($this->_length + $this->_limit > $this->_max) { if ($this->_length + $this->_limit > $this->_max) {
$this->_limit = $this->_length + $this->_limit - $this->_max; $this->_limit = $this->_length + $this->_limit - $this->_max;
} }
$data = $this->activeQuery->limit($this->_offset, $this->_limit)->get(); $data = $this->activeQuery->limit($this->_offset, $this->_limit)->get();
$this->_offset += $this->_limit; $this->_offset += $this->_limit;
$this->_length += $data->size(); $this->_length += $data->size();
return [$data->size(), $data]; return [$data->size(), $data];
} }
} }
+502 -502
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -26,7 +26,7 @@ class Async extends Component
*/ */
public function addAsync(string $name, Task $handler) public function addAsync(string $name, Task $handler)
{ {
$this->_absences[$name] = $handler; $this->_absences[$name] = $handler::class;
} }
@@ -47,7 +47,7 @@ class Async extends Component
} }
/** @var Task $class */ /** @var Task $class */
$class = $this->_absences[$name]; $class = new $this->_absences[$name]();
$class->setParams($params); $class->setParams($params);
$randWorkerId = random_int(0, $server->setting['task_worker_num'] - 1); $randWorkerId = random_int(0, $server->setting['task_worker_num'] - 1);
+1 -1
View File
@@ -185,7 +185,7 @@ class Container extends BaseObject
} }
foreach ($this->_property[$reflect->getName()] as $property => $inject) { foreach ($this->_property[$reflect->getName()] as $property => $inject) {
/** @var Inject $inject */ /** @var Inject $inject */
$inject->execute([$object, $property]); $inject->execute($object, $property);
} }
return $object; return $object;
} }