This commit is contained in:
2021-07-12 18:51:41 +08:00
parent 16b300b139
commit 49f358fa93
6 changed files with 610 additions and 635 deletions
+362 -366
View File
@@ -15,7 +15,6 @@ use Database\Traits\HasBase;
use Exception; use Exception;
use ReflectionException; use ReflectionException;
use Snowflake\Channel; use Snowflake\Channel;
use Snowflake\Event;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -33,410 +32,407 @@ defined('FIND_OR_CREATE_MESSAGE') or define('FIND_OR_CREATE_MESSAGE', 'Create a
class ActiveRecord extends BaseActiveRecord class ActiveRecord extends BaseActiveRecord
{ {
const DECR = 'decr';
const INCR = 'incr'; /**
* @return array
*/
public function rules(): array
{
return [];
}
/**
* @param string $column
* @param int $value
* @return ActiveRecord|false
* @throws Exception
*/
public function increment(string $column, int $value): bool|ActiveRecord
{
if (!$this->mathematics([$column => $value], '+', null)) {
return false;
}
$this->{$column} += $value;
return $this->refresh();
}
/** /**
* @return array * @param string $column
*/ * @param int $value
public function rules(): array * @return ActiveRecord|false
{ * @throws Exception
return []; */
} public function decrement(string $column, int $value): bool|ActiveRecord
{
/** if (!$this->mathematics([$column => $value], '-', null)) {
* @param string $column return false;
* @param int $value }
* @return ActiveRecord|false $this->{$column} -= $value;
* @throws Exception return $this->refresh();
*/ }
public function increment(string $column, int $value): bool|ActiveRecord
{
if (!$this->mathematics([$column => $value], '+')) {
return false;
}
$this->{$column} += $value;
return $this->refresh();
}
/** /**
* @param string $column * @param array $columns
* @param int $value * @return ActiveRecord|false
* @return ActiveRecord|false * @throws Exception
* @throws Exception */
*/ public function increments(array $columns): bool|static
public function decrement(string $column, int $value): bool|ActiveRecord {
{ if (!$this->mathematics($columns, '+', null)) {
if (!$this->mathematics([$column => $value], '-')) { return false;
return false; }
} foreach ($columns as $key => $attribute) {
$this->{$column} -= $value; $this->$key += $attribute;
return $this->refresh(); }
} return $this;
}
/** /**
* @param array $columns * @param array $columns
* @return ActiveRecord|false * @return ActiveRecord|false
* @throws Exception * @throws Exception
*/ */
public function increments(array $columns): bool|static public function decrements(array $columns): bool|static
{ {
if (!$this->mathematics($columns, '+')) { if (!$this->mathematics($columns, '-', null)) {
return false; return false;
} }
foreach ($columns as $key => $attribute) { foreach ($columns as $key => $attribute) {
$this->$key += $attribute; $this->$key -= $attribute;
} }
return $this; return $this;
} }
/**
* @param array $condition
* @param array $attributes
* @return bool|ActiveRecord
* @throws ReflectionException
* @throws NotFindClassException
* @throws Exception
*/
public static function findOrCreate(array $condition, array $attributes = []): bool|static
{
$logger = Snowflake::app()->getLogger();
/** @var static $select */
$select = static::find()->where($condition)->first();
if (!empty($select)) {
return $select;
}
if (empty($attributes)) {
return $logger->addError(FIND_OR_CREATE_MESSAGE, 'mysql');
}
$select = self::getModelClass();
$select->attributes = $attributes;
if (!$select->save()) {
return $logger->addError($select->getLastError(), 'mysql');
}
return $select;
}
/** /**
* @param array $columns * @param array $condition
* @return ActiveRecord|false * @param array $attributes
* @throws Exception * @return bool|static
*/ * @throws Exception
public function decrements(array $columns): bool|static */
{ public static function createOrUpdate(array $condition, array $attributes = []): bool|static
if (!$this->mathematics($columns, '-')) { {
return false; $logger = Snowflake::app()->getLogger();
} if (empty($attributes)) {
foreach ($columns as $key => $attribute) { return $logger->addError(FIND_OR_CREATE_MESSAGE, 'mysql');
$this->$key -= $attribute; }
} /** @var static $select */
return $this; $select = static::find()->where($condition)->first();
} if (empty($select)) {
$select = self::getModelClass();
/** }
* @param array $condition $select->attributes = $attributes;
* @param array $attributes if (!$select->save()) {
* @return bool|ActiveRecord return $logger->addError($select->getLastError(), 'mysql');
* @throws ReflectionException }
* @throws NotFindClassException return $select;
* @throws Exception }
*/
public static function findOrCreate(array $condition, array $attributes = []): bool|static
{
$logger = Snowflake::app()->getLogger();
/** @var static $select */
$select = static::find()->where($condition)->first();
if (!empty($select)) {
return $select;
}
if (empty($attributes)) {
return $logger->addError(FIND_OR_CREATE_MESSAGE, 'mysql');
}
$select = self::getModelClass();
$select->attributes = $attributes;
if (!$select->save()) {
return $logger->addError($select->getLastError(), 'mysql');
}
return $select;
}
/** /**
* @param array $condition * @return static
* @param array $attributes * @throws Exception
* @return bool|static */
* @throws Exception private static function getModelClass(): static
*/ {
public static function createOrUpdate(array $condition, array $attributes = []): bool|static /** @var Channel $channel */
{ $channel = Snowflake::app()->get('channel');
$logger = Snowflake::app()->getLogger(); return $channel->pop(static::class, function () {
if (empty($attributes)) { return new static();
return $logger->addError(FIND_OR_CREATE_MESSAGE, 'mysql'); });
} }
/** @var static $select */
$select = static::find()->where($condition)->first();
if (empty($select)) {
$select = self::getModelClass();
}
$select->attributes = $attributes;
if (!$select->save()) {
return $logger->addError($select->getLastError(), 'mysql');
}
return $select;
}
/** /**
* @return static * @param $action
* @throws Exception * @param $columns
*/ * @param null|array $condition
private static function getModelClass(): static * @return array|bool|int|string|null
{ * @throws Exception
/** @var Channel $channel */ */
$channel = Snowflake::app()->get('channel'); private function mathematics($columns, $action, ?array $condition): int|bool|array|string|null
return $channel->pop(static::class, function () { {
return new static(); if (empty($condition)) {
}); $condition = [$this->getPrimary() => $this->getPrimaryValue()];
} }
$activeQuery = static::find()->where($condition);
$create = SqlBuilder::builder($activeQuery)->mathematics($columns, $action);
if (is_bool($create)) {
return false;
}
return static::getDb()->createCommand($create[0], static::getDbName(), $create[1])->exec();
}
/** /**
* @param $action * @param array $fields
* @param $columns * @return ActiveRecord|bool
* @param array $condition * @throws Exception
* @return array|bool|int|string|null */
* @throws Exception public function update(array $fields): static|bool
*/ {
private function mathematics($columns, $action, $condition = []): int|bool|array|string|null return $this->save($fields);
{ }
if (empty($condition)) {
$condition = [$this->getPrimary() => $this->getPrimaryValue()];
}
$activeQuery = static::find()->where($condition);
$create = SqlBuilder::builder($activeQuery)->mathematics($columns, $action);
if (is_bool($create)) {
return false;
}
return static::getDb()->createCommand($create[0], static::getDbName(), $create[1])->exec();
}
/** /**
* @param array $fields * @param array $data
* @return ActiveRecord|bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function update(array $fields): static|bool public static function inserts(array $data): bool
{ {
return $this->save($fields); /** @var static $class */
} $class = Snowflake::createObject(['class' => static::class]);
if (empty($data)) {
return $class->addError('Insert data empty.', 'mysql');
}
return $class::find()->batchInsert($data);
}
/**
* @return bool
* @throws Exception
*/
public function delete(): bool
{
$conditions = $this->_oldAttributes;
if (empty($conditions)) {
return $this->addError("Delete condition do not empty.", 'mysql');
}
$primary = $this->getPrimary();
if (!empty($primary)) {
$conditions = [$primary => $this->getAttribute($primary)];
}
return static::deleteByCondition($conditions);
}
/** /**
* @param array $data * @param $condition
* @return bool * @param array $attributes
* @throws Exception *
*/ * @return bool
public static function inserts(array $data): bool * @throws Exception
{ */
/** @var static $class */ public static function updateAll(mixed $condition, $attributes = []): bool
$class = Snowflake::createObject(['class' => static::class]); {
if (empty($data)) { $condition = static::find()->where($condition);
return $class->addError('Insert data empty.', 'mysql'); return $condition->batchUpdate($attributes);
} }
return $class::find()->batchInsert($data);
}
/** /**
* @return bool * @param $condition
* @throws Exception * @param array $attributes
*/ *
public function delete(): bool * @return array|Collection
{ * @throws Exception
$conditions = $this->_oldAttributes; */
if (empty($conditions)) { public static function findAll($condition, $attributes = []): array|Collection
return $this->addError("Delete condition do not empty.", 'mysql'); {
} $query = static::find()->where($condition);
$primary = $this->getPrimary(); if (!empty($attributes)) {
$query->bindParams($attributes);
}
return $query->all();
}
if (!empty($primary)) { /**
$conditions = [$primary => $this->getAttribute($primary)]; * @param $method
} * @return mixed
return static::deleteByCondition($conditions); * @throws Exception
} */
private function resolveObject($method): mixed
{
$resolve = $this->{$this->getRelate($method)}();
if ($resolve instanceof HasBase) {
$resolve = $resolve->get();
}
if ($resolve instanceof Collection) {
return $resolve->toArray();
} else if ($resolve instanceof ActiveRecord) {
return $resolve->toArray();
} else if (is_object($resolve)) {
return get_object_vars($resolve);
} else {
return $resolve;
}
}
/** /**
* @param $condition * @return array
* @param array $attributes * @throws Exception
* */
* @return bool public function toArray(): array
* @throws Exception {
*/ $data = $this->_attributes;
public static function updateAll(mixed $condition, $attributes = []): bool
{
$condition = static::find()->where($condition);
return $condition->batchUpdate($attributes);
}
/** $lists = Snowflake::getAnnotation()->getGets(static::class);
* @param $condition foreach ($lists as $key => $item) {
* @param array $attributes $data[$key] = $this->{$item}($data[$key] ?? null);
* }
* @return array|Collection $data = array_merge($data, $this->runRelate());
* @throws Exception
*/
public static function findAll($condition, $attributes = []): array|Collection
{
$query = static::find()->where($condition);
if (!empty($attributes)) {
$query->bindParams($attributes);
}
return $query->all();
}
/** $class = Snowflake::app()->getChannel();
* @param $method $class->push($this, static::class);
* @return mixed
* @throws Exception return $data;
*/ }
private function resolveObject($method): mixed
{ /**
$resolve = $this->{$this->getRelate($method)}(); * @return array
if ($resolve instanceof HasBase) { * @throws Exception
$resolve = $resolve->get(); */
} private function runRelate(): array
if ($resolve instanceof Collection) { {
return $resolve->toArray(); $relates = [];
} else if ($resolve instanceof ActiveRecord) { if (empty($with = $this->getWith())) {
return $resolve->toArray(); return $relates;
} else if (is_object($resolve)) { }
return get_object_vars($resolve); foreach ($with as $val) {
} else { $relates[$val] = $this->resolveObject($val);
return $resolve; }
} return $relates;
} }
/** /**
* @return array * @param string $modelName
* @throws Exception * @param $foreignKey
*/ * @param $localKey
public function toArray(): array * @return HasOne|ActiveQuery
{ * @throws Exception
$data = $this->_attributes; */
public function hasOne(string $modelName, $foreignKey, $localKey): HasOne|ActiveQuery
{
if (($value = $this->getAttribute($localKey)) === null) {
throw new Exception("Need join table primary key.");
}
$lists = Snowflake::getAnnotation()->getGets(static::class); $relation = $this->getRelation();
foreach ($lists as $key => $item) {
$data[$key] = $this->{$item}($data[$key] ?? null);
}
$data = array_merge($data, $this->runRelate());
$class = Snowflake::app()->getChannel(); return new HasOne($modelName, $foreignKey, $value, $relation);
$class->push($this, static::class); }
return $data;
}
/**
* @return array
* @throws Exception
*/
private function runRelate(): array
{
$relates = [];
if (empty($with = $this->getWith())) {
return $relates;
}
foreach ($with as $val) {
$relates[$val] = $this->resolveObject($val);
}
return $relates;
}
/** /**
* @param string $modelName * @param $modelName
* @param $foreignKey * @param $foreignKey
* @param $localKey * @param $localKey
* @return HasOne|ActiveQuery * @return ActiveQuery
* @throws Exception * @throws Exception
*/ */
public function hasOne(string $modelName, $foreignKey, $localKey): HasOne|ActiveQuery public function hasCount($modelName, $foreignKey, $localKey): mixed
{ {
if (($value = $this->getAttribute($localKey)) === null) { if (($value = $this->getAttribute($localKey)) === null) {
throw new Exception("Need join table primary key."); throw new Exception("Need join table primary key.");
} }
$relation = $this->getRelation(); $relation = $this->getRelation();
return new HasOne($modelName, $foreignKey, $value, $relation); return new HasCount($modelName, $foreignKey, $value, $relation);
} }
/** /**
* @param $modelName * @param $modelName
* @param $foreignKey * @param $foreignKey
* @param $localKey * @param $localKey
* @return ActiveQuery * @return ActiveQuery
* @throws Exception * @throws Exception
*/ */
public function hasCount($modelName, $foreignKey, $localKey): mixed public function hasMany($modelName, $foreignKey, $localKey): mixed
{ {
if (($value = $this->getAttribute($localKey)) === null) { if (($value = $this->getAttribute($localKey)) === null) {
throw new Exception("Need join table primary key."); throw new Exception("Need join table primary key.");
} }
$relation = $this->getRelation(); $relation = $this->getRelation();
return new HasCount($modelName, $foreignKey, $value, $relation); return new HasMany($modelName, $foreignKey, $value, $relation);
} }
/**
* @param $modelName
* @param $foreignKey
* @param $localKey
* @return ActiveQuery
* @throws Exception
*/
public function hasIn($modelName, $foreignKey, $localKey): mixed
{
if (($value = $this->getAttribute($localKey)) === null) {
throw new Exception("Need join table primary key.");
}
/** $relation = $this->getRelation();
* @param $modelName
* @param $foreignKey
* @param $localKey
* @return ActiveQuery
* @throws Exception
*/
public function hasMany($modelName, $foreignKey, $localKey): mixed
{
if (($value = $this->getAttribute($localKey)) === null) {
throw new Exception("Need join table primary key.");
}
$relation = $this->getRelation(); return new HasMany($modelName, $foreignKey, $value, $relation);
}
return new HasMany($modelName, $foreignKey, $value, $relation); /**
} * @return bool
* @throws Exception
*/
public function afterDelete(): bool
{
if (!$this->hasPrimary()) {
return TRUE;
}
$value = $this->getPrimaryValue();
if (empty($value)) {
return TRUE;
}
return TRUE;
}
/** /**
* @param $modelName * @return bool
* @param $foreignKey * @throws Exception
* @param $localKey */
* @return ActiveQuery public function beforeDelete(): bool
* @throws Exception {
*/ if (!$this->hasPrimary()) {
public function hasIn($modelName, $foreignKey, $localKey): mixed return TRUE;
{ }
if (($value = $this->getAttribute($localKey)) === null) { $value = $this->getPrimaryValue();
throw new Exception("Need join table primary key."); if (empty($value)) {
} return TRUE;
}
$relation = $this->getRelation(); return TRUE;
}
return new HasMany($modelName, $foreignKey, $value, $relation);
}
/**
* @return bool
* @throws Exception
*/
public function afterDelete(): bool
{
if (!$this->hasPrimary()) {
return TRUE;
}
$value = $this->getPrimaryValue();
if (empty($value)) {
return TRUE;
}
return TRUE;
}
/**
* @return bool
* @throws Exception
*/
public function beforeDelete(): bool
{
if (!$this->hasPrimary()) {
return TRUE;
}
$value = $this->getPrimaryValue();
if (empty($value)) {
return TRUE;
}
return TRUE;
}
} }
+152 -208
View File
@@ -13,233 +13,177 @@ use Swoole\Coroutine;
class Context extends BaseContext class Context extends BaseContext
{ {
protected static array $_contents = []; protected static array $_contents = [];
/** /**
* @param $id * @param $id
* @param $context * @param $context
* @param null $key * @return mixed
* @return mixed */
*/ public static function setContext($id, $context): mixed
public static function setContext($id, $context, $key = null): mixed {
{ if (Coroutine::getCid() === -1) {
if (Coroutine::getCid() === -1) { return static::$_contents[$id] = $context;
return static::setStatic($id, $context, $key); }
} return Coroutine::getContext()[$id] = $context;
return self::setCoroutine($id, $context, $key); }
}
/** /**
* @param $id * @param $id
* @param $context * @param int $value
* @param null $key * @return bool|int
* @return array */
*/ public static function increment($id, int $value = 1): bool|int
private static function setStatic($id, $context, $key = null): mixed {
{ if (!isset(Coroutine::getContext()[$id])) {
if (empty($key)) { return Coroutine::getContext()[$id] += $value;
return static::$_contents[$id] = $context; }
} return false;
if (!is_array(static::$_contents[$id])) { }
static::$_contents[$id] = [$key => $context];
} else {
static::$_contents[$id][$key] = $context;
}
return $context;
}
/** /**
* @param $id * @param $id
* @param $context * @param int $value
* @param null $key * @return bool|int
* @return mixed */
*/ public static function decrement($id, int $value = 1): bool|int
private static function setCoroutine($id, $context, $key = null): mixed {
{ if (!static::hasContext($id)) {
if (empty($key)) { return false;
return Coroutine::getContext()[$id] = $context; }
} if (isset(Coroutine::getContext()[$id])) {
if (!is_array(Coroutine::getContext()[$id])) { return Coroutine::getContext()[$id] -= $value;
Coroutine::getContext()[$id] = [$key => $context]; }
} else { return false;
Coroutine::getContext()[$id][$key] = $context; }
}
return $context;
}
/** /**
* @param $id * @param $id
* @param null $key * @param null $default
* @param int $value * @return mixed
* @return bool|int */
*/ public static function getContext($id, $default = null): mixed
public static function increment($id, $key = null, $value = 1): bool|int {
{ if (Coroutine::getCid() === -1) {
if (!isset(Coroutine::getContext()[$id][$key])) { return static::loadByStatic($id, $default);
return false; }
} return static::loadByContext($id, $default);
return Coroutine::getContext()[$id][$key] += $value; }
}
/**
* @param $id
* @param null $key
* @param int $value
* @return bool|int
*/
public static function decrement($id, $key = null, $value = 1): bool|int
{
if (!static::hasContext($id)) {
return false;
}
if (!isset(Coroutine::getContext()[$id][$key])) {
return false;
}
return Coroutine::getContext()[$id][$key] -= $value;
}
/**
* @param $id
* @param null $key
* @return mixed
*/
public static function getContext($id, $key = null): mixed
{
if (Coroutine::getCid() === -1) {
return static::loadByStatic($id, $key);
}
return static::loadByContext($id, $key);
}
/** /**
* @param $id * @param $id
* @param null $key * @param null $default
* @return mixed * @return mixed
*/ */
private static function loadByContext($id, $key = null): mixed private static function loadByContext($id, $default = null): mixed
{ {
$data = Coroutine::getContext()[$id] ?? null; $data = Coroutine::getContext()[$id] ?? null;
if ($data === null) { if ($data === null) {
return null; return $default;
} }
if ($key !== null) { return $data;
return $data[$key] ?? null; }
}
return $data;
}
/** /**
* @param $id * @param $id
* @param null $key * @param null $default
* @return mixed * @return mixed
*/ */
private static function loadByStatic($id, $key = null): mixed private static function loadByStatic($id, $default = null): mixed
{ {
$data = static::$_contents[$id] ?? null; $data = static::$_contents[$id] ?? null;
if ($data === null) { if ($data === null) {
return null; return $default;
} }
if ($key !== null) { return $data;
return $data[$key] ?? null; }
}
return $data;
}
/** /**
* @return mixed * @return mixed
*/ */
public static function getAllContext(): mixed public static function getAllContext(): mixed
{ {
if (Coroutine::getCid() === -1) { if (Coroutine::getCid() === -1) {
return Coroutine::getContext() ?? []; return Coroutine::getContext() ?? [];
} else { } else {
return static::$_contents ?? []; return static::$_contents ?? [];
} }
} }
/** /**
* @param string $id * @param string $id
* @param string|null $key */
*/ public static function remove(string $id)
public static function remove(string $id, string $key = null) {
{ if (!static::hasContext($id)) {
if (!static::hasContext($id, $key)) { return;
return; }
} if (Coroutine::getCid() === -1) {
if (Coroutine::getCid() === -1) { unset(static::$_contents[$id]);
if (!empty($key)) { } else {
unset(static::$_contents[$id][$key]); unset(Coroutine::getContext()[$id]);
} else { }
unset(static::$_contents[$id]); }
}
} else {
if (!empty($key)) {
unset(Coroutine::getContext()[$id][$key]);
} else {
unset(Coroutine::getContext()[$id]);
}
}
}
/** /**
* @param $id * @param $id
* @param null $key * @param null $key
* @return bool * @return bool
*/ */
public static function hasContext($id, $key = null): bool public static function hasContext($id, $key = null): bool
{ {
if (Coroutine::getCid() === -1) { if (Coroutine::getCid() === -1) {
return static::searchByStatic($id, $key); return static::searchByStatic($id, $key);
} }
return static::searchByCoroutine($id, $key); return static::searchByCoroutine($id, $key);
} }
/** /**
* @param $id * @param $id
* @param null $key * @param null $key
* @return bool * @return bool
*/ */
private static function searchByStatic($id, $key = null): bool private static function searchByStatic($id, $key = null): bool
{ {
if (!isset(static::$_contents[$id])) { if (!isset(static::$_contents[$id])) {
return false; return false;
} }
if (!empty($key) && !isset(static::$_contents[$id][$key])) { if (!empty($key) && !isset(static::$_contents[$id][$key])) {
return false; return false;
} }
return true; return true;
} }
/** /**
* @param $id * @param $id
* @param null $key * @param null $key
* @return bool * @return bool
*/ */
private static function searchByCoroutine($id, $key = null): bool private static function searchByCoroutine($id, $key = null): bool
{ {
if (!isset(Coroutine::getContext()[$id])) { if (!isset(Coroutine::getContext()[$id])) {
return false; return false;
} }
if ($key !== null) { if ($key !== null) {
return isset((Coroutine::getContext()[$id] ?? [])[$key]); return isset((Coroutine::getContext()[$id] ?? [])[$key]);
} }
return true; return true;
} }
/** /**
* @return bool * @return bool
*/ */
public static function inCoroutine(): bool public static function inCoroutine(): bool
{ {
return Coroutine::getCid() !== -1; return Coroutine::getCid() !== -1;
} }
} }
+31 -9
View File
@@ -17,7 +17,10 @@ use HttpServer\Controller;
use HttpServer\Http\Context; use HttpServer\Http\Context;
use HttpServer\Http\Request; use HttpServer\Http\Request;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use ReflectionException;
use Snowflake\Aop;
use Snowflake\Core\Json; use Snowflake\Core\Json;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Throwable; use Throwable;
@@ -109,30 +112,49 @@ class Node extends HttpService
} }
if (!empty($this->handler)) { if (!empty($this->handler)) {
$this->callback = Reduce::reduce($this->createDispatch(), $this->annotation()); $this->callback = Reduce::reduce($this->createDispatch(), $this->annotation());
$this->setAop();
} }
return $this; return $this;
} }
private array $_aop;
/** /**
* @return Closure * @return Closure
* @throws Exception
*/ */
public function createDispatch(): Closure public function createDispatch(): Closure
{ {
$handler = $this->handler; return static function () {
return static function () use ($handler) { $dispatchParam = Context::getContext('dispatch-param', [\request()]);
$dispatchParam = Context::getContext('dispatch-param'); if (empty($this->_aop) || $this->handler instanceof Closure) {
if (empty($dispatchParam)) { return call_user_func($this->handler, ...$dispatchParam);
$dispatchParam = [\request()];
} }
if ($handler instanceof Closure) { return call_user_func($this->_aop[0], $this->_aop[1], $dispatchParam);
return call_user_func($handler, ...$dispatchParam);
}
return \aop($handler, $dispatchParam);
}; };
} }
/**
* @throws ReflectionException
* @throws NotFindClassException
*/
private function setAop()
{
/** @var Aop $aop */
$aop = Snowflake::app()->get('aop');
if (!$aop->hasAop($this->handler)) {
return;
}
$reflect = $aop->getAop($this->handler);
$method = $reflect->getMethod('invoke');
$this->_aop = [[$method, 'invokeArgs'], $reflect->newInstance($this->handler)];
}
private bool $_hasBeforeAction = false; private bool $_hasBeforeAction = false;
+61 -49
View File
@@ -5,6 +5,8 @@ namespace Snowflake;
use Exception; use Exception;
use Reflection;
use ReflectionClass;
use ReflectionException; use ReflectionException;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
@@ -20,25 +22,35 @@ class Aop extends Component
{ {
private static array $_aop = []; private static array $_aop = [];
/** /**
* @param array $handler * @param array $handler
* @param string $aspect * @param string $aspect
*/ */
public function aop_add(array $handler, string $aspect) public function aop_add(array $handler, string $aspect)
{ {
[$class, $method] = $handler; [$class, $method] = $handler;
$alias = $class::class . '::' . $method; $alias = $class::class . '::' . $method;
if (!isset(static::$_aop[$alias])) { if (!isset(static::$_aop[$alias])) {
static::$_aop[$alias] = []; static::$_aop[$alias] = [];
} }
if (in_array($aspect, static::$_aop[$alias])) { if (in_array($aspect, static::$_aop[$alias])) {
return; return;
} }
static::$_aop[$alias][] = $aspect; static::$_aop[$alias][] = $aspect;
} }
/**
* @param $handler
* @return bool
*/
public function hasAop($handler): bool
{
return isset(static::$_aop[$handler[0]::class . '::' . $handler[1]]);
}
/** /**
@@ -49,38 +61,38 @@ class Aop extends Component
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
final public function dispatch($handler, $params): mixed final public function dispatch($handler, $params): mixed
{ {
if ($handler instanceof \Closure) { $aopName = $handler[0]::class . '::' . $handler[1];
return call_user_func($handler, ...$params);
} $reflect = Snowflake::getDi()->getReflect(current(static::$_aop[$aopName]));
$aopName = $handler[0]::class . '::' . $handler[1]; if (!$reflect->isInstantiable() || !$reflect->hasMethod('invoke')) {
if (!isset(static::$_aop[$aopName])) { throw new Exception(ASPECT_ERROR . IAspect::class);
return $this->notFound($handler, $params); }
} $method = $reflect->getMethod('invoke');
return $this->invoke($handler, $params, $aopName);
} return $method->invokeArgs($reflect->newInstance($handler), $params);
}
/** /**
* @param $handler * @param array $handler
* @param $params * @return ReflectionClass
* @param $aopName
* @return mixed
* @throws ReflectionException
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function invoke($handler, $params, $aopName): mixed public function getAop(array $handler): ReflectionClass
{ {
$reflect = Snowflake::getDi()->getReflect(current(static::$_aop[$aopName])); $aopName = $handler[0]::class . '::' . $handler[1];
if (!$reflect->isInstantiable() || !$reflect->hasMethod('invoke')) {
throw new Exception(ASPECT_ERROR . IAspect::class);
}
$method = $reflect->getMethod('invoke');
return $method->invokeArgs($reflect->newInstance($handler), $params); $reflect = Snowflake::getDi()->getReflect(current(static::$_aop[$aopName]));
} if (!$reflect->isInstantiable() || !$reflect->hasMethod('invoke')) {
throw new Exception(ASPECT_ERROR . IAspect::class);
}
return $reflect;
}
/** /**
@@ -89,12 +101,12 @@ class Aop extends Component
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function notFound($handler, $params): mixed private function notFound($handler, $params): mixed
{ {
if (!method_exists($handler[0], $handler[1])) { if (!method_exists($handler[0], $handler[1])) {
return response()->close(404); return response()->close(404);
} }
return call_user_func($handler, ...$params); return call_user_func($handler, ...$params);
} }
} }
+3 -2
View File
@@ -32,7 +32,8 @@ class Connection extends Component
*/ */
public function inTransaction($cds): bool public function inTransaction($cds): bool
{ {
return Context::getContext('begin_' . $this->getPool()->name('Mysql:' . $cds, true)) == 0; $name = $this->getPool()->name('Mysql:' . $cds, true);
return Context::getContext('begin_' . $name) == 0;
} }
/** /**
@@ -122,7 +123,7 @@ class Connection extends Component
$connections = $this->createClient($coroutineName, $config); $connections = $this->createClient($coroutineName, $config);
} }
} }
if ($number = Context::getContext('begin_' . $coroutineName, Coroutine::getCid())) { if ($number = Context::getContext('begin_' . $coroutineName)) {
$number > 0 && $connections->beginTransaction(); $number > 0 && $connections->beginTransaction();
} }
return Context::setContext($coroutineName, $connections); return Context::setContext($coroutineName, $connections);
+1 -1
View File
@@ -67,7 +67,7 @@ class Snowflake
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function set($alias, $array = []): mixed public static function set($alias, array $array = []): mixed
{ {
return static::app()->set($alias, $array); return static::app()->set($alias, $array);
} }