This commit is contained in:
2020-12-17 14:09:14 +08:00
parent 672a719dbd
commit 36c1d0502a
151 changed files with 1937 additions and 2848 deletions
+2 -1
View File
@@ -7,6 +7,7 @@ namespace Annotation;
use ReflectionAttribute; use ReflectionAttribute;
use ReflectionClass; use ReflectionClass;
use ReflectionException; use ReflectionException;
use ReflectionMethod;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -104,7 +105,7 @@ class Annotation extends Component
$reflect = $this->reflectClass($class); $reflect = $this->reflectClass($class);
if ($reflect->isInstantiable()) { if ($reflect->isInstantiable()) {
$object = $reflect->newInstance(); $object = $reflect->newInstance();
foreach ($reflect->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { foreach ($reflect->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$tmp = $this->resolveAnnotations($method, $alias, $object); $tmp = $this->resolveAnnotations($method, $alias, $object);
$this->_classes[$reflect->getName()][$method->getName()] = $tmp; $this->_classes[$reflect->getName()][$method->getName()] = $tmp;
+28 -35
View File
@@ -6,6 +6,7 @@
* Time: 14:42 * Time: 14:42
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Database; namespace Database;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
@@ -86,7 +87,7 @@ class ActiveQuery extends Component
* @param $value * @param $value
* @return $this * @return $this
*/ */
public function addParam($key, $value) public function addParam($key, $value): static
{ {
$this->attributes[$key] = $value; $this->attributes[$key] = $value;
return $this; return $this;
@@ -96,7 +97,7 @@ class ActiveQuery extends Component
* @param array $values * @param array $values
* @return $this * @return $this
*/ */
public function addParams(array $values) public function addParams(array $values): static
{ {
foreach ($values as $key => $val) { foreach ($values as $key => $val) {
$this->addParam($key, $val); $this->addParam($key, $val);
@@ -108,7 +109,7 @@ class ActiveQuery extends Component
* @param $name * @param $name
* @return $this * @return $this
*/ */
public function with($name) public function with($name): static
{ {
if (empty($name)) { if (empty($name)) {
return $this; return $this;
@@ -126,17 +127,17 @@ class ActiveQuery extends Component
* @param bool $isArray * @param bool $isArray
* @return $this * @return $this
*/ */
public function asArray($isArray = TRUE) public function asArray($isArray = TRUE): static
{ {
$this->asArray = $isArray; $this->asArray = $isArray;
return $this; return $this;
} }
/** /**
* @return ActiveRecord * @return ActiveRecord|array|null
* @throws * @throws Exception
*/ */
public function first() public function first(): ActiveRecord|array|null
{ {
$data = $this->modelClass::getDb() $data = $this->modelClass::getDb()
->createCommand($this->oneLimit()->queryBuilder()) ->createCommand($this->oneLimit()->queryBuilder())
@@ -156,7 +157,7 @@ class ActiveQuery extends Component
/** /**
* @return array|Collection * @return array|Collection
*/ */
public function get() public function get(): Collection|array
{ {
return $this->all(); return $this->all();
} }
@@ -165,7 +166,7 @@ class ActiveQuery extends Component
/** /**
* @throws Exception * @throws Exception
*/ */
public function flush() public function flush(): array|bool|int|string|null
{ {
$sql = $this->getChange()->truncate($this->getTable()); $sql = $this->getChange()->truncate($this->getTable());
return $this->command($sql)->flush(); return $this->command($sql)->flush();
@@ -178,7 +179,7 @@ class ActiveQuery extends Component
* @return Pagination * @return Pagination
* @throws Exception * @throws Exception
*/ */
public function page(int $size, callable $callback) public function page(int $size, callable $callback): Pagination
{ {
$pagination = new Pagination($this); $pagination = new Pagination($this);
$pagination->setOffset(0); $pagination->setOffset(0);
@@ -194,7 +195,7 @@ class ActiveQuery extends Component
* @return array|null * @return array|null
* @throws Exception * @throws Exception
*/ */
public function column(string $field, $setKey = '') public function column(string $field, $setKey = ''): ?array
{ {
return $this->all()->column($field, $setKey); return $this->all()->column($field, $setKey);
} }
@@ -203,7 +204,7 @@ class ActiveQuery extends Component
* @return array|Collection * @return array|Collection
* @throws * @throws
*/ */
public function all() public function all(): Collection|array
{ {
$collect = new Collection($this, $this->modelClass::getDb() $collect = new Collection($this, $this->modelClass::getDb()
->createCommand($this->queryBuilder()) ->createCommand($this->queryBuilder())
@@ -220,7 +221,7 @@ class ActiveQuery extends Component
* @return ActiveRecord * @return ActiveRecord
* @throws Exception * @throws Exception
*/ */
public function populate(ActiveRecord $model, $data) public function populate(ActiveRecord $model, $data): ActiveRecord
{ {
return $this->getWith($model::populate($data)); return $this->getWith($model::populate($data));
} }
@@ -230,7 +231,7 @@ class ActiveQuery extends Component
* @param $model * @param $model
* @return mixed * @return mixed
*/ */
public function getWith($model) public function getWith($model): mixed
{ {
if (empty($this->with) || !is_array($this->with)) { if (empty($this->with) || !is_array($this->with)) {
return $model; return $model;
@@ -249,7 +250,7 @@ class ActiveQuery extends Component
* @return int * @return int
* @throws Exception * @throws Exception
*/ */
public function count() public function count(): int
{ {
$data = $this->modelClass::getDb() $data = $this->modelClass::getDb()
->createCommand($this->getBuild()->count($this)) ->createCommand($this->getBuild()->count($this))
@@ -266,7 +267,7 @@ class ActiveQuery extends Component
* @return array|Command|bool|int|string * @return array|Command|bool|int|string
* @throws Exception * @throws Exception
*/ */
public function batchUpdate(array $data) public function batchUpdate(array $data): Command|array|bool|int|string
{ {
return $this->getDb()->createCommand() return $this->getDb()->createCommand()
->batchUpdate($this->getTable(), $data, $this->getCondition()) ->batchUpdate($this->getTable(), $data, $this->getCondition())
@@ -278,7 +279,7 @@ class ActiveQuery extends Component
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function batchInsert(array $data) public function batchInsert(array $data): bool
{ {
return $this->getDb()->createCommand() return $this->getDb()->createCommand()
->batchInsert($this->getTable(), $data) ->batchInsert($this->getTable(), $data)
@@ -301,7 +302,7 @@ class ActiveQuery extends Component
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function exists() public function exists(): bool
{ {
$column = $this->modelClass::getDb() $column = $this->modelClass::getDb()
->createCommand($this->queryBuilder()) ->createCommand($this->queryBuilder())
@@ -309,31 +310,23 @@ class ActiveQuery extends Component
return $column !== false; return $column !== false;
} }
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function deleteAll() public function delete(): bool
{ {
return $this->modelClass::getDb() return $this->modelClass::getDb()
->createCommand($this->queryBuilder()) ->createCommand($this->queryBuilder())
->delete(); ->delete();
} }
/**
* @return bool
* @throws Exception
*/
public function delete()
{
return $this->deleteAll();
}
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function getCondition() public function getCondition(): string
{ {
return $this->getBuild()->getWhere($this->where); return $this->getBuild()->getWhere($this->where);
} }
@@ -342,7 +335,7 @@ class ActiveQuery extends Component
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function queryBuilder() public function queryBuilder(): string
{ {
return $this->getBuild()->getQuery($this); return $this->getBuild()->getQuery($this);
} }
@@ -353,7 +346,7 @@ class ActiveQuery extends Component
* @return Command * @return Command
* @throws Exception * @throws Exception
*/ */
private function command($sql, $attr = []) private function command($sql, $attr = []): Command
{ {
if (!empty($attr) && is_array($attr)) { if (!empty($attr) && is_array($attr)) {
$attr = array_merge($this->attributes, $attr); $attr = array_merge($this->attributes, $attr);
@@ -368,7 +361,7 @@ class ActiveQuery extends Component
* @return Select * @return Select
* @throws Exception * @throws Exception
*/ */
public function getBuild() public function getBuild(): Select
{ {
return $this->getDb()->getSchema()->getQueryBuilder(); return $this->getDb()->getSchema()->getQueryBuilder();
} }
@@ -377,7 +370,7 @@ class ActiveQuery extends Component
* @return orm\Change * @return orm\Change
* @throws Exception * @throws Exception
*/ */
public function getChange() public function getChange(): orm\Change
{ {
return $this->getDb()->getSchema()->getChange(); return $this->getDb()->getSchema()->getChange();
} }
@@ -386,7 +379,7 @@ class ActiveQuery extends Component
* @return Connection * @return Connection
* @throws Exception * @throws Exception
*/ */
public function getDb() public function getDb(): Connection
{ {
return $this->modelClass::getDb(); return $this->modelClass::getDb();
} }
@@ -395,7 +388,7 @@ class ActiveQuery extends Component
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function getPrimary() public function getPrimary(): mixed
{ {
return $this->modelClass->getPrimary(); return $this->modelClass->getPrimary();
} }
+36 -34
View File
@@ -14,6 +14,7 @@ use Exception;
use Database\Base\BaseActiveRecord; use Database\Base\BaseActiveRecord;
use Snowflake\Core\ArrayAccess; use Snowflake\Core\ArrayAccess;
use Snowflake\Error\Logger; use Snowflake\Error\Logger;
use Snowflake\Exception\ComponentException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
defined('SAVE_FAIL') or define('SAVE_FAIL', 3227); defined('SAVE_FAIL') or define('SAVE_FAIL', 3227);
@@ -37,7 +38,7 @@ class ActiveRecord extends BaseActiveRecord
/** /**
* @return array * @return array
*/ */
public function rules() public function rules(): array
{ {
return []; return [];
} }
@@ -48,7 +49,7 @@ class ActiveRecord extends BaseActiveRecord
* @return ActiveRecord|false * @return ActiveRecord|false
* @throws Exception * @throws Exception
*/ */
public function increment(string $column, int $value) public function increment(string $column, int $value): bool|ActiveRecord
{ {
if (!$this->mathematics(self::INCR, [$column => $value])) { if (!$this->mathematics(self::INCR, [$column => $value])) {
return false; return false;
@@ -64,7 +65,7 @@ class ActiveRecord extends BaseActiveRecord
* @return ActiveRecord|false * @return ActiveRecord|false
* @throws Exception * @throws Exception
*/ */
public function decrement(string $column, int $value) public function decrement(string $column, int $value): bool|ActiveRecord
{ {
if (!$this->mathematics(self::DECR, [$column => $value])) { if (!$this->mathematics(self::DECR, [$column => $value])) {
return false; return false;
@@ -79,7 +80,7 @@ class ActiveRecord extends BaseActiveRecord
* @return ActiveRecord|false * @return ActiveRecord|false
* @throws Exception * @throws Exception
*/ */
public function increments(array $columns) public function increments(array $columns): bool|static
{ {
if (!$this->mathematics(self::INCR, $columns)) { if (!$this->mathematics(self::INCR, $columns)) {
return false; return false;
@@ -96,7 +97,7 @@ class ActiveRecord extends BaseActiveRecord
* @return ActiveRecord|false * @return ActiveRecord|false
* @throws Exception * @throws Exception
*/ */
public function decrements(array $columns) public function decrements(array $columns): bool|static
{ {
if (!$this->mathematics(self::DECR, $columns)) { if (!$this->mathematics(self::DECR, $columns)) {
return false; return false;
@@ -108,12 +109,13 @@ class ActiveRecord extends BaseActiveRecord
} }
/** /**
* @param $attributes * @param array $condition
* @param $condition * @param array $attributes
* @return bool|ActiveRecord|mixed * @return mixed
* @throws ComponentException
* @throws Exception * @throws Exception
*/ */
public static function findOrCreate(array $condition, array $attributes = []) public static function findOrCreate(array $condition, array $attributes = []): mixed
{ {
$select = static::find()->where($condition)->first(); $select = static::find()->where($condition)->first();
if (!empty($select)) { if (!empty($select)) {
@@ -138,7 +140,7 @@ class ActiveRecord extends BaseActiveRecord
* @return array|bool|int|string|null * @return array|bool|int|string|null
* @throws Exception * @throws Exception
*/ */
private function mathematics($action, $columns, $condition = []) private function mathematics($action, $columns, $condition = []): int|bool|array|string|null
{ {
if (empty($condition)) { if (empty($condition)) {
$condition = [$this->getPrimary() => $this->getPrimaryValue()]; $condition = [$this->getPrimary() => $this->getPrimaryValue()];
@@ -155,7 +157,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public static function incrAll($column, $value, $condition = []) public static function incrAll($column, $value, $condition = []): bool
{ {
return static::getDb()->createCommand() return static::getDb()->createCommand()
->mathematics(self::getTable(), [self::INCR => [$column, $value]], $condition) ->mathematics(self::getTable(), [self::INCR => [$column, $value]], $condition)
@@ -170,7 +172,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public static function decrAll($column, $value, $condition = []) public static function decrAll($column, $value, $condition = []): bool
{ {
return static::getDb()->createCommand() return static::getDb()->createCommand()
->mathematics(self::getTable(), [self::DECR => [$column, $value]], $condition) ->mathematics(self::getTable(), [self::DECR => [$column, $value]], $condition)
@@ -183,7 +185,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool * @return bool
* @throws * @throws
*/ */
public function update(array $attributes) public function update(array $attributes): bool
{ {
return $this->save($attributes); return $this->save($attributes);
} }
@@ -194,7 +196,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool|static * @return bool|static
* @throws Exception * @throws Exception
*/ */
public static function insertOrUpdate(array $params, array $condition) public static function insertOrUpdate(array $params, array $condition): bool|static
{ {
$first = static::findOrCreate($condition, $params); $first = static::findOrCreate($condition, $params);
$first->attributes = $params; $first->attributes = $params;
@@ -223,7 +225,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function delete() public function delete(): bool
{ {
$conditions = $this->_oldAttributes; $conditions = $this->_oldAttributes;
if (empty($conditions)) { if (empty($conditions)) {
@@ -253,7 +255,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public static function batchUpdate($condition, $attributes = []) public static function batchUpdate($condition, $attributes = []): bool
{ {
$condition = static::find()->where($condition); $condition = static::find()->where($condition);
return $condition->batchUpdate($attributes); return $condition->batchUpdate($attributes);
@@ -263,10 +265,10 @@ class ActiveRecord extends BaseActiveRecord
* @param $condition * @param $condition
* @param array $attributes * @param array $attributes
* *
* @return array|mixed|null|Collection * @return array|Collection
* @throws Exception * @throws Exception
*/ */
public static function findAll($condition, $attributes = []) public static function findAll($condition, $attributes = []): array|Collection
{ {
$query = static::find()->where($condition); $query = static::find()->where($condition);
if (!empty($attributes)) { if (!empty($attributes)) {
@@ -277,10 +279,10 @@ class ActiveRecord extends BaseActiveRecord
/** /**
* @param $data * @param $data
* @return array|mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function resolveObject($data) private function resolveObject($data): mixed
{ {
if (is_numeric($data) || !is_string($data)) { if (is_numeric($data) || !is_string($data)) {
return $data; return $data;
@@ -303,10 +305,10 @@ class ActiveRecord extends BaseActiveRecord
/** /**
* @return array|mixed * @return array
* @throws Exception * @throws Exception
*/ */
public function toArray() public function toArray(): array
{ {
$data = []; $data = [];
foreach ($this->_attributes as $key => $val) { foreach ($this->_attributes as $key => $val) {
@@ -319,7 +321,7 @@ class ActiveRecord extends BaseActiveRecord
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
private function runRelate() private function runRelate(): array
{ {
$relates = []; $relates = [];
if (empty($this->_relate)) { if (empty($this->_relate)) {
@@ -333,13 +335,13 @@ class ActiveRecord extends BaseActiveRecord
/** /**
* @param $modelName * @param string $modelName
* @param $foreignKey * @param $foreignKey
* @param $localKey * @param $localKey
* @return mixed|ActiveQuery * @return HasOne
* @throws Exception * @throws Exception
*/ */
public function hasOne(string $modelName, $foreignKey, $localKey) public function hasOne(string $modelName, $foreignKey, $localKey): HasOne
{ {
if (!$this->has($localKey)) { if (!$this->has($localKey)) {
throw new Exception("Need join table primary key."); throw new Exception("Need join table primary key.");
@@ -357,10 +359,10 @@ class ActiveRecord extends BaseActiveRecord
* @param $modelName * @param $modelName
* @param $foreignKey * @param $foreignKey
* @param $localKey * @param $localKey
* @return mixed|ActiveQuery * @return HasCount
* @throws Exception * @throws Exception
*/ */
public function hasCount($modelName, $foreignKey, $localKey) public function hasCount($modelName, $foreignKey, $localKey): HasCount
{ {
if (!$this->has($localKey)) { if (!$this->has($localKey)) {
throw new Exception("Need join table primary key."); throw new Exception("Need join table primary key.");
@@ -378,10 +380,10 @@ class ActiveRecord extends BaseActiveRecord
* @param $modelName * @param $modelName
* @param $foreignKey * @param $foreignKey
* @param $localKey * @param $localKey
* @return mixed|ActiveQuery * @return HasMany
* @throws Exception * @throws Exception
*/ */
public function hasMany($modelName, $foreignKey, $localKey) public function hasMany($modelName, $foreignKey, $localKey): HasMany
{ {
if (!$this->has($localKey)) { if (!$this->has($localKey)) {
throw new Exception("Need join table primary key."); throw new Exception("Need join table primary key.");
@@ -398,10 +400,10 @@ class ActiveRecord extends BaseActiveRecord
* @param $modelName * @param $modelName
* @param $foreignKey * @param $foreignKey
* @param $localKey * @param $localKey
* @return mixed|ActiveQuery * @return HasMany
* @throws Exception * @throws Exception
*/ */
public function hasIn($modelName, $foreignKey, $localKey) public function hasIn($modelName, $foreignKey, $localKey): HasMany
{ {
if (!$this->has($localKey)) { if (!$this->has($localKey)) {
throw new Exception("Need join table primary key."); throw new Exception("Need join table primary key.");
@@ -418,7 +420,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function afterDelete() public function afterDelete(): bool
{ {
if (!$this->hasPrimary()) { if (!$this->hasPrimary()) {
return TRUE; return TRUE;
@@ -434,7 +436,7 @@ class ActiveRecord extends BaseActiveRecord
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function beforeDelete() public function beforeDelete(): bool
{ {
if (!$this->hasPrimary()) { if (!$this->hasPrimary()) {
return TRUE; return TRUE;
+4 -2
View File
@@ -12,6 +12,8 @@ namespace Database\Base;
use ArrayIterator; use ArrayIterator;
use Database\ActiveQuery; use Database\ActiveQuery;
use JetBrains\PhpStorm\Pure;
use ReflectionException;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Database\ActiveRecord; use Database\ActiveRecord;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
@@ -53,7 +55,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
/** /**
* @return int * @return int
*/ */
public function getLength(): int #[Pure] public function getLength(): int
{ {
return count($this->_item); return count($this->_item);
} }
@@ -86,7 +88,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
/** /**
* @return Traversable|CollectionIterator|ArrayIterator * @return Traversable|CollectionIterator|ArrayIterator
* @throws \ReflectionException * @throws ReflectionException
* @throws NotFindClassException * @throws NotFindClassException
*/ */
public function getIterator(): Traversable|CollectionIterator|ArrayIterator public function getIterator(): Traversable|CollectionIterator|ArrayIterator
+18 -15
View File
@@ -11,6 +11,7 @@ namespace Database\Base;
use HttpServer\Http\Context; use HttpServer\Http\Context;
use ReflectionException;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Core\JSON; use Snowflake\Core\JSON;
use Database\ActiveQuery; use Database\ActiveQuery;
@@ -23,6 +24,7 @@ use Database\Relation;
use Snowflake\Error\Logger; use Snowflake\Error\Logger;
use Exception; use Exception;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Exception\NotFindClassException;
use validator\Validator; use validator\Validator;
use Database\IOrm; use Database\IOrm;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -181,7 +183,7 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess
* @return null|string * @return null|string
* @throws Exception * @throws Exception
*/ */
public function getPrimaryValue() public function getPrimaryValue(): ?string
{ {
if (!$this->hasPrimary()) { if (!$this->hasPrimary()) {
return null; return null;
@@ -190,14 +192,14 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess
} }
/** /**
* @param $condition * @param $param
* @param $db * @param $db
* @return $this * @return $this
* @throws * @throws
*/ */
public static function findOne($condition, $db = NULL) public static function findOne($param, $db = NULL): static
{ {
if (is_numeric($condition)) { if (is_numeric($param)) {
$primary = static::getColumns()->getPrimaryKeys(); $primary = static::getColumns()->getPrimaryKeys();
if (empty($primary)) { if (empty($primary)) {
throw new Exception('Primary key cannot be empty.'); throw new Exception('Primary key cannot be empty.');
@@ -205,9 +207,9 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess
if (is_array($primary)) { if (is_array($primary)) {
$primary = current($primary); $primary = current($primary);
} }
$condition = [$primary => $condition]; $param = [$primary => $param];
} }
return static::find()->where($condition)->first(); return static::find()->where($param)->first();
} }
/** /**
@@ -234,10 +236,11 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess
} }
/** /**
* @return mixed|ActiveQuery * @return ActiveQuery
* @throws * @throws ReflectionException
* @throws NotFindClassException
*/ */
public static function find() public static function find():ActiveQuery
{ {
return Snowflake::createObject(ActiveQuery::class, [get_called_class()]); return Snowflake::createObject(ActiveQuery::class, [get_called_class()]);
} }
@@ -250,19 +253,19 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public static function deleteAll($condition = NULL, $attributes = [], $if_condition_is_null = false) public static function delete($condition = NULL, $attributes = [], $if_condition_is_null = false): bool
{ {
if (empty($condition)) { if (empty($condition)) {
if (!$if_condition_is_null) { if (!$if_condition_is_null) {
return false; return false;
} }
return static::find()->deleteAll(); return static::find()->delete();
} }
$model = static::find()->ifNotWhere($if_condition_is_null)->where($condition); $model = static::find()->ifNotWhere($if_condition_is_null)->where($condition);
if (!empty($attributes)) { if (!empty($attributes)) {
$model->bindParams($attributes); $model->bindParams($attributes);
} }
return $model->deleteAll(); return $model->delete();
} }
@@ -659,10 +662,10 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess
/** /**
* @param $name * @param $name
* @return mixed|null * @return mixed
* @throws Exception * @throws Exception
*/ */
public function __get($name) public function __get($name): mixed
{ {
$method = 'get' . ucfirst($name); $method = 'get' . ucfirst($name);
if (method_exists($this, $method . 'Attribute')) { if (method_exists($this, $method . 'Attribute')) {
@@ -780,7 +783,7 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function setDatabaseConnect($bsName) public static function setDatabaseConnect($bsName): Connection
{ {
return Snowflake::app()->db->get($bsName); return Snowflake::app()->db->get($bsName);
} }
+18 -17
View File
@@ -6,6 +6,7 @@
* Time: 13:38 * Time: 13:38
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Database; namespace Database;
use Database\Base\AbstractCollection; use Database\Base\AbstractCollection;
@@ -35,7 +36,7 @@ class Collection extends AbstractCollection
* @return array|null * @return array|null
* @throws Exception * @throws Exception
*/ */
public function values($field) public function values($field): ?array
{ {
if (empty($field) || !is_string($field)) { if (empty($field) || !is_string($field)) {
return NULL; return NULL;
@@ -53,7 +54,7 @@ class Collection extends AbstractCollection
* @param string $field * @param string $field
* @return array|null * @return array|null
*/ */
public function keyBy(string $field) public function keyBy(string $field): ?array
{ {
$array = $this->toArray(); $array = $this->toArray();
$column = array_flip(array_column($array, $field)); $column = array_flip(array_column($array, $field));
@@ -67,7 +68,7 @@ class Collection extends AbstractCollection
/** /**
* @return $this * @return $this
*/ */
public function orderRand() public function orderRand(): static
{ {
shuffle($this->_item); shuffle($this->_item);
return $this; return $this;
@@ -79,7 +80,7 @@ class Collection extends AbstractCollection
* *
* @return array * @return array
*/ */
public function slice($start = 0, $length = 20) #[Pure] public function slice($start = 0, $length = 20): array
{ {
if (empty($this->_item) || !is_array($this->_item)) { if (empty($this->_item) || !is_array($this->_item)) {
return []; return [];
@@ -97,7 +98,7 @@ class Collection extends AbstractCollection
* *
* @return array|null * @return array|null
*/ */
public function column($field, $setKey = '') public function column($field, $setKey = ''): ?array
{ {
$data = $this->toArray(); $data = $this->toArray();
if (empty($data)) { if (empty($data)) {
@@ -115,7 +116,7 @@ class Collection extends AbstractCollection
* *
* @return float|int|null * @return float|int|null
*/ */
public function sum($field) public function sum($field): float|int|null
{ {
$array = $this->column($field); $array = $this->column($field);
if (empty($array)) { if (empty($array)) {
@@ -125,9 +126,9 @@ class Collection extends AbstractCollection
} }
/** /**
* @return ActiveRecord|mixed * @return ActiveRecord|array
*/ */
public function current() #[Pure] public function current(): ActiveRecord|array
{ {
return current($this->_item); return current($this->_item);
} }
@@ -135,7 +136,7 @@ class Collection extends AbstractCollection
/** /**
* @return int * @return int
*/ */
public function size() #[Pure] public function size(): int
{ {
return (int)count($this->_item); return (int)count($this->_item);
} }
@@ -144,7 +145,7 @@ class Collection extends AbstractCollection
* @return array * @return array
* @throws * @throws
*/ */
public function toArray() public function toArray(): array
{ {
$array = []; $array = [];
foreach ($this as $value) { foreach ($this as $value) {
@@ -161,7 +162,7 @@ class Collection extends AbstractCollection
* @throws Exception * @throws Exception
* 批量删除 * 批量删除
*/ */
public function delete() public function delete(): bool
{ {
$model = $this->model; $model = $this->model;
if (!$model->hasPrimary()) { if (!$model->hasPrimary()) {
@@ -177,7 +178,7 @@ class Collection extends AbstractCollection
} }
return $this->model::find() return $this->model::find()
->in($model->getPrimary(), $ids) ->in($model->getPrimary(), $ids)
->deleteAll(); ->delete();
} }
/** /**
@@ -185,7 +186,7 @@ class Collection extends AbstractCollection
* @return Collection * @return Collection
* @throws * @throws
*/ */
public function filter(array $condition) public function filter(array $condition): Collection|static
{ {
$_filters = []; $_filters = [];
if (empty($condition)) { if (empty($condition)) {
@@ -207,7 +208,7 @@ class Collection extends AbstractCollection
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
private function filterCheck($value, $condition) private function filterCheck($value, $condition): bool
{ {
$_value = $value; $_value = $value;
if ($_value instanceof ActiveRecord) { if ($_value instanceof ActiveRecord) {
@@ -224,9 +225,9 @@ class Collection extends AbstractCollection
/** /**
* @param $key * @param $key
* @param $value * @param $value
* @return ActiveRecord|mixed|null * @return mixed
*/ */
public function exists($key, $value) public function exists($key, $value): mixed
{ {
foreach ($this as $item) { foreach ($this as $item) {
if ($item->$key === $value) { if ($item->$key === $value) {
@@ -239,7 +240,7 @@ class Collection extends AbstractCollection
/** /**
* @return bool * @return bool
*/ */
public function isEmpty() #[Pure] public function isEmpty(): bool
{ {
return $this->size() < 1; return $this->size() < 1;
} }
+38 -38
View File
@@ -43,10 +43,10 @@ class Command extends Component
/** /**
* @return bool|PDOStatement * @return array|bool|int|string|PDOStatement|null
* @throws * @throws Exception
*/ */
public function incrOrDecr() public function incrOrDecr(): array|bool|int|string|PDOStatement|null
{ {
return $this->execute(static::EXECUTE); return $this->execute(static::EXECUTE);
} }
@@ -54,10 +54,10 @@ class Command extends Component
/** /**
* @param bool $isInsert * @param bool $isInsert
* @param bool $hasAutoIncrement * @param bool $hasAutoIncrement
* @return bool|string * @return int|bool|array|string|null
* @throws * @throws Exception
*/ */
public function save($isInsert = TRUE, $hasAutoIncrement = true) public function save($isInsert = TRUE, $hasAutoIncrement = true): int|bool|array|string|null
{ {
return $this->execute(static::EXECUTE, $isInsert, $hasAutoIncrement); return $this->execute(static::EXECUTE, $isInsert, $hasAutoIncrement);
} }
@@ -70,7 +70,7 @@ class Command extends Component
* @return Command * @return Command
* @throws Exception * @throws Exception
*/ */
public function update($model, $attributes, $condition, $param) public function update($model, $attributes, $condition, $param): Command
{ {
$change = $this->db->getSchema()->getChange(); $change = $this->db->getSchema()->getChange();
$sql = $change->update($model, $attributes, $condition, $param); $sql = $change->update($model, $attributes, $condition, $param);
@@ -85,7 +85,7 @@ class Command extends Component
* @return Command * @return Command
* @throws Exception * @throws Exception
*/ */
public function batchUpdate($tableName, $attributes, $condition) public function batchUpdate($tableName, $attributes, $condition): Command
{ {
$change = $this->db->getSchema()->getChange(); $change = $this->db->getSchema()->getChange();
[$sql, $param] = $change->batchUpdate($tableName, $attributes, $condition); [$sql, $param] = $change->batchUpdate($tableName, $attributes, $condition);
@@ -99,7 +99,7 @@ class Command extends Component
* @return Command * @return Command
* @throws Exception * @throws Exception
*/ */
public function batchInsert($tableName, $attributes) public function batchInsert($tableName, $attributes): Command
{ {
$change = $this->db->getSchema()->getChange(); $change = $this->db->getSchema()->getChange();
$attribute_key = array_keys(current($attributes)); $attribute_key = array_keys(current($attributes));
@@ -114,7 +114,7 @@ class Command extends Component
* @return Command * @return Command
* @throws Exception * @throws Exception
*/ */
public function insert($tableName, $attributes, $param) public function insert($tableName, $attributes, $param): Command
{ {
$change = $this->db->getSchema()->getChange(); $change = $this->db->getSchema()->getChange();
$sql = $change->insert($tableName, $attributes, $param); $sql = $change->insert($tableName, $attributes, $param);
@@ -122,10 +122,10 @@ class Command extends Component
} }
/** /**
* @return bool|int * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function all() public function all(): int|bool|array|string|null
{ {
return $this->execute(static::FETCH_ALL); return $this->execute(static::FETCH_ALL);
} }
@@ -137,7 +137,7 @@ class Command extends Component
* @return Command * @return Command
* @throws Exception * @throws Exception
*/ */
public function mathematics($tableName, $param, $condition) public function mathematics($tableName, $param, $condition): static
{ {
$change = $this->db->getSchema()->getChange(); $change = $this->db->getSchema()->getChange();
$sql = $change->mathematics($tableName, $param, $condition); $sql = $change->mathematics($tableName, $param, $condition);
@@ -145,49 +145,49 @@ class Command extends Component
} }
/** /**
* @return array|mixed * @return array|bool|int|string|null
* @throws Exception * @throws Exception
*/ */
public function one() public function one(): null|array|bool|int|string
{ {
return $this->execute(static::FETCH); return $this->execute(static::FETCH);
} }
/** /**
* @return bool|int * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function fetchColumn() public function fetchColumn(): int|bool|array|string|null
{ {
return $this->execute(static::FETCH_COLUMN); return $this->execute(static::FETCH_COLUMN);
} }
/** /**
* @return bool|int * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function rowCount() public function rowCount(): int|bool|array|string|null
{ {
return $this->execute(static::ROW_COUNT); return $this->execute(static::ROW_COUNT);
} }
/** /**
* @return bool|int * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function flush() public function flush(): int|bool|array|string|null
{ {
return $this->execute(static::EXECUTE); return $this->execute(static::EXECUTE);
} }
/** /**
* @param $type * @param $type
* @param $isInsert * @param null $isInsert
* @param $hasAutoIncrement * @param bool $hasAutoIncrement
* @return bool|int * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
private function execute($type, $isInsert = null, $hasAutoIncrement = true) private function execute($type, $isInsert = null, $hasAutoIncrement = true): int|bool|array|string|null
{ {
try { try {
$time = microtime(true); $time = microtime(true);
@@ -211,10 +211,10 @@ class Command extends Component
/** /**
* @param $type * @param $type
* @return array|int|mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function search($type) private function search($type): mixed
{ {
$connect = $this->db->getConnect($this->sql); $connect = $this->db->getConnect($this->sql);
if (!($connect instanceof PDO)) { if (!($connect instanceof PDO)) {
@@ -239,7 +239,7 @@ class Command extends Component
* @return bool|string * @return bool|string
* @throws Exception * @throws Exception
*/ */
private function insert_or_change($isInsert, $hasAutoIncrement) private function insert_or_change($isInsert, $hasAutoIncrement): bool|string
{ {
if (!($connection = $this->initPDOStatement())) { if (!($connection = $this->initPDOStatement())) {
return false; return false;
@@ -262,7 +262,7 @@ class Command extends Component
* 重新构建 * 重新构建
* @throws * @throws
*/ */
private function initPDOStatement() private function initPDOStatement(): PDO|bool|null
{ {
if (empty($this->sql)) { if (empty($this->sql)) {
return null; return null;
@@ -281,7 +281,7 @@ class Command extends Component
* @param $modelName * @param $modelName
* @return $this * @return $this
*/ */
public function setModelName($modelName) public function setModelName($modelName): static
{ {
$this->_modelName = $modelName; $this->_modelName = $modelName;
return $this; return $this;
@@ -290,25 +290,25 @@ class Command extends Component
/** /**
* @return string * @return string
*/ */
public function getModelName() public function getModelName(): string
{ {
return $this->_modelName; return $this->_modelName;
} }
/** /**
* @return bool|int * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function delete() public function delete(): int|bool|array|string|null
{ {
return $this->execute(static::EXECUTE); return $this->execute(static::EXECUTE);
} }
/** /**
* @return bool|int * @return int|bool|array|string|null
* @throws Exception * @throws Exception
*/ */
public function exec() public function exec(): int|bool|array|string|null
{ {
return $this->execute(static::EXECUTE); return $this->execute(static::EXECUTE);
} }
@@ -317,7 +317,7 @@ class Command extends Component
* @param array|null $data * @param array|null $data
* @return $this * @return $this
*/ */
public function bindValues(array $data = NULL) public function bindValues(array $data = NULL): static
{ {
if (!is_array($this->params)) { if (!is_array($this->params)) {
$this->params = []; $this->params = [];
@@ -333,7 +333,7 @@ class Command extends Component
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function setSql($sql) public function setSql($sql): static
{ {
$this->sql = $sql; $this->sql = $sql;
return $this; return $this;
@@ -342,7 +342,7 @@ class Command extends Component
/** /**
* @return string * @return string
*/ */
public function getError() public function getError(): string
{ {
return $this->prepare->errorInfo()[2] ?? 'Db 驱动错误.'; return $this->prepare->errorInfo()[2] ?? 'Db 驱动错误.';
} }
+6 -5
View File
@@ -7,6 +7,7 @@ namespace Database\Condition;
use Database\ActiveQuery; use Database\ActiveQuery;
use Database\Base\ConditionClassMap; use Database\Base\ConditionClassMap;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure;
use Snowflake\Core\Str; use Snowflake\Core\Str;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -23,7 +24,7 @@ class ArrayCondition extends Condition
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function builder() public function builder(): mixed
{ {
if ($this->value instanceof Condition) { if ($this->value instanceof Condition) {
return $this->value->builder(); return $this->value->builder();
@@ -58,7 +59,7 @@ class ArrayCondition extends Condition
* @param $value * @param $value
* @return bool * @return bool
*/ */
private function isMath($value) #[Pure] private function isMath($value): bool
{ {
return isset($value[0]) && in_array($value[0], $this->math); return isset($value[0]) && in_array($value[0], $this->math);
} }
@@ -68,7 +69,7 @@ class ArrayCondition extends Condition
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function buildOperaCondition($value) public function buildOperaCondition(array $value): mixed
{ {
[$option['opera'], $option['column'], $option['value']] = $value; [$option['opera'], $option['column'], $option['value']] = $value;
$strPer = strtoupper($option['opera']); $strPer = strtoupper($option['opera']);
@@ -79,7 +80,7 @@ class ArrayCondition extends Condition
} }
$option = array_merge($option, $class); $option = array_merge($option, $class);
} else if ($value instanceof ActiveQuery) { } else if ($value instanceof ActiveQuery) {
$option['value'] = $value->adaptation(); $option['value'] = $value->getBuild()->getQuery($value);
$option['class'] = ChildCondition::class; $option['class'] = ChildCondition::class;
} else { } else {
$option['class'] = DefaultCondition::class; $option['class'] = DefaultCondition::class;
@@ -94,7 +95,7 @@ class ArrayCondition extends Condition
* @param $value * @param $value
* @return string * @return string
*/ */
public function buildHashCondition($key, $value) public function buildHashCondition($key, $value): string
{ {
return $this->resolve($key, $value); return $this->resolve($key, $value);
} }
+1 -1
View File
@@ -15,7 +15,7 @@ class BetweenCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
return $this->column . ' BETWEEN ' . $this->value[0] . ' AND ' . $this->value[1]; return $this->column . ' BETWEEN ' . $this->value[0] . ' AND ' . $this->value[1];
} }
+1 -1
View File
@@ -14,7 +14,7 @@ class ChildCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
return $this->column . ' ' . $this->opera . ' (' . $this->value . ')'; return $this->column . ' ' . $this->opera . ' (' . $this->value . ')';
} }
+6 -5
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Database\Condition; namespace Database\Condition;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\BaseObject; use Snowflake\Abstracts\BaseObject;
use Snowflake\Core\Str; use Snowflake\Core\Str;
@@ -66,7 +67,7 @@ abstract class Condition extends BaseObject
* $query->ANDWhere('id', '=', 7); * $query->ANDWhere('id', '=', 7);
* $sql = '(((id=2 AND id=3 AND id<4) OR id=5) OR id=6) AND i(d=7)'; * $sql = '(((id=2 AND id=3 AND id<4) OR id=5) OR id=6) AND i(d=7)';
*/ */
protected function resolve($column, $value = null, $oprea = '=') protected function resolve($column, $value = null, $oprea = '='): string
{ {
if ($value === NULL) { if ($value === NULL) {
return ''; return '';
@@ -83,7 +84,7 @@ abstract class Condition extends BaseObject
$explode = explode('(', $columns); $explode = explode('(', $columns);
$explode = array_shift($explode); $explode = array_shift($explode);
if (strpos($explode, ' ') !== false) { if (str_contains($explode, ' ')) {
$explode = explode(' ', $explode)[0]; $explode = explode(' ', $explode)[0];
} }
if (!in_array(trim($explode), static::INT_TYPE)) { if (!in_array(trim($explode), static::INT_TYPE)) {
@@ -97,9 +98,9 @@ abstract class Condition extends BaseObject
/** /**
* @param array|null $param * @param array|null $param
* @return array * @return array|null
*/ */
protected function format(?array $param) protected function format(?array $param): ?array
{ {
if (!is_array($param)) { if (!is_array($param)) {
return null; return null;
@@ -126,7 +127,7 @@ abstract class Condition extends BaseObject
* @param string $oprea * @param string $oprea
* @return string * @return string
*/ */
public function typeBuilder($column, $value = null, $oprea = '=') #[Pure] public function typeBuilder($column, $value = null, $oprea = '='): string
{ {
if (is_numeric($value)) { if (is_numeric($value)) {
if ($value != (int)$value) { if ($value != (int)$value) {
+1 -1
View File
@@ -14,7 +14,7 @@ class DefaultCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
return $this->resolve($this->column, $this->value, $this->opera); return $this->resolve($this->column, $this->value, $this->opera);
} }
+1 -1
View File
@@ -12,7 +12,7 @@ class HashCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
$array = []; $array = [];
if (empty($this->value)) { if (empty($this->value)) {
+3 -2
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Database\Condition; namespace Database\Condition;
use Database\ActiveQuery; use Database\ActiveQuery;
use Exception;
/** /**
* Class InCondition * Class InCondition
@@ -15,9 +16,9 @@ class InCondition extends Condition
/** /**
* @return string * @return string
* @throws \Exception * @throws Exception
*/ */
public function builder() public function builder(): string
{ {
if ($this->value instanceof ActiveQuery) { if ($this->value instanceof ActiveQuery) {
$this->value = $this->value->getBuild()->getQuery($this->value); $this->value = $this->value->getBuild()->getQuery($this->value);
+1 -1
View File
@@ -17,7 +17,7 @@ class LLikeCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
if (!is_string($this->value)) { if (!is_string($this->value)) {
$this->value = array_shift($this->value); $this->value = array_shift($this->value);
+1 -1
View File
@@ -17,7 +17,7 @@ class LikeCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
if (!is_string($this->value)) { if (!is_string($this->value)) {
$this->value = array_shift($this->value); $this->value = array_shift($this->value);
+7 -7
View File
@@ -15,7 +15,7 @@ class MathematicsCondition extends Condition
/** /**
* @return mixed * @return mixed
*/ */
public function builder() public function builder(): mixed
{ {
return $this->{strtolower($this->type)}((float)$this->value); return $this->{strtolower($this->type)}((float)$this->value);
} }
@@ -24,7 +24,7 @@ class MathematicsCondition extends Condition
* @param $value * @param $value
* @return string * @return string
*/ */
public function eq($value) public function eq($value): string
{ {
return $this->column . ' = ' . $value; return $this->column . ' = ' . $value;
} }
@@ -33,7 +33,7 @@ class MathematicsCondition extends Condition
* @param $value * @param $value
* @return string * @return string
*/ */
public function neq($value) public function neq($value): string
{ {
return $this->column . ' <> ' . $value; return $this->column . ' <> ' . $value;
} }
@@ -42,7 +42,7 @@ class MathematicsCondition extends Condition
* @param $value * @param $value
* @return string * @return string
*/ */
public function gt($value) public function gt($value): string
{ {
return $this->column . ' > ' . $value; return $this->column . ' > ' . $value;
} }
@@ -51,7 +51,7 @@ class MathematicsCondition extends Condition
* @param $value * @param $value
* @return string * @return string
*/ */
public function egt($value) public function egt($value): string
{ {
return $this->column . ' >= ' . $value; return $this->column . ' >= ' . $value;
} }
@@ -61,7 +61,7 @@ class MathematicsCondition extends Condition
* @param $value * @param $value
* @return string * @return string
*/ */
public function lt($value) public function lt($value): string
{ {
return $this->column . ' < ' . $value; return $this->column . ' < ' . $value;
} }
@@ -70,7 +70,7 @@ class MathematicsCondition extends Condition
* @param $value * @param $value
* @return string * @return string
*/ */
public function elt($value) public function elt($value): string
{ {
return $this->column . ' <= ' . $value; return $this->column . ' <= ' . $value;
} }
+1 -1
View File
@@ -14,7 +14,7 @@ class NotBetweenCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
return $this->column . ' NOT BETWEEN ' . $this->value[0] . ' AND ' . $this->value[1]; return $this->column . ' NOT BETWEEN ' . $this->value[0] . ' AND ' . $this->value[1];
} }
+1 -1
View File
@@ -14,7 +14,7 @@ class NotInCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
$format = array_filter($this->format($this->value)); $format = array_filter($this->format($this->value));
+1 -1
View File
@@ -17,7 +17,7 @@ class NotLikeCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
if (!is_string($this->value)) { if (!is_string($this->value)) {
$this->value = array_shift($this->value); $this->value = array_shift($this->value);
+1 -1
View File
@@ -15,7 +15,7 @@ class OrCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
return 'OR ' . $this->resolve($this->column, $this->value, $this->opera); return 'OR ' . $this->resolve($this->column, $this->value, $this->opera);
} }
+1 -1
View File
@@ -17,7 +17,7 @@ class RLikeCondition extends Condition
/** /**
* @return string * @return string
*/ */
public function builder() public function builder(): string
{ {
if (!is_string($this->value)) { if (!is_string($this->value)) {
$this->value = array_shift($this->value); $this->value = array_shift($this->value);
+21 -17
View File
@@ -11,6 +11,8 @@ declare(strict_types=1);
namespace Database; namespace Database;
use JetBrains\PhpStorm\Pure;
use ReflectionException;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Database\Mysql\Schema; use Database\Mysql\Schema;
use Database\Orm\Select; use Database\Orm\Select;
@@ -18,6 +20,7 @@ use Exception;
use PDO; use PDO;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
/** /**
@@ -92,7 +95,7 @@ class Connection extends Component
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function getConnect($sql = NULL) public function getConnect($sql = NULL): PDO
{ {
$connections = Snowflake::app()->connections; $connections = Snowflake::app()->connections;
$connections->initConnections($this->cds, true, $this->maxNumber); $connections->initConnections($this->cds, true, $this->maxNumber);
@@ -119,7 +122,7 @@ class Connection extends Component
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
private function getPdo($sql) private function getPdo($sql): PDO
{ {
if ($this->isWrite($sql)) { if ($this->isWrite($sql)) {
$connect = $this->masterInstance(); $connect = $this->masterInstance();
@@ -130,10 +133,11 @@ class Connection extends Component
} }
/** /**
* @return mixed|object|Schema * @return mixed
* @throws Exception * @throws ReflectionException
* @throws NotFindClassException
*/ */
public function getSchema() public function getSchema(): mixed
{ {
if ($this->_schema === null) { if ($this->_schema === null) {
$this->_schema = Snowflake::createObject([ $this->_schema = Snowflake::createObject([
@@ -148,7 +152,7 @@ class Connection extends Component
* @param $sql * @param $sql
* @return bool * @return bool
*/ */
public function isWrite($sql) #[Pure] public function isWrite($sql): bool
{ {
if (empty($sql)) return false; if (empty($sql)) return false;
@@ -158,10 +162,10 @@ class Connection extends Component
} }
/** /**
* @return mixed|null * @return mixed
* @throws ComponentException * @throws ComponentException
*/ */
public function getCacheDriver() public function getCacheDriver(): mixed
{ {
if (!$this->enableCache) { if (!$this->enableCache) {
return null; return null;
@@ -173,7 +177,7 @@ class Connection extends Component
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function masterInstance() public function masterInstance(): PDO
{ {
$config = [ $config = [
'cds' => $this->cds, 'cds' => $this->cds,
@@ -188,7 +192,7 @@ class Connection extends Component
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function slaveInstance() public function slaveInstance(): PDO
{ {
if (empty($this->slaveConfig)) { if (empty($this->slaveConfig)) {
return $this->masterInstance(); return $this->masterInstance();
@@ -203,7 +207,7 @@ class Connection extends Component
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function beginTransaction() public function beginTransaction(): static
{ {
$connections = Snowflake::app()->connections; $connections = Snowflake::app()->connections;
$connections->beginTransaction($this->cds); $connections->beginTransaction($this->cds);
@@ -214,7 +218,7 @@ class Connection extends Component
* @return $this|bool * @return $this|bool
* @throws Exception * @throws Exception
*/ */
public function inTransaction() public function inTransaction(): bool|static
{ {
$connections = Snowflake::app()->connections; $connections = Snowflake::app()->connections;
return $connections->inTransaction($this->cds); return $connections->inTransaction($this->cds);
@@ -227,7 +231,7 @@ class Connection extends Component
public function rollback() public function rollback()
{ {
$connections = Snowflake::app()->connections; $connections = Snowflake::app()->connections;
return $connections->rollback($this->cds); $connections->rollback($this->cds);
} }
/** /**
@@ -237,7 +241,7 @@ class Connection extends Component
public function commit() public function commit()
{ {
$connections = Snowflake::app()->connections; $connections = Snowflake::app()->connections;
return $connections->commit($this->cds); $connections->commit($this->cds);
} }
/** /**
@@ -245,7 +249,7 @@ class Connection extends Component
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function refresh($sql) public function refresh($sql): PDO
{ {
if ($this->isWrite($sql)) { if ($this->isWrite($sql)) {
$instance = $this->masterInstance(); $instance = $this->masterInstance();
@@ -261,7 +265,7 @@ class Connection extends Component
* @return Command * @return Command
* @throws * @throws
*/ */
public function createCommand($sql = null, $attributes = []) 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);
@@ -271,7 +275,7 @@ class Connection extends Component
* @return Select * @return Select
* @throws Exception * @throws Exception
*/ */
public function getBuild() public function getBuild(): Select
{ {
return $this->getSchema()->getQueryBuilder(); return $this->getSchema()->getQueryBuilder();
} }
+3 -3
View File
@@ -35,7 +35,7 @@ class DatabasesProviders extends Providers
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function get($name) public function get($name): Connection
{ {
$application = Snowflake::app(); $application = Snowflake::app();
if ($application->has('databases.' . $name)) { if ($application->has('databases.' . $name)) {
@@ -87,10 +87,10 @@ class DatabasesProviders extends Providers
/** /**
* @param $name * @param $name
* @return array|mixed|null * @return mixed
* @throws ConfigException * @throws ConfigException
*/ */
public function getConfig($name) public function getConfig($name): mixed
{ {
return Config::get('databases.' . $name, true); return Config::get('databases.' . $name, true);
} }
+22 -22
View File
@@ -25,7 +25,7 @@ class Db
/** /**
* @return bool * @return bool
*/ */
public static function transactionsActive() public static function transactionsActive(): bool
{ {
return static::$isActive; return static::$isActive;
} }
@@ -65,7 +65,7 @@ class Db
* *
* @return static * @return static
*/ */
public static function table($table) public static function table($table): Db|static
{ {
$db = new Db(); $db = new Db();
$db->from($table); $db->from($table);
@@ -77,7 +77,7 @@ class Db
* @param string $alias * @param string $alias
* @return string * @return string
*/ */
public static function any_value(string $column, string $alias = '') public static function any_value(string $column, string $alias = ''): string
{ {
if (empty($alias)) { if (empty($alias)) {
$alias = $column . '_any_value'; $alias = $column . '_any_value';
@@ -90,7 +90,7 @@ class Db
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function get(Connection $db = NULL) public function get(Connection $db = NULL): mixed
{ {
if (empty($db)) { if (empty($db)) {
$db = Snowflake::app()->database; $db = Snowflake::app()->database;
@@ -104,17 +104,17 @@ class Db
* @param $column * @param $column
* @return string * @return string
*/ */
public static function raw($column) public static function raw($column): string
{ {
return '`' . $column . '`'; return '`' . $column . '`';
} }
/** /**
* @param Connection|null $db * @param Connection|null $db
* @return array|mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function find(Connection $db = NULL) public function find(Connection $db = NULL): mixed
{ {
if (empty($db)) { if (empty($db)) {
$db = Snowflake::app()->database; $db = Snowflake::app()->database;
@@ -129,7 +129,7 @@ class Db
* @return bool|int * @return bool|int
* @throws Exception * @throws Exception
*/ */
public function count(Connection $db = NULL) public function count(Connection $db = NULL): bool|int
{ {
if (empty($db)) { if (empty($db)) {
$db = Snowflake::app()->database; $db = Snowflake::app()->database;
@@ -144,7 +144,7 @@ class Db
* @return bool|int * @return bool|int
* @throws Exception * @throws Exception
*/ */
public function exists(Connection $db = NULL) public function exists(Connection $db = NULL): bool|int
{ {
if (empty($db)) { if (empty($db)) {
$db = Snowflake::app()->database; $db = Snowflake::app()->database;
@@ -161,7 +161,7 @@ class Db
* @return array|bool|int|string|null * @return array|bool|int|string|null
* @throws Exception * @throws Exception
*/ */
public static function findAllBySql(string $sql, array $attributes = [], Connection $db = NULL) public static function findAllBySql(string $sql, array $attributes = [], Connection $db = NULL): int|bool|array|string|null
{ {
return $db->createCommand($sql, $attributes)->all(); return $db->createCommand($sql, $attributes)->all();
} }
@@ -173,7 +173,7 @@ class Db
* @return array|mixed * @return array|mixed
* @throws Exception * @throws Exception
*/ */
public static function findBySql(string $sql, array $attributes = [], Connection $db = NULL) public static function findBySql(string $sql, array $attributes = [], Connection $db = NULL): mixed
{ {
return $db->createCommand($sql, $attributes)->one(); return $db->createCommand($sql, $attributes)->one();
} }
@@ -183,7 +183,7 @@ class Db
* @return array|null * @return array|null
* @throws Exception * @throws Exception
*/ */
public function values(string $field) public function values(string $field): ?array
{ {
$data = $this->get(); $data = $this->get();
if (empty($data) || empty($field)) { if (empty($data) || empty($field)) {
@@ -198,10 +198,10 @@ class Db
/** /**
* @param $field * @param $field
* @return array|mixed|null * @return mixed
* @throws Exception * @throws Exception
*/ */
public function value($field) public function value($field): mixed
{ {
$data = $this->find(); $data = $this->find();
if (!empty($field) && isset($data[$field])) { if (!empty($field) && isset($data[$field])) {
@@ -215,7 +215,7 @@ class Db
* @return bool|int * @return bool|int
* @throws Exception * @throws Exception
*/ */
public function delete($db = null) public function delete($db = null): bool|int
{ {
if (empty($db)) { if (empty($db)) {
$db = Snowflake::app()->database; $db = Snowflake::app()->database;
@@ -232,7 +232,7 @@ class Db
* @return bool|int * @return bool|int
* @throws Exception * @throws Exception
*/ */
public static function drop($table, $db = null) public static function drop($table, $db = null): bool|int
{ {
if (empty($db)) { if (empty($db)) {
$db = Snowflake::app()->database; $db = Snowflake::app()->database;
@@ -246,7 +246,7 @@ class Db
* @return bool|int * @return bool|int
* @throws Exception * @throws Exception
*/ */
public static function truncate($table, $db = null) public static function truncate($table, $db = null): bool|int
{ {
if (empty($db)) { if (empty($db)) {
@@ -259,10 +259,10 @@ class Db
/** /**
* @param $table * @param $table
* @param Connection|NULL $db * @param Connection|NULL $db
* @return array|mixed|null * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function showCreateSql($table, Connection $db = NULL) public static function showCreateSql($table, Connection $db = NULL): mixed
{ {
if (empty($db)) { if (empty($db)) {
@@ -283,7 +283,7 @@ class Db
* @return bool|int|null * @return bool|int|null
* @throws Exception * @throws Exception
*/ */
public static function desc($table, Connection $db = NULL) public static function desc($table, Connection $db = NULL): bool|int|null
{ {
if (empty($db)) { if (empty($db)) {
$db = Snowflake::app()->database; $db = Snowflake::app()->database;
@@ -300,10 +300,10 @@ class Db
/** /**
* @param string $table * @param string $table
* @param Connection|NULL $db * @param Connection|NULL $db
* @return array|mixed|null * @return mixed
* @throws Exception * @throws Exception
*/ */
public static function show(string $table, Connection $db = NULL) public static function show(string $table, Connection $db = NULL): mixed
{ {
if (empty($table)) { if (empty($table)) {
return null; return null;
+3 -6
View File
@@ -21,15 +21,13 @@ abstract class HasBase
{ {
/** @var ActiveRecord|Collection */ /** @var ActiveRecord|Collection */
protected $data; protected Collection|ActiveRecord $data;
/** /**
* @var IOrm * @var IOrm
*/ */
protected IOrm $model; protected IOrm $model;
/** @var */
protected $primaryId;
/** @var array */ /** @var array */
protected array $value = []; protected array $value = [];
@@ -46,7 +44,7 @@ abstract class HasBase
* @param Relation $relation * @param Relation $relation
* @throws Exception * @throws Exception
*/ */
public function __construct(IOrm $model, $primaryId, $value, Relation $relation) public function __construct(mixed $model, $primaryId, $value, Relation $relation)
{ {
if (!class_exists($model)) { if (!class_exists($model)) {
throw new Exception('Model must implement ' . ActiveRecord::class); throw new Exception('Model must implement ' . ActiveRecord::class);
@@ -64,7 +62,6 @@ abstract class HasBase
$this->_relation = $relation->bindIdentification($model, $_model); $this->_relation = $relation->bindIdentification($model, $_model);
$this->model = $model; $this->model = $model;
$this->primaryId = $primaryId;
$this->value = $value; $this->value = $value;
} }
@@ -74,7 +71,7 @@ abstract class HasBase
* @param $name * @param $name
* @return mixed * @return mixed
*/ */
public function __get($name) public function __get($name): mixed
{ {
if (empty($this->value)) { if (empty($this->value)) {
return null; return null;
+2 -2
View File
@@ -18,7 +18,7 @@ class HasCount extends HasBase
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function __call($name, $arguments) public function __call($name, $arguments): static
{ {
$this->_relation->getQuery($this->model::className())->$name(...$arguments); $this->_relation->getQuery($this->model::className())->$name(...$arguments);
return $this; return $this;
@@ -28,7 +28,7 @@ class HasCount extends HasBase
* @return array|null|ActiveRecord * @return array|null|ActiveRecord
* @throws Exception * @throws Exception
*/ */
public function get() public function get(): array|ActiveRecord|null
{ {
return $this->_relation->count($this->model::className(), $this->value); return $this->_relation->count($this->model::className(), $this->value);
} }
+3 -3
View File
@@ -22,10 +22,10 @@ class HasMany extends HasBase
/** /**
* @param $name * @param $name
* @param $arguments * @param $arguments
* @return mixed * @return static
* @throws Exception * @throws Exception
*/ */
public function __call($name, $arguments) public function __call($name, $arguments): static
{ {
$this->_relation->getQuery($this->model::className())->$name(...$arguments); $this->_relation->getQuery($this->model::className())->$name(...$arguments);
return $this; return $this;
@@ -35,7 +35,7 @@ class HasMany extends HasBase
* @return array|null|ActiveRecord * @return array|null|ActiveRecord
* @throws Exception * @throws Exception
*/ */
public function get() public function get(): array|ActiveRecord|null
{ {
return $this->_relation->get($this->model::className(), $this->value); return $this->_relation->get($this->model::className(), $this->value);
} }
+2 -2
View File
@@ -24,7 +24,7 @@ class HasOne extends HasBase
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function __call($name, $arguments) public function __call($name, $arguments): static
{ {
$this->_relation->getQuery($this->model::className())->$name(...$arguments); $this->_relation->getQuery($this->model::className())->$name(...$arguments);
return $this; return $this;
@@ -34,7 +34,7 @@ class HasOne extends HasBase
* @return array|null|ActiveRecord * @return array|null|ActiveRecord
* @throws Exception * @throws Exception
*/ */
public function get() public function get(): array|ActiveRecord|null
{ {
return $this->_relation->first($this->model::className(), $this->value); return $this->_relation->first($this->model::className(), $this->value);
} }
+4 -4
View File
@@ -21,27 +21,27 @@ interface IOrm
* @param null $db * @param null $db
* @return ActiveRecord * @return ActiveRecord
*/ */
public static function findOne($param, $db = NULL); public static function findOne($param, $db = NULL): static;
/** /**
* @return string * @return string
*/ */
public static function className(); public static function className(): string;
/** /**
* @return ActiveQuery * @return ActiveQuery
* return a sql queryBuilder * return a sql queryBuilder
*/ */
public static function find(); public static function find(): ActiveQuery;
/** /**
* @param $dbName * @param $dbName
* @return Connection * @return Connection
*/ */
public static function setDatabaseConnect($dbName); public static function setDatabaseConnect($dbName): Connection;
// public static function deleteAll($condition, $attributes); // public static function deleteAll($condition, $attributes);
+37 -37
View File
@@ -11,6 +11,7 @@ declare(strict_types=1);
namespace Database\Mysql; namespace Database\Mysql;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Database\Connection; use Database\Connection;
use Exception; use Exception;
@@ -58,7 +59,7 @@ class Columns extends Component
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function table(string $table) public function table(string $table): static
{ {
$this->structure($this->table = $table); $this->structure($this->table = $table);
return $this; return $this;
@@ -67,7 +68,7 @@ class Columns extends Component
/** /**
* @return string * @return string
*/ */
public function getTable() public function getTable(): string
{ {
return $this->table; return $this->table;
} }
@@ -75,10 +76,10 @@ class Columns extends Component
/** /**
* @param $key * @param $key
* @param $val * @param $val
* @return float|int|mixed|string * @return mixed
* @throws Exception * @throws Exception
*/ */
public function fieldFormat($key, $val) public function fieldFormat($key, $val): mixed
{ {
return $this->encode($val, $this->get_fields($key)); return $this->encode($val, $this->get_fields($key));
} }
@@ -88,7 +89,7 @@ class Columns extends Component
* @return array * @return array
* @throws * @throws
*/ */
public function populate($data) public function populate($data): array
{ {
$column = $this->get_fields(); $column = $this->get_fields();
foreach ($data as $key => $val) { foreach ($data as $key => $val) {
@@ -102,11 +103,10 @@ class Columns extends Component
/** /**
* @param $val * @param $val
* @param $format * @param null $format
* @return float|int|mixed|string * @return mixed
* @throws
*/ */
public function decode($val, $format = null) public function decode($val, $format = null): mixed
{ {
if (empty($format)) { if (empty($format)) {
return $val; return $val;
@@ -125,12 +125,12 @@ class Columns extends Component
/** /**
* @param $name * @param string $name
* @param $value * @param $value
* @return float|int|mixed|string * @return mixed
* @throws Exception * @throws Exception
*/ */
public function _decode(string $name, $value) public function _decode(string $name, $value): mixed
{ {
return $this->decode($value, $this->get_fields($name)); return $this->decode($value, $this->get_fields($name));
} }
@@ -138,11 +138,11 @@ class Columns extends Component
/** /**
* @param $val * @param $val
* @param $format * @param null $format
* @return float|int|mixed|string * @return mixed
* @throws * @throws Exception
*/ */
public function encode($val, $format = null) public function encode($val, $format = null): mixed
{ {
if (empty($format)) { if (empty($format)) {
return $val; return $val;
@@ -163,7 +163,7 @@ class Columns extends Component
* @param $format * @param $format
* @return bool * @return bool
*/ */
public function isInt($format) #[Pure] public function isInt($format): bool
{ {
return in_array($format, ['int', 'bigint', 'tinyint', 'smallint', 'mediumint']); return in_array($format, ['int', 'bigint', 'tinyint', 'smallint', 'mediumint']);
} }
@@ -172,7 +172,7 @@ class Columns extends Component
* @param $format * @param $format
* @return bool * @return bool
*/ */
public function isFloat($format) #[Pure] public function isFloat($format): bool
{ {
return in_array($format, ['float', 'double', 'decimal']); return in_array($format, ['float', 'double', 'decimal']);
} }
@@ -181,7 +181,7 @@ class Columns extends Component
* @param $format * @param $format
* @return bool * @return bool
*/ */
public function isJson($format) #[Pure] public function isJson($format): bool
{ {
return in_array($format, ['json']); return in_array($format, ['json']);
} }
@@ -190,7 +190,7 @@ class Columns extends Component
* @param $format * @param $format
* @return bool * @return bool
*/ */
public function isString($format) #[Pure] public function isString($format): bool
{ {
return in_array($format, ['varchar', 'char', 'text', 'longtext', 'tinytext', 'mediumtext']); return in_array($format, ['varchar', 'char', 'text', 'longtext', 'tinytext', 'mediumtext']);
} }
@@ -200,7 +200,7 @@ class Columns extends Component
* @return array * @return array
* @throws * @throws
*/ */
public function format() public function format(): array
{ {
return $this->columns('Default', 'Field'); return $this->columns('Default', 'Field');
} }
@@ -209,7 +209,7 @@ class Columns extends Component
* @return int|string|null * @return int|string|null
* @throws Exception * @throws Exception
*/ */
public function getAutoIncrement() public function getAutoIncrement(): int|string|null
{ {
return $this->_auto_increment[$this->table] ?? null; return $this->_auto_increment[$this->table] ?? null;
} }
@@ -219,7 +219,7 @@ class Columns extends Component
* *
* @throws Exception * @throws Exception
*/ */
public function getPrimaryKeys() public function getPrimaryKeys(): array|string|null
{ {
if (isset($this->_auto_increment[$this->table])) { if (isset($this->_auto_increment[$this->table])) {
return $this->_auto_increment[$this->table]; return $this->_auto_increment[$this->table];
@@ -232,7 +232,7 @@ class Columns extends Component
* *
* @throws Exception * @throws Exception
*/ */
public function getFirstPrimary() #[Pure] public function getFirstPrimary(): array|string|null
{ {
if (isset($this->_auto_increment[$this->table])) { if (isset($this->_auto_increment[$this->table])) {
return $this->_auto_increment[$this->table]; return $this->_auto_increment[$this->table];
@@ -249,7 +249,7 @@ class Columns extends Component
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
private function columns($name, $index = null) private function columns($name, $index = null): array
{ {
if (empty($index)) { if (empty($index)) {
return array_column($this->getColumns(), $name); return array_column($this->getColumns(), $name);
@@ -259,10 +259,10 @@ class Columns extends Component
} }
/** /**
* @return array|bool|int|mixed|string * @return array|static
* @throws Exception * @throws Exception
*/ */
private function getColumns() private function getColumns(): array|static
{ {
return $this->structure($this->getTable()); return $this->structure($this->getTable());
} }
@@ -270,10 +270,10 @@ class Columns extends Component
/** /**
* @param $table * @param $table
* @return $this * @return array|Columns
* @throws Exception * @throws Exception
*/ */
private function structure($table) private function structure($table): array|static
{ {
if (!isset($this->columns[$table]) || empty($this->columns[$table])) { if (!isset($this->columns[$table]) || empty($this->columns[$table])) {
$sql = $this->db->getBuild()->getColumn($table); $sql = $this->db->getBuild()->getColumn($table);
@@ -291,9 +291,9 @@ class Columns extends Component
/** /**
* @param $column * @param $column
* @param $table * @param $table
* @return mixed * @return array
*/ */
private function resolve(array $column, $table) private function resolve(array $column, $table): array
{ {
foreach ($column as $key => $item) { foreach ($column as $key => $item) {
$this->addPrimary($item, $table); $this->addPrimary($item, $table);
@@ -335,24 +335,24 @@ class Columns extends Component
* @param $type * @param $type
* @return string * @return string
*/ */
private function clean($type) private function clean($type): string
{ {
if (strpos($type, ')') === false) { if (!str_contains($type, ')')) {
return $type; return $type;
} }
$replace = preg_replace('/\(\d+(,\d+)?\)(\s+\w+)*/', '', $type); $replace = preg_replace('/\(\d+(,\d+)?\)(\s+\w+)*/', '', $type);
if (strpos(' ', $replace) !== FALSE) { if (str_contains(' ', $replace)) {
$replace = explode(' ', $replace)[1]; $replace = explode(' ', $replace)[1];
} }
return $replace; return $replace;
} }
/** /**
* @param $field * @param null $field
* @return array|string * @return array|string|null
* @throws Exception * @throws Exception
*/ */
public function get_fields($field = null) public function get_fields($field = null): array|string|null
{ {
$fields = $this->columns('Type', 'Field'); $fields = $this->columns('Type', 'Field');
if (empty($field)) { if (empty($field)) {
+6 -6
View File
@@ -28,9 +28,9 @@ class Schema extends Component
private ?Change $_change = null; private ?Change $_change = null;
/** /**
* @return Select * @return Select|null
*/ */
public function getQueryBuilder() public function getQueryBuilder(): ?Select
{ {
if ($this->_builder === null) { if ($this->_builder === null) {
$this->_builder = new Select(); $this->_builder = new Select();
@@ -39,9 +39,9 @@ class Schema extends Component
} }
/** /**
* @return Change * @return Change|null
*/ */
public function getChange() public function getChange(): ?Change
{ {
if ($this->_change === null) { if ($this->_change === null) {
$this->_change = new Change(); $this->_change = new Change();
@@ -51,9 +51,9 @@ class Schema extends Component
/** /**
* @return Columns * @return Columns|null
*/ */
public function getColumns() public function getColumns(): ?Columns
{ {
if ($this->_column === null) { if ($this->_column === null) {
$this->_column = new Columns(['db' => $this->db]); $this->_column = new Columns(['db' => $this->db]);
+13 -12
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Database\Orm; namespace Database\Orm;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\BaseObject; use Snowflake\Abstracts\BaseObject;
use Database\ActiveQuery; use Database\ActiveQuery;
use Exception; use Exception;
@@ -26,7 +27,7 @@ class Change extends BaseObject
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function update(string $model, $attributes, $condition, &$params) public function update(string $model, $attributes, $condition, &$params): string
{ {
if (empty($params)) { if (empty($params)) {
throw new Exception("Not has update values."); throw new Exception("Not has update values.");
@@ -55,7 +56,7 @@ class Change extends BaseObject
* @return array|string * @return array|string
* @throws * @throws
*/ */
public function batchUpdate(string $table, array $attributes, $condition) public function batchUpdate(string $table, array $attributes, $condition): array|string
{ {
$param = []; $param = [];
$_attributes = []; $_attributes = [];
@@ -83,7 +84,7 @@ class Change extends BaseObject
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function mathematics($table, $params, $condition) public function mathematics($table, $params, $condition): string
{ {
$_tmp = $newParam = []; $_tmp = $newParam = [];
if (isset($params['incr']) && is_array($params['incr'])) { if (isset($params['incr']) && is_array($params['incr'])) {
@@ -109,7 +110,7 @@ class Change extends BaseObject
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
private function assemble($params, $op, array $_tmp) private function assemble($params, $op, array $_tmp): array
{ {
$message = 'Incr And Decr action. The value must a numeric.'; $message = 'Incr And Decr action. The value must a numeric.';
foreach ($params as $key => $val) { foreach ($params as $key => $val) {
@@ -127,7 +128,7 @@ class Change extends BaseObject
* @param array $params * @param array $params
* @return string * @return string
*/ */
public function insertOrUpdateByDUPLICATE($table, array $params) public function insertOrUpdateByDUPLICATE($table, array $params): string
{ {
$keys = implode(',', array_keys($params)); $keys = implode(',', array_keys($params));
@@ -153,14 +154,14 @@ class Change extends BaseObject
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function insert($table, $attributes, array $params = NULL) public function insert($table, $attributes, array $params = NULL): string
{ {
$sql = $this->inserts($table, implode(',', $attributes), '(:' . implode(',:', $attributes) . ')'); $sql = $this->inserts($table, implode(',', $attributes), '(:' . implode(',:', $attributes) . ')');
if (empty($params)) { if (empty($params)) {
throw new Exception("save data param not find."); throw new Exception("save data param not find.");
} }
foreach ($params as $key => $val) { foreach ($params as $key => $val) {
if (strpos($sql, ':' . $key) === FALSE) { if (!str_contains($sql, ':' . $key)) {
throw new Exception("save $key data param not find."); throw new Exception("save $key data param not find.");
} }
} }
@@ -175,7 +176,7 @@ class Change extends BaseObject
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function batchInsert($table, $attributes, array $params = NULL) public function batchInsert($table, $attributes, array $params = NULL): array
{ {
if (empty($params)) { if (empty($params)) {
throw new Exception("save data param not find."); throw new Exception("save data param not find.");
@@ -205,7 +206,7 @@ class Change extends BaseObject
* @return string * @return string
* 构建SQL语句 * 构建SQL语句
*/ */
private function inserts($table, $fields, $data) #[Pure] private function inserts($table, $fields, $data): string
{ {
$query = [ $query = [
'INSERT IGNORE INTO', '%s', '(%s)', 'VALUES %s' 'INSERT IGNORE INTO', '%s', '(%s)', 'VALUES %s'
@@ -223,7 +224,7 @@ class Change extends BaseObject
* @return bool|string * @return bool|string
* @throws Exception * @throws Exception
*/ */
public function updateAll($table, $attributes, $condition) public function updateAll($table, $attributes, $condition): bool|string
{ {
$param = []; $param = [];
foreach ($attributes as $key => $val) { foreach ($attributes as $key => $val) {
@@ -247,7 +248,7 @@ class Change extends BaseObject
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function delete(ActiveQuery $query) public function delete(ActiveQuery $query): string
{ {
if (empty($query->from)) { if (empty($query->from)) {
$query->from = $query->getTable(); $query->from = $query->getTable();
@@ -266,7 +267,7 @@ class Change extends BaseObject
* @param string $tableName * @param string $tableName
* @return string * @return string
*/ */
public function truncate(string $tableName) public function truncate(string $tableName): string
{ {
return 'TRUNCATE ' . $tableName; return 'TRUNCATE ' . $tableName;
} }
+20 -15
View File
@@ -3,8 +3,11 @@ declare(strict_types=1);
namespace Database\Orm; namespace Database\Orm;
use JetBrains\PhpStorm\Pure;
use ReflectionException;
use Snowflake\Core\JSON; use Snowflake\Core\JSON;
use Snowflake\Core\Str; use Snowflake\Core\Str;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Database\ActiveQuery; use Database\ActiveQuery;
use Database\Base\ConditionClassMap; use Database\Base\ConditionClassMap;
@@ -26,7 +29,7 @@ trait Condition
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function getWhere($query) public function getWhere($query): string
{ {
return $this->builderWhere($query); return $this->builderWhere($query);
} }
@@ -36,7 +39,7 @@ trait Condition
* @param $alias * @param $alias
* @return string * @return string
*/ */
private function builderAlias($alias) private function builderAlias($alias): string
{ {
return " AS " . $alias; return " AS " . $alias;
} }
@@ -46,7 +49,7 @@ trait Condition
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function builderFrom($table) private function builderFrom($table): string
{ {
if ($table instanceof ActiveQuery) { if ($table instanceof ActiveQuery) {
$table = '(' . $table->getBuild()->getQuery($table) . ')'; $table = '(' . $table->getBuild()->getQuery($table) . ')';
@@ -58,7 +61,7 @@ trait Condition
* @param $join * @param $join
* @return string * @return string
*/ */
private function builderJoin($join) #[Pure] private function builderJoin($join): string
{ {
if (!empty($join)) { if (!empty($join)) {
return ' ' . implode(' ', $join); return ' ' . implode(' ', $join);
@@ -71,7 +74,7 @@ trait Condition
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function builderWhere($where) private function builderWhere($where): string
{ {
if (empty($where)) { if (empty($where)) {
return ''; return '';
@@ -101,10 +104,11 @@ trait Condition
/** /**
* @param $value * @param $value
* @return mixed|object|string|null * @return mixed
* @throws Exception * @throws ReflectionException
* @throws NotFindClassException
*/ */
private function arrayMap($value) private function arrayMap($value): mixed
{ {
$classMap = ConditionClassMap::$conditionMap; $classMap = ConditionClassMap::$conditionMap;
if (isset($value[0])) { if (isset($value[0])) {
@@ -125,10 +129,11 @@ trait Condition
/** /**
* @param $value * @param $value
* @return mixed|object * @return mixed
* @throws Exception * @throws NotFindClassException
* @throws ReflectionException
*/ */
private function classMap($value) private function classMap($value): mixed
{ {
[$option['opera'], $option['column'], $option['value']] = $value; [$option['opera'], $option['column'], $option['value']] = $value;
@@ -146,7 +151,7 @@ trait Condition
* @param $group * @param $group
* @return string * @return string
*/ */
private function builderGroup($group) private function builderGroup($group): string
{ {
if (empty($group)) { if (empty($group)) {
return ''; return '';
@@ -158,7 +163,7 @@ trait Condition
* @param $order * @param $order
* @return string * @return string
*/ */
private function builderOrder($order) private function builderOrder($order): string
{ {
if (!empty($order)) { if (!empty($order)) {
return ' ORDER BY ' . implode(',', $order); return ' ORDER BY ' . implode(',', $order);
@@ -171,7 +176,7 @@ trait Condition
* @param ActiveQuery $query * @param ActiveQuery $query
* @return string * @return string
*/ */
private function builderLimit(ActiveQuery $query) private function builderLimit(ActiveQuery $query): string
{ {
$limit = $query->limit; $limit = $query->limit;
if (!is_numeric($limit) || $limit < 1) { if (!is_numeric($limit) || $limit < 1) {
@@ -192,7 +197,7 @@ trait Condition
* @param bool $isSearch * @param bool $isSearch
* @return int|string * @return int|string
*/ */
public function valueEncode($value, $isSearch = false) public function valueEncode($value, $isSearch = false): int|string
{ {
if ($isSearch) { if ($isSearch) {
return $value; return $value;
+7 -6
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Database\Orm; namespace Database\Orm;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\BaseObject; use Snowflake\Abstracts\BaseObject;
use Database\ActiveQuery; use Database\ActiveQuery;
use Database\Sql; use Database\Sql;
@@ -24,17 +25,17 @@ class Select extends BaseObject
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function getQuery($query) public function getQuery(ActiveQuery|Sql|Db $query): string
{ {
return $this->generate($query, false); return $this->generate($query, false);
} }
/** /**
* @param ActiveQuery|Db|mixed $query * @param ActiveQuery|Db|Sql $query
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function count($query) public function count(ActiveQuery|Db|Sql $query): string
{ {
return $this->generate($query, true); return $this->generate($query, true);
} }
@@ -45,7 +46,7 @@ class Select extends BaseObject
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function generate($query, $isCount = false) private function generate(ActiveQuery|Db|Sql $query, $isCount = false): string
{ {
if (empty($query->from)) { if (empty($query->from)) {
$query->from = $query->getTable(); $query->from = $query->getTable();
@@ -78,7 +79,7 @@ class Select extends BaseObject
* @param bool $isCount * @param bool $isCount
* @return string * @return string
*/ */
private function builderSelect($select = NULL, $isCount = false) #[Pure] private function builderSelect($select = NULL, $isCount = false): string
{ {
if ($isCount === true) { if ($isCount === true) {
return 'SELECT COUNT(*)'; return 'SELECT COUNT(*)';
@@ -97,7 +98,7 @@ class Select extends BaseObject
* @param $table * @param $table
* @return string * @return string
*/ */
public function getColumn($table) public function getColumn($table): string
{ {
return 'SHOW FULL FIELDS FROM ' . $table; return 'SHOW FULL FIELDS FROM ' . $table;
} }
+10 -10
View File
@@ -52,10 +52,10 @@ class Pagination extends Component
/** /**
* @param Closure|array $callback * @param array|Closure $callback
* @throws Exception * @throws Exception
*/ */
public function setCallback($callback) public function setCallback(array|Closure $callback)
{ {
if (!is_callable($callback, true)) { if (!is_callable($callback, true)) {
throw new Exception('非法回调函数~'); throw new Exception('非法回调函数~');
@@ -68,7 +68,7 @@ class Pagination extends Component
* @param int $number * @param int $number
* @return Pagination * @return Pagination
*/ */
public function setOffset(int $number) public function setOffset(int $number): static
{ {
if ($number < 0) { if ($number < 0) {
$number = 0; $number = 0;
@@ -82,7 +82,7 @@ class Pagination extends Component
* @param int $number * @param int $number
* @return Pagination * @return Pagination
*/ */
public function setLimit(int $number) public function setLimit(int $number): static
{ {
if ($number < 1) { if ($number < 1) {
$number = 100; $number = 100;
@@ -96,9 +96,9 @@ class Pagination extends Component
/** /**
* @param int $number * @param int $number
* @return Pagination|void * @return Pagination
*/ */
public function setMax(int $number) public function setMax(int $number): static
{ {
if ($number < 0) { if ($number < 0) {
return $this; return $this;
@@ -125,7 +125,7 @@ class Pagination extends Component
* @param $param * @param $param
* @return array * @return array
*/ */
public function loop($param) 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();
@@ -145,7 +145,7 @@ class Pagination extends Component
/** /**
* @return array * @return array
*/ */
public function output() public function output(): array
{ {
return []; return [];
} }
@@ -172,7 +172,7 @@ class Pagination extends Component
* 解释器 * 解释器
* @return mixed * @return mixed
*/ */
private function executed($callback, $data, $param) private function executed($callback, $data, $param): mixed
{ {
$this->_group->add(1); $this->_group->add(1);
return Coroutine::create(function ($callback, $data, $param): void { return Coroutine::create(function ($callback, $data, $param): void {
@@ -192,7 +192,7 @@ class Pagination extends Component
/** /**
* @return array|Collection * @return array|Collection
*/ */
private function get() 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;
+13 -14
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Database; namespace Database;
use Exception;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
/** /**
@@ -23,7 +24,7 @@ class Relation extends Component
* @param ActiveQuery $query * @param ActiveQuery $query
* @return $this * @return $this
*/ */
public function bindIdentification(string $identification, ActiveQuery $query) public function bindIdentification(string $identification, ActiveQuery $query): static
{ {
$this->_query[$identification] = $query; $this->_query[$identification] = $query;
return $this; return $this;
@@ -33,19 +34,18 @@ class Relation extends Component
* @param $name * @param $name
* @return ActiveQuery|null * @return ActiveQuery|null
*/ */
public function getQuery(string $name) public function getQuery(string $name): ?ActiveQuery
{ {
return $this->_query[$name] ?? null; return $this->_query[$name] ?? null;
} }
/** /**
* @param $identification * @param string $identification
* @param $localValue * @param $localValue
* @return ActiveRecord|mixed * @return mixed
* @throws
*/ */
public function first(string $identification, $localValue) public function first(string $identification, $localValue): mixed
{ {
$_identification = $identification . '_first_' . $localValue; $_identification = $identification . '_first_' . $localValue;
if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) { if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) {
@@ -62,12 +62,12 @@ class Relation extends Component
/** /**
* @param $identification * @param string $identification
* @param $localValue * @param $localValue
* @return ActiveRecord|mixed * @return mixed
* @throws * @throws Exception
*/ */
public function count(string $identification, $localValue) public function count(string $identification, $localValue): mixed
{ {
$_identification = $identification . '_count_' . $localValue; $_identification = $identification . '_count_' . $localValue;
if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) { if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) {
@@ -84,12 +84,11 @@ class Relation extends Component
/** /**
* @param $identification * @param string $identification
* @param $localValue * @param $localValue
* @return array|Collection|mixed|null * @return mixed
* @throws
*/ */
public function get(string $identification, $localValue) public function get(string $identification, $localValue): mixed
{ {
if (is_array($localValue)) { if (is_array($localValue)) {
$_identification = $identification . '_get_' . implode('_', $localValue); $_identification = $identification . '_get_' . implode('_', $localValue);
+3 -2
View File
@@ -11,6 +11,7 @@ namespace Database;
use Database\Orm\Select; use Database\Orm\Select;
use Database\Traits\QueryTrait; use Database\Traits\QueryTrait;
use Exception;
/** /**
* Class Sql * Class Sql
@@ -23,9 +24,9 @@ class Sql
/** /**
* @return string * @return string
* @throws \Exception * @throws Exception
*/ */
public function getSql() public function getSql(): string
{ {
return (new Select())->getQuery($this); return (new Select())->getQuery($this);
} }
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -27,7 +27,7 @@ class Command extends \Console\Command
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function onHandler(Input $dtl) public function onHandler(Input $dtl): array
{ {
/** @var Gii $gii */ /** @var Gii $gii */
$gii = Snowflake::app()->get('gii'); $gii = Snowflake::app()->get('gii');
+18 -20
View File
@@ -12,6 +12,8 @@ namespace Gii;
use Database\Connection; use Database\Connection;
use Database\Db; use Database\Db;
use Exception; use Exception;
use JetBrains\PhpStorm\ArrayShape;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Input; use Snowflake\Abstracts\Input;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException; use Snowflake\Exception\ConfigException;
@@ -52,7 +54,7 @@ class Gii
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function run(?Connection $db, $input) public function run(?Connection $db, $input): array
{ {
$this->input = $input; $this->input = $input;
if (!empty($db)) $this->db = $db; if (!empty($db)) $this->db = $db;
@@ -90,8 +92,9 @@ class Gii
* @return array * @return array
* @throws ComponentException * @throws ComponentException
* @throws ConfigException * @throws ConfigException
* @throws Exception
*/ */
private function getModel($make, $input) private function getModel($make, $input): array
{ {
if (!$this->db) { if (!$this->db) {
$db = $this->input->get('databases', 'db'); $db = $this->input->get('databases', 'db');
@@ -120,7 +123,7 @@ class Gii
* *
* @throws Exception * @throws Exception
*/ */
private function getTable($controller, $model) private function getTable($controller, $model): array
{ {
$tables = $this->getFields($this->getTables()); $tables = $this->getFields($this->getTables());
if (empty($tables)) { if (empty($tables)) {
@@ -145,7 +148,7 @@ class Gii
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function generateModel(array $data) private function generateModel(array $data): string
{ {
$controller = new GiiModel($data['classFileName'], $data['tableName'], $data['visible'], $data['res'], $data['fields']); $controller = new GiiModel($data['classFileName'], $data['tableName'], $data['visible'], $data['res'], $data['fields']);
$controller->setConnection($this->db); $controller->setConnection($this->db);
@@ -163,7 +166,7 @@ class Gii
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function generateController(array $data) private function generateController(array $data): string
{ {
$controller = new GiiController($data['classFileName'], $data['fields']); $controller = new GiiController($data['classFileName'], $data['fields']);
$controller->setConnection($this->db); $controller->setConnection($this->db);
@@ -177,10 +180,10 @@ class Gii
} }
/** /**
* @return array|null * @return array|string|null
* @throws Exception * @throws Exception
*/ */
private function getTables() private function getTables(): array|string|null
{ {
if (empty($this->tableName)) { if (empty($this->tableName)) {
return $this->showAll(); return $this->showAll();
@@ -199,7 +202,7 @@ class Gii
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
private function showAll() private function showAll(): array
{ {
$res = []; $res = [];
$_tables = Db::findAllBySql('show tables', [], $this->db); $_tables = Db::findAllBySql('show tables', [], $this->db);
@@ -214,10 +217,10 @@ class Gii
/** /**
* @param $table * @param $table
* @return bool|int * @return bool|int|null
* @throws Exception * @throws Exception
*/ */
private function getIndex($table) private function getIndex($table): bool|int|null
{ {
$data = Db::findAllBySql('SHOW INDEX FROM ' . $table, [], $this->db); $data = Db::findAllBySql('SHOW INDEX FROM ' . $table, [], $this->db);
@@ -230,7 +233,7 @@ class Gii
* @return array * @return array
* @throws * @throws
*/ */
private function getFields($tables) private function getFields($tables): array
{ {
$res = []; $res = [];
if (!is_array($tables)) { if (!is_array($tables)) {
@@ -254,7 +257,7 @@ class Gii
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function createModelFile($tableName, $tables) public function createModelFile($tableName, $tables): array
{ {
$res = $visible = $fields = $keys = []; $res = $visible = $fields = $keys = [];
foreach ($tables as $_key => $_val) { foreach ($tables as $_key => $_val) {
@@ -289,7 +292,7 @@ class Gii
* @return string * @return string
* 创建变量注释 * 创建变量注释
*/ */
private function createVisible($field) private function createVisible($field): string
{ {
return ' return '
* @property $' . $field; * @property $' . $field;
@@ -301,7 +304,7 @@ class Gii
* @return string * @return string
* 暂时不知道干嘛用的 * 暂时不知道干嘛用的
*/ */
private function createSetFunc($field, $comment) #[Pure] private function createSetFunc($field, $comment): string
{ {
return ' return '
' . str_pad('\'' . $field . '\'', 20, ' ', STR_PAD_RIGHT) . '=> \'' . (empty($comment) ? ucfirst($field) : $comment) . '\','; ' . str_pad('\'' . $field . '\'', 20, ' ', STR_PAD_RIGHT) . '=> \'' . (empty($comment) ? ucfirst($field) : $comment) . '\',';
@@ -312,18 +315,13 @@ class Gii
* @return string * @return string
* 构建类名称 * 构建类名称
*/ */
private function getClassName($tableName) private function getClassName($tableName): string
{ {
$res = []; $res = [];
foreach (explode('_', $tableName) as $n => $val) { foreach (explode('_', $tableName) as $n => $val) {
$res[] = ucfirst($val); $res[] = ucfirst($val);
} }
$name = ucfirst(rtrim($this->db->tablePrefix, '_'));
return implode('', $res); return implode('', $res);
return str_replace($name, '', implode('', $res)) . 'Comply';
} }
} }
+24 -22
View File
@@ -6,6 +6,9 @@ namespace Gii;
use Database\Connection; use Database\Connection;
use JetBrains\PhpStorm\ArrayShape;
use JetBrains\PhpStorm\Pure;
use ReflectionClass;
use Snowflake\Abstracts\Input; use Snowflake\Abstracts\Input;
/** /**
@@ -15,22 +18,22 @@ use Snowflake\Abstracts\Input;
abstract class GiiBase abstract class GiiBase
{ {
public $fileList = []; public array $fileList = [];
/** @var Input */ /** @var Input */
protected $input; protected Input $input;
public $modelPath = APP_PATH . '/app/Models/'; public string $modelPath = APP_PATH . '/app/Models/';
public $modelNamespace = 'App\Models\\'; public string $modelNamespace = 'App\Models\\';
public $controllerPath = APP_PATH . '/app/Http/Controllers/'; public string $controllerPath = APP_PATH . '/app/Http/Controllers/';
public $controllerNamespace = 'App\\Http\\Controllers\\'; public string $controllerNamespace = 'App\\Http\\Controllers\\';
public $module = null; public ?string $module = null;
public $rules = []; public array $rules = [];
public $type = [ public array $type = [
'int' => ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'], 'int' => ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'],
'string' => ['char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext', 'enum'], 'string' => ['char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext', 'enum'],
'date' => ['date'], 'date' => ['date'],
@@ -40,10 +43,9 @@ abstract class GiiBase
'timestamp' => ['timestamp'], 'timestamp' => ['timestamp'],
'float' => ['float', 'double', 'decimal',], 'float' => ['float', 'double', 'decimal',],
]; ];
public $tableName = NULL; public ?string $tableName = NULL;
/** @var Connection */ public ?Connection $db = null;
public $db;
/** /**
* @param string $modelPath * @param string $modelPath
@@ -96,12 +98,12 @@ abstract class GiiBase
/** /**
* @param \ReflectionClass $object * @param ReflectionClass $object
* @param $className * @param $className
* *
* @return string * @return string
*/ */
public function getUseContent($object, $className) public function getUseContent(ReflectionClass $object, $className): string
{ {
if (empty($object)) { if (empty($object)) {
return ''; return '';
@@ -126,10 +128,10 @@ abstract class GiiBase
/** /**
* @param $fields * @param $fields
* @return mixed|null * @return mixed 返回表主键
* 返回表主键 * 返回表主键
*/ */
public function getPrimaryKey($fields) public function getPrimaryKey($fields): mixed
{ {
$condition = ['PRI', 'UNI']; $condition = ['PRI', 'UNI'];
foreach ($fields as $field) { foreach ($fields as $field) {
@@ -147,7 +149,7 @@ abstract class GiiBase
* @param $className * @param $className
* @return string * @return string
*/ */
private function getFilePath($className) private function getFilePath($className): string
{ {
if (strpos($className, '\\')) { if (strpos($className, '\\')) {
$className = str_replace('\\', '/', $className); $className = str_replace('\\', '/', $className);
@@ -160,13 +162,13 @@ abstract class GiiBase
} }
/** /**
* @param \ReflectionClass $object * @param ReflectionClass $object
* @param $className * @param $className
* @param $method * @param $method
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public function getFuncLineContent($object, $className, $method) public function getFuncLineContent(ReflectionClass $object, $className, $method): string
{ {
$fun = $object->getMethod($method); $fun = $object->getMethod($method);
@@ -180,7 +182,7 @@ abstract class GiiBase
/** /**
* @return array * @return array
*/ */
protected function getModelPath() protected function getModelPath(): array
{ {
$dbName = $this->db->id; $dbName = $this->db->id;
if (empty($dbName) || $dbName == 'db') { if (empty($dbName) || $dbName == 'db') {
@@ -217,7 +219,7 @@ abstract class GiiBase
* @param $val * @param $val
* @return string * @return string
*/ */
protected function checkIsRequired($val) #[Pure] protected function checkIsRequired($val): string
{ {
return strtolower($val['Null']) == 'no' && $val['Default'] === NULL ? 'true' : 'false'; return strtolower($val['Null']) == 'no' && $val['Default'] === NULL ? 'true' : 'false';
} }
@@ -225,7 +227,7 @@ abstract class GiiBase
/** /**
* @return array * @return array
*/ */
public function getFileLists() public function getFileLists(): array
{ {
return $this->fileList; return $this->fileList;
} }
+26 -16
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Gii; namespace Gii;
use Exception;
use Snowflake\Snowflake; use Snowflake\Snowflake;
/** /**
@@ -13,9 +14,9 @@ use Snowflake\Snowflake;
class GiiController extends GiiBase class GiiController extends GiiBase
{ {
public $className; public string $className = '';
public $fields; public array $fields = [];
public function __construct($className, $fields) public function __construct($className, $fields)
{ {
@@ -26,9 +27,9 @@ class GiiController extends GiiBase
/** /**
* @return string * @return string
* @throws \Exception * @throws Exception
*/ */
public function generate() public function generate(): string
{ {
$path = $this->getControllerPath(); $path = $this->getControllerPath();
$modelPath = $this->getModelPath(); $modelPath = $this->getModelPath();
@@ -70,7 +71,7 @@ use {$model_namespace}\\{$managerName};
} }
$historyModel = "use {$model_namespace}\\{$managerName};"; $historyModel = "use {$model_namespace}\\{$managerName};";
if (strpos($html, $historyModel) === false) { if (!str_contains($html, $historyModel)) {
$html .= $historyModel; $html .= $historyModel;
} }
@@ -125,7 +126,7 @@ class {$controllerName}Controller extends Controller
/** /**
* @return array * @return array
*/ */
private function getControllerPath() private function getControllerPath(): array
{ {
$dbName = $this->db->id; $dbName = $this->db->id;
if (empty($dbName) || $dbName == 'db') { if (empty($dbName) || $dbName == 'db') {
@@ -159,7 +160,7 @@ class {$controllerName}Controller extends Controller
* @return string * @return string
* 新增 * 新增
*/ */
public function controllerMethodAdd($fields, $className, $object = NULL) public function controllerMethodAdd($fields, $className, $object = NULL): string
{ {
return ' return '
/** /**
@@ -184,7 +185,7 @@ class {$controllerName}Controller extends Controller
* @return string * @return string
* 通用 * 通用
*/ */
public function controllerMethodLoadParam($fields, $className, $object = NULL) public function controllerMethodLoadParam($fields, $className, $object = NULL): string
{ {
return ' return '
/** /**
@@ -205,7 +206,7 @@ class {$controllerName}Controller extends Controller
* @return string * @return string
* 构建更新 * 构建更新
*/ */
public function controllerMethodUpdate($fields, $className, $object = NULL) public function controllerMethodUpdate($fields, $className, $object = NULL): string
{ {
return ' return '
/** /**
@@ -234,7 +235,7 @@ class {$controllerName}Controller extends Controller
* @return string * @return string
* 构建更新 * 构建更新
*/ */
public function controllerMethodBatchDelete($fields, $className, $object = NULL) public function controllerMethodBatchDelete($fields, $className, $object = NULL): string
{ {
return ' return '
/** /**
@@ -269,7 +270,7 @@ class {$controllerName}Controller extends Controller
* @return string * @return string
* 构建详情 * 构建详情
*/ */
public function controllerMethodDetail($fields, $className, $managerName) public function controllerMethodDetail($fields, $className, $managerName): string
{ {
return ' return '
/** /**
@@ -293,7 +294,7 @@ class {$controllerName}Controller extends Controller
* @return string * @return string
* 构建删除操作 * 构建删除操作
*/ */
public function controllerMethodDelete($fields, $className, $managerName) public function controllerMethodDelete($fields, $className, $managerName): string
{ {
return ' return '
/** /**
@@ -329,7 +330,7 @@ class {$controllerName}Controller extends Controller
* @return string * @return string
* 构建查询列表 * 构建查询列表
*/ */
public function controllerMethodList($fields, $className, $managerName, $object = NULL) public function controllerMethodList($fields, $className, $managerName, $object = NULL): string
{ {
return ' return '
/** /**
@@ -366,7 +367,7 @@ class {$controllerName}Controller extends Controller
'; ';
} }
private function getData($fields) private function getData($fields): string
{ {
$html = ''; $html = '';
@@ -439,7 +440,12 @@ class {$controllerName}Controller extends Controller
return $html; return $html;
} }
private function getMaxLength($fields)
/**
* @param $fields
* @return int
*/
private function getMaxLength($fields): int
{ {
$length = 0; $length = 0;
foreach ($fields as $key => $val) { foreach ($fields as $key => $val) {
@@ -448,7 +454,11 @@ class {$controllerName}Controller extends Controller
return $length; return $length;
} }
private function getWhere($fields) /**
* @param $fields
* @return string
*/
private function getWhere($fields): string
{ {
$html = ''; $html = '';
+2 -5
View File
@@ -15,17 +15,14 @@ use Snowflake\Snowflake;
class GiiInterceptor extends GiiBase class GiiInterceptor extends GiiBase
{ {
public $tableName; public ?string $tableName = null;
public $visible;
public $res;
public $fields;
/** /**
* @return string[] * @return string[]
* @throws Exception * @throws Exception
*/ */
public function generate() public function generate(): array
{ {
$managerName = $this->input->get('name', null); $managerName = $this->input->get('name', null);
+2 -5
View File
@@ -15,17 +15,14 @@ use Snowflake\Snowflake;
class GiiLimits extends GiiBase class GiiLimits extends GiiBase
{ {
public $tableName; public ?string $tableName = '';
public $visible;
public $res;
public $fields;
/** /**
* @return string[] * @return string[]
* @throws Exception * @throws Exception
*/ */
public function generate() public function generate(): array
{ {
$managerName = $this->input->get('name', null); $managerName = $this->input->get('name', null);
+2 -7
View File
@@ -15,17 +15,12 @@ use Snowflake\Snowflake;
class GiiMiddleware extends GiiBase class GiiMiddleware extends GiiBase
{ {
public $tableName;
public $visible;
public $res;
public $fields;
/** /**
* @return string[] * @return array
* @throws Exception * @throws Exception
*/ */
public function generate() public function generate(): array
{ {
$managerName = $this->input->get('name', null); $managerName = $this->input->get('name', null);
+30 -24
View File
@@ -5,6 +5,8 @@ declare(strict_types=1);
namespace Gii; namespace Gii;
use Database\Db; use Database\Db;
use Exception;
use ReflectionException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
/** /**
@@ -14,11 +16,10 @@ use Snowflake\Snowflake;
class GiiModel extends GiiBase class GiiModel extends GiiBase
{ {
public $classFileName; public ?string $classFileName;
public $tableName; public ?array $visible;
public $visible; public ?array $res;
public $res; public ?array $fields;
public $fields;
/** /**
* ModelFile constructor. * ModelFile constructor.
@@ -28,7 +29,7 @@ class GiiModel extends GiiBase
* @param $res * @param $res
* @param $fields * @param $fields
*/ */
public function __construct($classFileName, $tableName, $visible, $res, $fields) public function __construct(string $classFileName, string $tableName, array $visible, array $res, array $fields)
{ {
$this->classFileName = $classFileName; $this->classFileName = $classFileName;
$this->tableName = $tableName; $this->tableName = $tableName;
@@ -38,10 +39,10 @@ class GiiModel extends GiiBase
} }
/** /**
* @throws \ReflectionException * @throws ReflectionException
* @throws \Exception * @throws Exception
*/ */
public function generate() public function generate(): string
{ {
$class = ''; $class = '';
$modelPath = $this->getModelPath(); $modelPath = $this->getModelPath();
@@ -75,7 +76,7 @@ use Database\ActiveRecord;';
$createSql = $this->setCreateSql($this->tableName); $createSql = $this->setCreateSql($this->tableName);
if (strpos($html, $createSql) === false) { if (!str_contains($html, $createSql)) {
$html .= ' $html .= '
' . $this->setCreateSql($this->tableName); ' . $this->setCreateSql($this->tableName);
} }
@@ -193,7 +194,12 @@ class ' . $managerName . ' extends ActiveRecord
} }
private function generate_json_function($html, $fields) /**
* @param $html
* @param $fields
* @return array
*/
private function generate_json_function($html, $fields): array
{ {
$strings = []; $strings = [];
foreach ($fields as $field) { foreach ($fields as $field) {
@@ -228,11 +234,11 @@ class ' . $managerName . ' extends ActiveRecord
} }
'; ';
if (strpos($html, 'set' . ucfirst($field['Field']) . 'Attribute') === false) { if (!str_contains($html, 'set' . ucfirst($field['Field']) . 'Attribute')) {
$strings[] = $function; $strings[] = $function;
} }
if (strpos($html, 'get' . ucfirst($field['Field']) . 'Attribute') === false) { if (!str_contains($html, 'get' . ucfirst($field['Field']) . 'Attribute')) {
$strings[] = $get_function; $strings[] = $get_function;
} }
} }
@@ -247,7 +253,7 @@ class ' . $managerName . ' extends ActiveRecord
* @return string * @return string
* 创建表名称 * 创建表名称
*/ */
private function createTableName($field) private function createTableName($field): string
{ {
$prefixed = $this->db->tablePrefix; $prefixed = $this->db->tablePrefix;
@@ -271,7 +277,7 @@ class ' . $managerName . ' extends ActiveRecord
* @return string * @return string
* 创建效验规则 * 创建效验规则
*/ */
private function createRules($fields) private function createRules($fields): string
{ {
$data = []; $data = [];
foreach ($fields as $key => $val) { foreach ($fields as $key => $val) {
@@ -325,7 +331,7 @@ class ' . $managerName . ' extends ActiveRecord
* @param $val * @param $val
* @return string * @return string
*/ */
public function getLength($val) public function getLength($val): string
{ {
$data = []; $data = [];
foreach ($val as $key => $_val) { foreach ($val as $key => $_val) {
@@ -339,7 +345,7 @@ class ' . $managerName . ' extends ActiveRecord
if (empty($data)) return ''; if (empty($data)) return '';
$string = []; $string = [];
foreach ($data as $key => $_val) { foreach ($data as $key => $_val) {
if (is_string($key) && strpos($key, ',') !== false) { if (is_string($key) && str_contains($key, ',')) {
$key = '[' . $key . ']'; $key = '[' . $key . ']';
} }
if (count($_val) == 1) { if (count($_val) == 1) {
@@ -359,12 +365,12 @@ class ' . $managerName . ' extends ActiveRecord
* @param $fields * @param $fields
* @return string * @return string
*/ */
public function getUnique($fields) public function getUnique($fields): string
{ {
$data = []; $data = [];
foreach ($fields as $_key => $_val) { foreach ($fields as $_key => $_val) {
if ($_val['Extra'] == 'auto_increment') continue; if ($_val['Extra'] == 'auto_increment') continue;
if (strpos($_val['Type'], 'unique') !== FALSE) { if (str_contains($_val['Type'], 'unique')) {
$data[] = $_val['Field']; $data[] = $_val['Field'];
} }
} }
@@ -379,7 +385,7 @@ class ' . $managerName . ' extends ActiveRecord
* @param $val * @param $val
* @return string * @return string
*/ */
public function getRequired($val) public function getRequired($val): string
{ {
$data = []; $data = [];
foreach ($val as $_key => $_val) { foreach ($val as $_key => $_val) {
@@ -409,7 +415,7 @@ class ' . $managerName . ' extends ActiveRecord
* 'field' ,'字段類型' ,'是否必填' ,'字段长度' , '字段解释', * 'field' ,'字段類型' ,'是否必填' ,'字段长度' , '字段解释',
* ) * )
*/ */
private function createPrimary($fields) private function createPrimary($fields): ?string
{ {
$field = $this->getPrimaryKey($fields); $field = $this->getPrimaryKey($fields);
if (empty($field)) { if (empty($field)) {
@@ -422,7 +428,7 @@ class ' . $managerName . ' extends ActiveRecord
/** /**
* @return string * @return string
*/ */
private function createDatabaseSource() private function createDatabaseSource(): string
{ {
return ' return '
/** /**
@@ -439,9 +445,9 @@ class ' . $managerName . ' extends ActiveRecord
/** /**
* @param $table * @param $table
* @return string * @return string
* @throws \Exception * @throws Exception
*/ */
private function setCreateSql($table) private function setCreateSql($table): string
{ {
$text = Db::showCreateSql($table, $this->db)['Create Table'] ?? ''; $text = Db::showCreateSql($table, $this->db)['Create Table'] ?? '';
+1 -7
View File
@@ -14,18 +14,12 @@ use Snowflake\Snowflake;
class GiiTask extends GiiBase class GiiTask extends GiiBase
{ {
public $classFileName;
public $tableName;
public $visible;
public $res;
public $fields;
/** /**
* @return string[] * @return string[]
* @throws Exception * @throws Exception
*/ */
public function generate() public function generate(): array
{ {
$managerName = $this->input->get('name', null); $managerName = $this->input->get('name', null);
+1 -1
View File
@@ -86,7 +86,7 @@ abstract class Callback extends Application
* @throws \PHPMailer\PHPMailer\Exception * @throws \PHPMailer\PHPMailer\Exception
* @throws ConfigException * @throws ConfigException
*/ */
private function createEmail() private function createEmail(): PHPMailer
{ {
$mail = new PHPMailer(true); $mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
+1 -1
View File
@@ -25,7 +25,7 @@ abstract class ServerBase extends Application
/** /**
* @return Server * @return Server
*/ */
public function getServer() public function getServer(): Server
{ {
return $this->server; return $this->server;
} }
+4 -3
View File
@@ -5,6 +5,7 @@ namespace HttpServer;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Input; use Snowflake\Abstracts\Input;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -87,7 +88,7 @@ trait Action
/** /**
* WorkerId Iterator * WorkerId Iterator
*/ */
private function masterIdCheck() private function masterIdCheck(): bool
{ {
echo '.'; echo '.';
$files = new \DirectoryIterator($this->getWorkerPath()); $files = new \DirectoryIterator($this->getWorkerPath());
@@ -110,7 +111,7 @@ trait Action
/** /**
* @return string * @return string
*/ */
private function getWorkerPath() #[Pure] private function getWorkerPath(): string
{ {
return "glob://" . ltrim(APP_PATH, '/') . '/storage/worker/*.sock'; return "glob://" . ltrim(APP_PATH, '/') . '/storage/worker/*.sock';
} }
@@ -120,7 +121,7 @@ trait Action
* @param $port * @param $port
* @return bool|array * @return bool|array
*/ */
private function isUse($port) private function isUse($port): bool|array
{ {
if (empty($port)) { if (empty($port)) {
return false; return false;
+8 -8
View File
@@ -28,23 +28,23 @@ class Application extends HttpService
} }
/** /**
* @param $methods * @param $name
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function __get($methods) public function __get($name): mixed
{ {
if (method_exists($this, $methods)) { if (method_exists($this, $name)) {
return $this->{$methods}(); return $this->{$name}();
} }
$handler = 'get' . ucfirst($methods); $handler = 'get' . ucfirst($name);
if (method_exists($this, $handler)) { if (method_exists($this, $handler)) {
return $this->{$handler}(); return $this->{$handler}();
} }
if (property_exists($this, $methods)) { if (property_exists($this, $name)) {
return $this->$methods; return $this->$name;
} }
$message = sprintf('method %s::%s not exists.', get_called_class(), $methods); $message = sprintf('method %s::%s not exists.', get_called_class(), $name);
throw new Exception($message); throw new Exception($message);
} }
+11 -11
View File
@@ -10,7 +10,7 @@ declare(strict_types=1);
namespace HttpServer\Client; namespace HttpServer\Client;
use Exception; use Exception;
use Swoole\Coroutine; use JetBrains\PhpStorm\Pure;
use Swoole\Coroutine\Http\Client as SClient; use Swoole\Coroutine\Http\Client as SClient;
/** /**
@@ -22,17 +22,17 @@ class Client extends ClientAbstracts
/** /**
* @param string $method * @param string $method
* @param $url * @param $path
* @param array $data * @param array $params
* @return array|mixed|Result * @return array|string|Result
* @throws Exception * @throws Exception
*/ */
public function request(string $method, $url, $data = []) public function request(string $method, $path, $params = []): array|string|Result
{ {
return $this->setMethod($method) return $this->setMethod($method)
->coroutine( ->coroutine(
$this->matchHost($url), $this->matchHost($path),
$this->paramEncode($data) $this->paramEncode($params)
); );
} }
@@ -40,11 +40,11 @@ class Client extends ClientAbstracts
/** /**
* @param $url * @param $url
* @param array $data * @param array $data
* @return array|mixed|Result * @return array|string|Result
* @throws Exception * @throws Exception
* 使用swoole协程方式请求 * 使用swoole协程方式请求
*/ */
private function coroutine($url, $data = []) private function coroutine($url, $data = []): array|string|Result
{ {
try { try {
$client = $this->generate_client($data, ...$url); $client = $this->generate_client($data, ...$url);
@@ -77,7 +77,7 @@ class Client extends ClientAbstracts
* @param $path * @param $path
* @return SClient * @return SClient
*/ */
private function generate_client($data, $host, $isHttps, $path) private function generate_client($data, $host, $isHttps, $path): SClient
{ {
if ($isHttps || $this->isSSL()) { if ($isHttps || $this->isSSL()) {
$client = new SClient($host, 443, $this->isSSL()); $client = new SClient($host, 443, $this->isSSL());
@@ -112,7 +112,7 @@ class Client extends ClientAbstracts
/** /**
* @return array * @return array
*/ */
private function settings() #[Pure] private function settings(): array
{ {
$sslCert = $this->getSslCertFile(); $sslCert = $this->getSslCertFile();
$sslKey = $this->getSslKeyFile(); $sslKey = $this->getSslKeyFile();
+95 -104
View File
@@ -6,6 +6,7 @@ namespace HttpServer\Client;
use Closure; use Closure;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Core\Help; use Snowflake\Core\Help;
use Snowflake\Core\JSON; use Snowflake\Core\JSON;
@@ -57,33 +58,32 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @return static * @return static
*/ */
public static function NewRequest() #[Pure] public static function NewRequest(): static
{ {
return new static(); return new static();
} }
/** /**
* @param $url * @param $path
* @param array $data * @param array $params
* @return array|mixed|Result * @return array|int|string|Result
* @throws * @throws
*/ */
public function post($url, $data = []) public function post(string $path, array $params = []): array|int|string|Result
{ {
return $this->request(self::POST, $url, $data); return $this->request(self::POST, $path, $params);
} }
/** /**
* @param $url * @param string $path
* @param array $data * @param array $params
* @return array|mixed|Result * @return array|int|string|Result
* @throws
*/ */
public function put($url, $data = []) public function put(string $path, array $params = []): array|int|string|Result
{ {
return $this->request(self::PUT, $url, $data); return $this->request(self::PUT, $path, $params);
} }
@@ -99,54 +99,50 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
* @return mixed * @return array|int|string|Result
*/ */
public function head(string $path, array $params = []) public function head(string $path, array $params = []): array|int|string|Result
{ {
return $this->request(self::HEAD, $path, $params); return $this->request(self::HEAD, $path, $params);
} }
/** /**
* @param $url * @param string $path
* @param array $data * @param array $params
* @return array|mixed|Result * @return array|int|string|Result
* @throws
*/ */
public function get($url, $data = []) public function get(string $path, array $params = []): array|int|string|Result
{ {
return $this->request(self::GET, $url, $data); return $this->request(self::GET, $path, $params);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws Exception
*/
public function option($url, $data = [])
{
return $this->request(self::OPTIONS, $url, $data);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws Exception
*/
public function delete($url, $data = [])
{
return $this->request(self::DELETE, $url, $data);
} }
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
* @return mixed * @return array|int|string|Result
* @throws Exception
*/ */
public function options(string $path, array $params = []) public function option(string $path, array $params = []): array|int|string|Result
{
return $this->request(self::OPTIONS, $path, $params);
}
/**
* @param string $path
* @param array $params
* @return array|int|string|Result
*/
public function delete(string $path, array $params = []): array|int|string|Result
{
return $this->request(self::DELETE, $path, $params);
}
/**
* @param string $path
* @param array $params
* @return array|int|string|Result
*/
public function options(string $path, array $params = []): array|int|string|Result
{ {
return $this->request(self::OPTIONS, $path, $params); return $this->request(self::OPTIONS, $path, $params);
@@ -155,10 +151,9 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
* @return mixed * @return array|int|string|Result
* @throws Exception
*/ */
public function upload(string $path, array $params = []) public function upload(string $path, array $params = []): array|int|string|Result
{ {
return $this->request(self::UPLOAD, $path, $params); return $this->request(self::UPLOAD, $path, $params);
} }
@@ -175,7 +170,7 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @return int * @return int
*/ */
protected function getHostPort() protected function getHostPort(): int
{ {
if (!empty($this->getPort())) { if (!empty($this->getPort())) {
return $this->getPort(); return $this->getPort();
@@ -196,10 +191,6 @@ abstract class ClientAbstracts extends Component implements IClient
$this->host = System::gethostbyname($host); $this->host = System::gethostbyname($host);
} }
$this->addHeader('Host', $host); $this->addHeader('Host', $host);
//
// if (!preg_match('/(\d{1,3}\.){4}/', $host . '.')) {
// } else {
// }
} }
/** /**
@@ -220,15 +211,15 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param array $headers * @param array $header
* @return array * @return array
*/ */
public function setHeaders(array $headers) public function setHeaders(array $header): array
{ {
if (empty($headers)) { if (empty($header)) {
return []; return [];
} }
foreach ($headers as $key => $val) { foreach ($header as $key => $val) {
$this->header[$key] = $val; $this->header[$key] = $val;
} }
return $this->header; return $this->header;
@@ -252,11 +243,11 @@ abstract class ClientAbstracts extends Component implements IClient
} }
/** /**
* @param int $timeout * @param int $value
*/ */
public function setTimeout(int $timeout): void public function setTimeout(int $value): void
{ {
$this->timeout = $timeout; $this->timeout = $value;
} }
/** /**
@@ -268,11 +259,11 @@ abstract class ClientAbstracts extends Component implements IClient
} }
/** /**
* @param Closure|null $callback * @param Closure|null $value
*/ */
public function setCallback(?Closure $callback): void public function setCallback(?Closure $value): void
{ {
$this->callback = $callback; $this->callback = $value;
} }
/** /**
@@ -284,12 +275,12 @@ abstract class ClientAbstracts extends Component implements IClient
} }
/** /**
* @param string $method * @param string $value
* @return $this * @return $this
*/ */
public function setMethod(string $method): self public function setMethod(string $value): self
{ {
$this->method = $method; $this->method = $value;
return $this; return $this;
} }
@@ -414,17 +405,17 @@ abstract class ClientAbstracts extends Component implements IClient
} }
/** /**
* @param string $ca * @param string $ssl_key_file
*/ */
public function setCa(string $ca): void public function setCa(string $ssl_key_file): void
{ {
$this->ca = $ca; $this->ca = $ssl_key_file;
} }
/** /**
* @return int * @return int
*/ */
public function getPort(): int #[Pure] public function getPort(): int
{ {
if ($this->isSSL()) { if ($this->isSSL()) {
return 443; return 443;
@@ -496,7 +487,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $host * @param $host
* @return string|string[] * @return string|string[]
*/ */
protected function replaceHost($host) protected function replaceHost($host): array|string
{ {
if ($this->isHttp($host)) { if ($this->isHttp($host)) {
return str_replace('http://', '', $host); return str_replace('http://', '', $host);
@@ -512,7 +503,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $url * @param $url
* @return false|int * @return false|int
*/ */
protected function checkIsIp($url) protected function checkIsIp($url): bool|int
{ {
return preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $url); return preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $url);
} }
@@ -521,18 +512,18 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $url * @param $url
* @return bool * @return bool
*/ */
protected function isHttp($url) #[Pure] protected function isHttp($url): bool
{ {
return strpos($url, 'http://') === 0; return str_starts_with($url, 'http://');
} }
/** /**
* @param $url * @param $url
* @return bool * @return bool
*/ */
protected function isHttps($url) #[Pure] protected function isHttps($url): bool
{ {
return strpos($url, 'https://') === 0; return str_starts_with($url, 'https://');
} }
@@ -540,7 +531,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $newData * @param $newData
* @return mixed * @return mixed
*/ */
protected function mergeParams($newData) protected function mergeParams($newData): mixed
{ {
if (empty($this->getData())) { if (empty($this->getData())) {
return $this->toRequest($newData); return $this->toRequest($newData);
@@ -559,9 +550,9 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param $data * @param $data
* @return false|mixed|string * @return string
*/ */
protected function toRequest($data) protected function toRequest($data): string
{ {
if (is_string($data)) { if (is_string($data)) {
return $data; return $data;
@@ -572,9 +563,9 @@ abstract class ClientAbstracts extends Component implements IClient
} else if (isset($this->header['content-type'])) { } else if (isset($this->header['content-type'])) {
$contentType = $this->header['content-type']; $contentType = $this->header['content-type'];
} }
if (strpos($contentType, 'json') !== false) { if (str_contains($contentType, 'json')) {
return Help::toJson($data); return Help::toJson($data);
} else if (strpos($contentType, 'xml') !== false) { } else if (str_contains($contentType, 'xml')) {
return Help::toXml($data); return Help::toXml($data);
} else { } else {
return http_build_query($data); return http_build_query($data);
@@ -585,21 +576,21 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param $data * @param $data
* @param $body * @param $body
* @return mixed * @return array
*/ */
protected function resolve($data, $body) protected function resolve($data, $body): array
{ {
if (is_array($body)) { if (is_array($body)) {
return $body; return $body;
} }
$type = $data['content-type'] ?? $data['Content-Type'] ?? 'text/html'; $type = $data['content-type'] ?? $data['Content-Type'] ?? 'text/html';
if (strpos($type, 'text/html') !== false) { if (str_contains($type, 'text/html')) {
return $body; return $body;
} else if (strpos($type, 'json') !== false) { } else if (str_contains($type, 'json')) {
return json_decode($body, true); return json_decode($body, true);
} else if (strpos($type, 'xml') !== false) { } else if (str_contains($type, 'xml')) {
return Help::xmlToArray($body); return Help::xmlToArray($body);
} else if (strpos($type, 'plain') !== false) { } else if (str_contains($type, 'plain')) {
return Help::toArray($body); return Help::toArray($body);
} }
return $body; return $body;
@@ -609,12 +600,12 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param $body * @param $body
* @param $_data * @param $_data
* @param $header * @param array $header
* @param $statusCode * @param int $statusCode
* @return array|mixed|Result * @return mixed 构建返回体
* 构建返回体 * 构建返回体
*/ */
protected function structure($body, $_data, $header = [], $statusCode = 200) protected function structure($body, $_data, $header = [], $statusCode = 200): mixed
{ {
if ($this->callback instanceof Closure) { if ($this->callback instanceof Closure) {
$result = call_user_func($this->callback, $body, $_data, $header); $result = call_user_func($this->callback, $body, $_data, $header);
@@ -631,7 +622,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $statusCode * @param $statusCode
* @return Result * @return Result
*/ */
private function parseResult($body, $header, $statusCode) private function parseResult($body, $header, $statusCode): Result
{ {
if (is_string($body)) { if (is_string($body)) {
$result['code'] = 0; $result['code'] = 0;
@@ -649,9 +640,9 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param $body * @param $body
* @return array|mixed|string * @return mixed
*/ */
protected function searchMessageByData($body) protected function searchMessageByData($body): mixed
{ {
$parent = []; $parent = [];
if (empty($this->errorMsgField)) { if (empty($this->errorMsgField)) {
@@ -682,7 +673,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @return bool * @return bool
* check isPost Request * check isPost Request
*/ */
public function isPost() #[Pure] public function isPost(): bool
{ {
return strtolower($this->method) === self::POST; return strtolower($this->method) === self::POST;
} }
@@ -693,7 +684,7 @@ abstract class ClientAbstracts extends Component implements IClient
* *
* check isGet Request * check isGet Request
*/ */
public function isGet() #[Pure] public function isGet(): bool
{ {
return strtolower($this->method) === self::GET; return strtolower($this->method) === self::GET;
} }
@@ -704,7 +695,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @return array|string * @return array|string
* 将请求参数进行编码 * 将请求参数进行编码
*/ */
protected function paramEncode($arr) #[Pure] protected function paramEncode($arr): array|string
{ {
if (!is_array($arr)) { if (!is_array($arr)) {
return $arr; return $arr;
@@ -722,15 +713,15 @@ abstract class ClientAbstracts extends Component implements IClient
/** /**
* @param string $string * @param string $string
* @return array|string[] * @return array
*/ */
protected function matchHost(string $string) protected function matchHost(string $string): array
{ {
if (($parse = isUrl($string, true)) === false) { if (($parse = isUrl($string, true)) === false) {
return $this->defaultString($string); return $this->defaultString($string);
} }
[$isHttps, $domain, $port, $path] = $parse; [$isHttps, $domain, $port, $path] = $parse;
if (strpos($domain, ':' . $port) !== false) { if (str_contains($domain, ':' . $port)) {
$domain = str_replace(':' . $port, '', $domain); $domain = str_replace(':' . $port, '', $domain);
} }
$this->port = $isHttps ? 443 : $this->port; $this->port = $isHttps ? 443 : $this->port;
@@ -753,7 +744,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $string * @param $string
* @return array * @return array
*/ */
private function defaultString($string) private function defaultString($string): array
{ {
$host = $this->getHost(); $host = $this->getHost();
if ($string == '/') { if ($string == '/') {
@@ -770,7 +761,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $params * @param $params
* @return string * @return string
*/ */
protected function joinGetParams($path, $params) #[Pure] protected function joinGetParams($path, $params): string
{ {
if (empty($params)) { if (empty($params)) {
return $path; return $path;
@@ -778,7 +769,7 @@ abstract class ClientAbstracts extends Component implements IClient
if (!is_string($params)) { if (!is_string($params)) {
$params = http_build_query($params); $params = http_build_query($params);
} }
if (strpos($path, '?') !== false) { if (str_contains($path, '?')) {
[$path, $getParams] = explode('?', $path); [$path, $getParams] = explode('?', $path);
} }
if (!isset($getParams) || empty($getParams)) { if (!isset($getParams) || empty($getParams)) {
@@ -795,7 +786,7 @@ abstract class ClientAbstracts extends Component implements IClient
* @param $header * @param $header
* @return Result * @return Result
*/ */
protected function fail($code, $message, $data = [], $header = []) protected function fail($code, $message, $data = [], $header = []): Result
{ {
return new Result([ return new Result([
'code' => $code, 'code' => $code,
+15 -14
View File
@@ -5,6 +5,7 @@ namespace HttpServer\Client;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure;
/** /**
* Class Curl * Class Curl
@@ -14,13 +15,13 @@ class Curl extends ClientAbstracts
{ {
/** /**
* @param $path
* @param $method * @param $method
* @param $path
* @param array $params * @param array $params
* @return bool|string * @return Result|bool|array|string
* @throws Exception * @throws Exception
*/ */
public function request($method, $path, $params = []) public function request($method, $path, $params = []): Result|bool|array|string
{ {
if ($method == self::GET) { if ($method == self::GET) {
$path = $this->joinGetParams($path, $params); $path = $this->joinGetParams($path, $params);
@@ -33,10 +34,10 @@ class Curl extends ClientAbstracts
* @param $path * @param $path
* @param $method * @param $method
* @param $params * @param $params
* @return mixed|resource * @return mixed
* @throws Exception * @throws Exception
*/ */
private function getCurlHandler($path, $method, $params) private function getCurlHandler($path, $method, $params): mixed
{ {
[$host, $isHttps, $path] = $this->matchHost($path); [$host, $isHttps, $path] = $this->matchHost($path);
@@ -71,7 +72,7 @@ class Curl extends ClientAbstracts
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
private function curlHandlerSslSet($resource) private function curlHandlerSslSet($resource): bool
{ {
if (!empty($this->ssl_key)) { if (!empty($this->ssl_key)) {
if (!file_exists($this->ssl_key)) { if (!file_exists($this->ssl_key)) {
@@ -129,10 +130,10 @@ class Curl extends ClientAbstracts
/** /**
* @param $curl * @param $curl
* @return bool|string * @return Result|bool|array|string
* @throws Exception * @throws Exception
*/ */
private function execute($curl) private function execute($curl): Result|bool|array|string
{ {
$output = curl_exec($curl); $output = curl_exec($curl);
if ($output === false) { if ($output === false) {
@@ -146,10 +147,10 @@ class Curl extends ClientAbstracts
* @param $curl * @param $curl
* @param $output * @param $output
* @param array $params * @param array $params
* @return array|Result|mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function parseResponse($curl, $output, $params = []) private function parseResponse($curl, $output, $params = []): mixed
{ {
curl_close($curl); curl_close($curl);
if ($output === FALSE) { if ($output === FALSE) {
@@ -170,9 +171,9 @@ class Curl extends ClientAbstracts
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
private function explode($output) private function explode($output): array
{ {
if (empty($output) || strpos($output, "\r\n\r\n") === false) { if (empty($output) || !str_contains($output, "\r\n\r\n")) {
throw new Exception('Get data null.'); throw new Exception('Get data null.');
} }
@@ -193,7 +194,7 @@ class Curl extends ClientAbstracts
* @param $headers * @param $headers
* @return array * @return array
*/ */
private function headerFormat($headers) private function headerFormat($headers): array
{ {
$_tmp = []; $_tmp = [];
foreach ($headers as $key => $val) { foreach ($headers as $key => $val) {
@@ -208,7 +209,7 @@ class Curl extends ClientAbstracts
/** /**
* @return array * @return array
*/ */
private function parseHeaderMat() #[Pure] private function parseHeaderMat(): array
{ {
$headers = []; $headers = [];
foreach ($this->getHeader() as $key => $val) { foreach ($this->getHeader() as $key => $val) {
+9 -9
View File
@@ -25,10 +25,10 @@ class Http2 extends Component
* @param $path * @param $path
* @param array $params * @param array $params
* @param int $timeout * @param int $timeout
* @return mixed * @return Result
* @throws Exception * @throws Exception
*/ */
public function get($domain, $path, $params = [], $timeout = -1) public function get($domain, $path, $params = [], $timeout = -1): Result
{ {
$client = $this->getClient($domain, $path, $timeout); $client = $this->getClient($domain, $path, $timeout);
$client->send($this->getRequest($domain, $path, 'GET', $params)); $client->send($this->getRequest($domain, $path, 'GET', $params));
@@ -41,10 +41,10 @@ class Http2 extends Component
* @param $path * @param $path
* @param array $params * @param array $params
* @param int $timeout * @param int $timeout
* @return mixed * @return Result
* @throws Exception * @throws Exception
*/ */
public function post($domain, $path, $params = [], $timeout = -1) public function post($domain, $path, $params = [], $timeout = -1): Result
{ {
$client = $this->getClient($domain, $path, $timeout); $client = $this->getClient($domain, $path, $timeout);
$client->send($this->getRequest($domain, $path, 'POST', $params)); $client->send($this->getRequest($domain, $path, 'POST', $params));
@@ -57,10 +57,10 @@ class Http2 extends Component
* @param $path * @param $path
* @param array $params * @param array $params
* @param int $timeout * @param int $timeout
* @return mixed * @return Result
* @throws Exception * @throws Exception
*/ */
public function delete($domain, $path, $params = [], $timeout = -1) public function delete($domain, $path, $params = [], $timeout = -1): Result
{ {
$client = $this->getClient($domain, $path, $timeout); $client = $this->getClient($domain, $path, $timeout);
$client->send($this->getRequest($domain, $path, 'DELETE', $params)); $client->send($this->getRequest($domain, $path, 'DELETE', $params));
@@ -76,7 +76,7 @@ class Http2 extends Component
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function put($domain, $path, $params = [], $timeout = -1) public function put($domain, $path, $params = [], $timeout = -1): Result
{ {
$client = $this->getClient($domain, $path, $timeout); $client = $this->getClient($domain, $path, $timeout);
$client->send($this->getRequest($domain, $path, 'PUT', $params)); $client->send($this->getRequest($domain, $path, 'PUT', $params));
@@ -92,7 +92,7 @@ class Http2 extends Component
* @return Request * @return Request
* @throws Exception * @throws Exception
*/ */
public function getRequest($domain, $path, $method, $params) public function getRequest($domain, $path, $method, $params): Request
{ {
if (Context::hasContext($domain . $path)) { if (Context::hasContext($domain . $path)) {
$req = Context::getContext($domain . $path); $req = Context::getContext($domain . $path);
@@ -123,7 +123,7 @@ class Http2 extends Component
* @return H2Client * @return H2Client
* @throws Exception * @throws Exception
*/ */
private function getClient($domain, $path, $timeout = -1) private function getClient($domain, $path, $timeout = -1): H2Client
{ {
if (Context::hasContext($domain)) { if (Context::hasContext($domain)) {
return Context::getContext($domain); return Context::getContext($domain);
+2 -1
View File
@@ -4,6 +4,7 @@
namespace HttpServer\Client; namespace HttpServer\Client;
use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine; use Swoole\Coroutine;
@@ -28,7 +29,7 @@ class HttpClient extends Component
/** /**
* @return Http2 * @return Http2
*/ */
public static function http2() #[Pure] public static function http2(): Http2
{ {
return Snowflake::app()->http2; return Snowflake::app()->http2;
} }
+2 -2
View File
@@ -44,7 +44,7 @@ class HttpParse
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public static function parse($data) public static function parse($data): string
{ {
$tmp = []; $tmp = [];
if (is_string($data)) { if (is_string($data)) {
@@ -65,7 +65,7 @@ class HttpParse
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private static function ifElse($t, $qt) private static function ifElse($t, $qt): string
{ {
if (is_numeric($qt)) { if (is_numeric($qt)) {
return $t . '=' . $qt; return $t . '=' . $qt;
+14 -13
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace HttpServer\Client; namespace HttpServer\Client;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure;
/** /**
* Class Result * Class Result
@@ -45,7 +46,7 @@ class Result
* @param $data * @param $data
* @return $this * @return $this
*/ */
public function setAssignment($data) public function setAssignment($data): static
{ {
foreach ($data as $key => $val) { foreach ($data as $key => $val) {
if (!property_exists($this, $key)) { if (!property_exists($this, $key)) {
@@ -59,9 +60,9 @@ class Result
/** /**
* @param $name * @param $name
* @return mixed|null * @return mixed
*/ */
public function __get($name) public function __get($name): mixed
{ {
return $this->$name; return $this->$name;
} }
@@ -69,9 +70,9 @@ class Result
/** /**
* @param $name * @param $name
* @param $value * @param $value
* @return $this|void * @return $this
*/ */
public function __set($name, $value) public function __set($name, $value): static
{ {
$this->$name = $value; $this->$name = $value;
@@ -81,7 +82,7 @@ class Result
/** /**
* @return array * @return array
*/ */
public function getHeaders() public function getHeaders(): array
{ {
$_tmp = []; $_tmp = [];
if (!is_array($this->header)) { if (!is_array($this->header)) {
@@ -103,7 +104,7 @@ class Result
/** /**
* @return array * @return array
*/ */
public function getTime() public function getTime(): array
{ {
return [ return [
'startTime' => $this->startTime, 'startTime' => $this->startTime,
@@ -118,7 +119,7 @@ class Result
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function setAttr($key, $data) public function setAttr($key, $data): static
{ {
if (!property_exists($this, $key)) { if (!property_exists($this, $key)) {
throw new Exception('未查找到相应对象属性'); throw new Exception('未查找到相应对象属性');
@@ -131,7 +132,7 @@ class Result
* @param int $status * @param int $status
* @return bool * @return bool
*/ */
public function isResultsOK($status = 0) public function isResultsOK($status = 0): bool
{ {
if (!$this->httpIsOk()) { if (!$this->httpIsOk()) {
return false; return false;
@@ -142,7 +143,7 @@ class Result
/** /**
* @return bool * @return bool
*/ */
public function httpIsOk() #[Pure] public function httpIsOk(): bool
{ {
return in_array($this->httpStatus, [100, 101, 200, 201, 202, 203, 204, 205, 206]); return in_array($this->httpStatus, [100, 101, 200, 201, 202, 203, 204, 205, 206]);
} }
@@ -150,7 +151,7 @@ class Result
/** /**
* @return mixed * @return mixed
*/ */
public function getBody() public function getBody(): mixed
{ {
return $this->data; return $this->data;
} }
@@ -158,7 +159,7 @@ class Result
/** /**
* @return mixed * @return mixed
*/ */
public function getMessage() public function getMessage(): mixed
{ {
return $this->message; return $this->message;
} }
@@ -166,7 +167,7 @@ class Result
/** /**
* @return mixed * @return mixed
*/ */
public function getCode() public function getCode(): mixed
{ {
return $this->code; return $this->code;
} }
+3 -3
View File
@@ -27,11 +27,11 @@ class Command extends \Console\Command
/** /**
* @param Input $dtl * @param Input $dtl
* @return mixed|void * @return string
* @throws Exception * @throws Exception
* @throws ConfigException * @throws ConfigException
*/ */
public function onHandler(Input $dtl) public function onHandler(Input $dtl): string
{ {
$manager = Snowflake::app()->server; $manager = Snowflake::app()->server;
$manager->setDaemon($dtl->get('daemon', 0)); $manager->setDaemon($dtl->get('daemon', 0));
@@ -48,7 +48,7 @@ class Command extends \Console\Command
if ($dtl->get('action') == 'stop') { if ($dtl->get('action') == 'stop') {
return 'shutdown success.'; return 'shutdown success.';
} }
$manager->start(); return $manager->start();
} }
} }
+6 -10
View File
@@ -15,8 +15,6 @@ use Exception;
use HttpServer\Route\Router; use HttpServer\Route\Router;
use Kafka\Producer; use Kafka\Producer;
use Snowflake\Abstracts\BaseGoto; use Snowflake\Abstracts\BaseGoto;
use Snowflake\Annotation\Annotation;
use Snowflake\Cache\Memcached;
use Snowflake\Cache\Redis; use Snowflake\Cache\Redis;
use Snowflake\Error\Logger; use Snowflake\Error\Logger;
use Snowflake\Event; use Snowflake\Event;
@@ -30,7 +28,6 @@ use Snowflake\Snowflake;
* Class WebController * Class WebController
* @package Snowflake\Snowflake\Web * @package Snowflake\Snowflake\Web
* @property BaseGoto $goto * @property BaseGoto $goto
* @property Annotation $annotation
* @property Event $event * @property Event $event
* @property Router $router * @property Router $router
* @property SPool $pool * @property SPool $pool
@@ -38,7 +35,6 @@ use Snowflake\Snowflake;
* @property Server $server * @property Server $server
* @property DatabasesProviders $db * @property DatabasesProviders $db
* @property Connection $connections * @property Connection $connections
* @property Memcached $memcached
* @property Logger $logger * @property Logger $logger
* @property Jwt $jwt * @property Jwt $jwt
* @property Client $client * @property Client $client
@@ -131,23 +127,23 @@ class Controller extends Application
/** /**
* @param $methods * @param $name
* @return mixed * @return mixed
* @throws ComponentException * @throws ComponentException
*/ */
public function __get($methods): mixed public function __get($name): mixed
{ {
// TODO: Change the autogenerated stub // TODO: Change the autogenerated stub
if (property_exists($this, $methods)) { if (property_exists($this, $name)) {
return $this->$methods; return $this->$name;
} }
$method = 'get' . ucfirst($methods); $method = 'get' . ucfirst($name);
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
return $this->{$method}(); return $this->{$method}();
} }
return Snowflake::app()->get($methods); return Snowflake::app()->get($name);
} }
-5
View File
@@ -6,10 +6,6 @@ namespace HttpServer\Events;
use Annotation\Route\Socket; use Annotation\Route\Socket;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Route\Annotation\Http;
use HttpServer\Route\Annotation\Tcp;
use HttpServer\Route\Annotation\Websocket;
use HttpServer\Route\Annotation\Websocket as AWebsocket;
use HttpServer\Route\Node; use HttpServer\Route\Node;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
@@ -17,7 +13,6 @@ use Snowflake\Snowflake;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\Server; use Swoole\Server;
use Exception; use Exception;
use Swoole\Http\Server as HServer;
use Swoole\WebSocket\Server as WServer; use Swoole\WebSocket\Server as WServer;
/** /**
+4
View File
@@ -8,6 +8,10 @@ use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use Swoole\Server; use Swoole\Server;
/**
* Class OnFinish
* @package HttpServer\Events
*/
class OnFinish extends Callback class OnFinish extends Callback
{ {
/** /**
+4 -5
View File
@@ -7,7 +7,6 @@ namespace HttpServer\Events;
use Annotation\Route\Socket; use Annotation\Route\Socket;
use Exception; use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Route\Annotation\Websocket as AWebsocket;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -62,7 +61,7 @@ class OnHandshake extends Callback
* @param int $code * @param int $code
* @return false * @return false
*/ */
private function disconnect($response, $code = 500) private function disconnect($response, $code = 500): bool
{ {
$response->status($code); $response->status($code);
$response->end(); $response->end();
@@ -73,10 +72,10 @@ class OnHandshake extends Callback
/** /**
* @param SRequest $request * @param SRequest $request
* @param SResponse $response * @param SResponse $response
* @return mixed|void * @return void
* @throws Exception * @throws ComponentException
*/ */
public function onHandler(SRequest $request, SResponse $response) public function onHandler(SRequest $request, SResponse $response): void
{ {
Coroutine::defer(function () { Coroutine::defer(function () {
fire(Event::EVENT_AFTER_REQUEST); fire(Event::EVENT_AFTER_REQUEST);
+2 -3
View File
@@ -4,12 +4,11 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine\System;
use Swoole\Process;
use Swoole\Server; use Swoole\Server;
class OnManagerStart extends Callback class OnManagerStart extends Callback
@@ -17,7 +16,7 @@ class OnManagerStart extends Callback
/** /**
* @param Server $server * @param Server $server
* @throws \Exception * @throws Exception
*/ */
public function onHandler(Server $server) public function onHandler(Server $server)
{ {
+2 -1
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -18,7 +19,7 @@ class OnManagerStop extends Callback
/** /**
* @param $server * @param $server
* @throws \Exception * @throws Exception
*/ */
public function onHandler(Server $server) public function onHandler(Server $server)
{ {
+1 -2
View File
@@ -6,7 +6,6 @@ namespace HttpServer\Events;
use Closure; use Closure;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use Snowflake\Core\JSON;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Server; use Swoole\Server;
@@ -36,7 +35,7 @@ class OnPacket extends Callback
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function onHandler(Server $server, string $data, array $clientInfo) public function onHandler(Server $server, string $data, array $clientInfo): mixed
{ {
try { try {
$data = DataResolve::unpack($this->unpack, $clientInfo['address'], $clientInfo['port'], $data); $data = DataResolve::unpack($this->unpack, $clientInfo['address'], $clientInfo['port'], $data);
+1 -1
View File
@@ -36,7 +36,7 @@ class OnReceive extends Callback
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function onHandler(\Swoole\Server $server, int $fd, int $reID, string $data) public function onHandler(\Swoole\Server $server, int $fd, int $reID, string $data): mixed
{ {
try { try {
$client = $server->getClientInfo($fd, $reID); $client = $server->getClientInfo($fd, $reID);
-4
View File
@@ -7,13 +7,9 @@ namespace HttpServer\Events;
use Exception; use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Exception\ExitException; use HttpServer\Exception\ExitException;
use HttpServer\Http\Context;
use HttpServer\Http\Request as HRequest; use HttpServer\Http\Request as HRequest;
use HttpServer\Http\Response as HResponse; use HttpServer\Http\Response as HResponse;
use HttpServer\Route\Node;
use HttpServer\Service\Http;
use ReflectionException; use ReflectionException;
use Snowflake\Abstracts\Config;
use Snowflake\Core\JSON; use Snowflake\Core\JSON;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
-8
View File
@@ -6,18 +6,10 @@ namespace HttpServer\Events;
use Exception; use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use Snowflake\Abstracts\Config;
use Snowflake\Core\JSON;
use Snowflake\Error\Logger;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine;
use Swoole\Server; use Swoole\Server;
use Closure;
/** /**
* Class OnShutdown * Class OnShutdown
+2 -3
View File
@@ -4,12 +4,11 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine\System;
use Swoole\Process;
use Swoole\Server; use Swoole\Server;
class OnStart extends Callback class OnStart extends Callback
@@ -17,7 +16,7 @@ class OnStart extends Callback
/** /**
* @param Server $server * @param Server $server
* @throws \Exception * @throws Exception
*/ */
public function onHandler(Server $server) public function onHandler(Server $server)
{ {
-5
View File
@@ -6,15 +6,10 @@ namespace HttpServer\Events;
use Exception; use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Route\Annotation\Websocket as AWebsocket;
use HttpServer\Service\Http;
use HttpServer\Service\Websocket;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Error\Logger;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Exception\ConfigException; use Snowflake\Exception\ConfigException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine\System;
use Swoole\Server; use Swoole\Server;
/** /**
+2 -1
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Exception;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
/** /**
@@ -17,7 +18,7 @@ class OnWorkerStop extends Callback
/** /**
* @param $server * @param $server
* @param $worker_id * @param $worker_id
* @throws \Exception * @throws Exception
*/ */
public function onHandler($server, $worker_id) public function onHandler($server, $worker_id)
{ {
+2 -2
View File
@@ -65,11 +65,11 @@ class DataResolve
* @param $address * @param $address
* @param $port * @param $port
* @param $data * @param $data
* @return array|mixed * @return mixed
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
private static function callbackResolve($callback, $address, $port, $data) private static function callbackResolve($callback, $address, $port, $data): mixed
{ {
if ($callback instanceof Closure) { if ($callback instanceof Closure) {
if (empty($address) && empty($port)) { if (empty($address) && empty($port)) {
+10 -2
View File
@@ -9,6 +9,7 @@ declare(strict_types=1);
namespace HttpServer\Exception; namespace HttpServer\Exception;
use JetBrains\PhpStorm\Pure;
use Throwable; use Throwable;
/** /**
@@ -17,8 +18,15 @@ use Throwable;
*/ */
class AuthException extends \Exception class AuthException extends \Exception
{ {
public function __construct($message = "", $code = 0, Throwable $previous = NULL)
/**
* AuthException constructor.
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
#[Pure] public function __construct($message = "", $code = 0, Throwable $previous = NULL)
{ {
parent::__construct($message, 7000, $previous); parent::__construct($message, 7000, $previous);
} }
+2 -1
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace HttpServer\Exception; namespace HttpServer\Exception;
use JetBrains\PhpStorm\Pure;
use Throwable; use Throwable;
/** /**
@@ -19,7 +20,7 @@ class ExitException extends \Exception
* @param int $code * @param int $code
* @param Throwable|null $previous * @param Throwable|null $previous
*/ */
public function __construct($message = "", $code = 0, Throwable $previous = null) #[Pure] public function __construct($message = "", $code = 0, Throwable $previous = null)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
+3 -3
View File
@@ -145,10 +145,10 @@ class Context extends BaseContext
} }
/** /**
* @param $id * @param string $id
* @param null $key * @param string|null $key
*/ */
public static function deleteId($id, $key = null) public static function deleteId(string $id,string $key = null)
{ {
if (!static::hasContext($id, $key)) { if (!static::hasContext($id, $key)) {
return; return;
+2 -1
View File
@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace HttpServer\Http\Formatter; namespace HttpServer\Http\Formatter;
use Exception;
use Snowflake\Core\JSON; use Snowflake\Core\JSON;
use HttpServer\Application; use HttpServer\Application;
use Swoole\Http\Response; use Swoole\Http\Response;
@@ -32,7 +33,7 @@ class HtmlFormatter extends Application implements IFormatter
/** /**
* @param $context * @param $context
* @return $this * @return $this
* @throws \Exception * @throws Exception
*/ */
public function send($context): static public function send($context): static
{ {
+2 -2
View File
@@ -49,9 +49,9 @@ class XmlFormatter extends Application implements IFormatter
} }
/** /**
* @return mixed * @return string|null
*/ */
public function getData(): mixed public function getData(): ?string
{ {
$data = $this->data; $data = $this->data;
$this->clear(); $this->clear();
+38 -35
View File
@@ -6,7 +6,10 @@ namespace HttpServer\Http;
use Exception; use Exception;
use HttpServer\Application; use HttpServer\Application;
use HttpServer\IInterface\AuthIdentity; use HttpServer\IInterface\AuthIdentity;
use JetBrains\PhpStorm\Pure;
use ReflectionException;
use Snowflake\Core\JSON; use Snowflake\Core\JSON;
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use function router; use function router;
@@ -77,7 +80,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function isFavicon() public function isFavicon(): bool
{ {
return $this->getUri() === 'favicon.ico'; return $this->getUri() === 'favicon.ico';
} }
@@ -85,7 +88,7 @@ class Request extends Application
/** /**
* @return mixed * @return mixed
*/ */
public function getIdentity() public function getIdentity(): mixed
{ {
return $this->_grant; return $this->_grant;
} }
@@ -93,7 +96,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function isHead() public function isHead(): bool
{ {
$result = $this->headers->getHeader('request_method') == 'head'; $result = $this->headers->getHeader('request_method') == 'head';
if ($result) { if ($result) {
@@ -108,7 +111,7 @@ class Request extends Application
* @param $status * @param $status
* @return mixed * @return mixed
*/ */
public function setStatus($status) public function setStatus($status): mixed
{ {
return $this->statusCode = $status; return $this->statusCode = $status;
} }
@@ -116,7 +119,7 @@ class Request extends Application
/** /**
* @return int * @return int
*/ */
public function getStatus() public function getStatus(): int
{ {
return $this->statusCode; return $this->statusCode;
} }
@@ -124,7 +127,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function getIsPackage() public function getIsPackage(): bool
{ {
return $this->headers->getHeader('request_method') == 'package'; return $this->headers->getHeader('request_method') == 'package';
} }
@@ -132,7 +135,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function getIsReceive() public function getIsReceive(): bool
{ {
return $this->headers->getHeader('request_method') == 'receive'; return $this->headers->getHeader('request_method') == 'receive';
} }
@@ -150,7 +153,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function hasGrant() public function hasGrant(): bool
{ {
return $this->_grant !== null; return $this->_grant !== null;
} }
@@ -159,7 +162,7 @@ class Request extends Application
/** /**
* @return string * @return string
*/ */
public function parseUri() public function parseUri(): string
{ {
$array = []; $array = [];
$explode = explode('/', $this->headers->getHeader('request_uri')); $explode = explode('/', $this->headers->getHeader('request_uri'));
@@ -175,15 +178,15 @@ class Request extends Application
/** /**
* @return string[] * @return string[]
*/ */
public function getExplode() public function getExplode(): array
{ {
return $this->explode; return $this->explode;
} }
/** /**
* @return mixed|string * @return string
*/ */
public function getCurrent() #[Pure] public function getCurrent(): string
{ {
return current($this->explode); return current($this->explode);
} }
@@ -191,7 +194,7 @@ class Request extends Application
/** /**
* @return string * @return string
*/ */
public function getUri() public function getUri(): string
{ {
if (!$this->headers) { if (!$this->headers) {
return 'command exec.'; return 'command exec.';
@@ -207,10 +210,10 @@ class Request extends Application
/** /**
* @return mixed|string * @return mixed
* @throws Exception * @throws ComponentException
*/ */
public function adapter() public function adapter(): mixed
{ {
if (!$this->isHead()) { if (!$this->isHead()) {
return router()->dispatch(); return router()->dispatch();
@@ -222,7 +225,7 @@ class Request extends Application
/** /**
* @return string|null * @return string|null
*/ */
public function getPlatform() public function getPlatform(): ?string
{ {
$user = $this->headers->getHeader('user-agent'); $user = $this->headers->getHeader('user-agent');
$match = preg_match('/\(.*\)?/', $user, $output); $match = preg_match('/\(.*\)?/', $user, $output);
@@ -245,7 +248,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function isIos() public function isIos(): bool
{ {
return $this->getPlatform() == static::PLATFORM_IPHONE; return $this->getPlatform() == static::PLATFORM_IPHONE;
} }
@@ -253,7 +256,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function isAndroid() public function isAndroid(): bool
{ {
return $this->getPlatform() == static::PLATFORM_ANDROID; return $this->getPlatform() == static::PLATFORM_ANDROID;
} }
@@ -261,7 +264,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function isMacOs() public function isMacOs(): bool
{ {
return $this->getPlatform() == static::PLATFORM_MAC_OX; return $this->getPlatform() == static::PLATFORM_MAC_OX;
} }
@@ -269,7 +272,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function isWindows() public function isWindows(): bool
{ {
return $this->getPlatform() == static::PLATFORM_WINDOWS; return $this->getPlatform() == static::PLATFORM_WINDOWS;
} }
@@ -277,7 +280,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function getIsPost() public function getIsPost(): bool
{ {
return $this->getMethod() == 'post'; return $this->getMethod() == 'post';
} }
@@ -286,7 +289,7 @@ class Request extends Application
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function getIsHttp() public function getIsHttp(): bool
{ {
return true; return true;
} }
@@ -294,7 +297,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function getIsOption() public function getIsOption(): bool
{ {
return $this->getMethod() == 'options'; return $this->getMethod() == 'options';
} }
@@ -302,7 +305,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function getIsGet() public function getIsGet(): bool
{ {
return $this->getMethod() == 'get'; return $this->getMethod() == 'get';
} }
@@ -310,7 +313,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function getIsDelete() public function getIsDelete(): bool
{ {
return $this->getMethod() == 'delete'; return $this->getMethod() == 'delete';
} }
@@ -320,7 +323,7 @@ class Request extends Application
* *
* 获取请求类型 * 获取请求类型
*/ */
public function getMethod() public function getMethod(): string
{ {
$method = $this->headers->get('request_method'); $method = $this->headers->get('request_method');
if (empty($method)) { if (empty($method)) {
@@ -332,7 +335,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function getIsCli() public function getIsCli(): bool
{ {
return $this->isCli === TRUE; return $this->isCli === TRUE;
} }
@@ -357,7 +360,7 @@ class Request extends Application
/** /**
* @return mixed|null * @return mixed|null
*/ */
public function getIp() #[Pure] public function getIp()
{ {
$headers = $this->headers->getHeaders(); $headers = $this->headers->getHeaders();
if (!empty($headers['x-forwarded-for'])) return $headers['x-forwarded-for']; if (!empty($headers['x-forwarded-for'])) return $headers['x-forwarded-for'];
@@ -369,7 +372,7 @@ class Request extends Application
/** /**
* @return string * @return string
*/ */
public function getRuntime() #[Pure] public function getRuntime(): string
{ {
return sprintf('%.5f', microtime(TRUE) - $this->startTime); return sprintf('%.5f', microtime(TRUE) - $this->startTime);
} }
@@ -377,7 +380,7 @@ class Request extends Application
/** /**
* @return string * @return string
*/ */
public function getDebug() public function getDebug(): string
{ {
$mainstay = sprintf("%.6f", microtime(true)); // 带毫秒的时间戳 $mainstay = sprintf("%.6f", microtime(true)); // 带毫秒的时间戳
@@ -402,7 +405,7 @@ class Request extends Application
* @param $router * @param $router
* @return bool * @return bool
*/ */
public function is($router) public function is($router): bool
{ {
return $this->getUri() == trim($router, '/'); return $this->getUri() == trim($router, '/');
} }
@@ -410,7 +413,7 @@ class Request extends Application
/** /**
* @return bool * @return bool
*/ */
public function isNotFound() public function isNotFound(): bool
{ {
return JSON::to(404, 'Page ' . $this->getUri() . ' not found.'); return JSON::to(404, 'Page ' . $this->getUri() . ' not found.');
} }
@@ -419,10 +422,10 @@ class Request extends Application
/** /**
* @param $request * @param $request
* @return mixed * @return mixed
* @throws \ReflectionException * @throws ReflectionException
* @throws NotFindClassException * @throws NotFindClassException
*/ */
public static function create($request) public static function create($request): Request
{ {
$sRequest = Context::setContext('request', Snowflake::createObject(Request::class)); $sRequest = Context::setContext('request', Snowflake::createObject(Request::class));
$sRequest->fd = $request->fd; $sRequest->fd = $request->fd;
-257
View File
@@ -1,257 +0,0 @@
<?php
declare(strict_types=1);
namespace HttpServer\Route\Annotation;
use HttpServer\IInterface\After;
use HttpServer\IInterface\Interceptor;
use HttpServer\IInterface\Limits;
use HttpServer\Route\Node;
use ReflectionClass;
use ReflectionException;
use Snowflake\Annotation\Annotation;
use Snowflake\Snowflake;
/**
* Class Annotation
*/
class Http extends Annotation
{
const HTTP_EVENT = 'http:event:';
const CLOSE = 'Close';
/**
* @var string
* @Interceptor(LoginInterceptor)
*/
private string $Interceptor = 'required|not empty';
/**
* @var string
*/
private string $Limits = 'required|not empty';
private string $Method = 'post';
private string $Middleware = '';
private string $After = '';
protected array $_annotations = [];
/**
* @param Node $node
* @param ReflectionClass $reflect
* @param $method
* @param $annotations
* @throws ReflectionException
*/
public function read(Node $node, ReflectionClass $reflect, $method, $annotations)
{
$method = $reflect->getMethod($method);
$_annotations = $this->getDocCommentAnnotation($annotations, $method->getDocComment());
foreach ($_annotations as $keyName => $annotation) {
if (!in_array($keyName, $annotations)) {
continue;
}
$this->bind($keyName, $node, $annotation);
}
}
/**
* @param $keyName
* @param $node
* @param $annotation
*/
private function bind($keyName, $node, $annotation)
{
switch ($keyName) {
case 'Method':
$this->bindMethod($node, $annotation);
break;
case'Interceptor':
$this->bindInterceptors($node, $annotation);
break;
case 'Middleware':
$this->bindMiddleware($node, $annotation);
break;
case 'Limits':
$this->bindLimits($node, $annotation);
break;
case 'After':
$this->bindAfter($node, $annotation);
break;
}
}
/**
* @param $node
* @param $annotation
*/
private function bindMethod($node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
if (in_array('any', $explode)) {
$explode = ['*'];
}
$node->method = $explode;
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindMiddleware(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\Middleware\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$node->addMiddleware($middleware);
}
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindInterceptors(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\Interceptor\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$middleware = Snowflake::createObject($middleware);
if (!($middleware instanceof Interceptor)) {
continue;
}
$node->addInterceptor([$middleware, 'Interceptor']);
}
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindAfter(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\After\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$middleware = Snowflake::createObject($middleware);
if (!($middleware instanceof After)) {
continue;
}
$node->addAfter([$middleware, 'onHandler']);
}
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindLimits(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\Limits\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$middleware = Snowflake::createObject($middleware);
if (!($middleware instanceof Limits)) {
continue;
}
$node->addLimits([$middleware, 'next']);
}
}
/**
* @param $controller
* @param $methodName
* @param $events
* @return array|void
* @throws
*/
public function createHandler($controller, $methodName, $events)
{
return Snowflake::createObject($events[2]);
}
/**
* @param $events
* @return bool
*/
public function isLegitimate($events)
{
return isset($events[2]) && !empty($events[2]);
}
/**
* @param $name
* @param $comment
* @return false|string
*/
public function getName($name, $comment = [])
{
$prefix = self::HTTP_EVENT . ltrim($name, ':');
if (isset($comment[2]) && !empty($comment[2])) {
return $prefix . ':' . $comment[2];
}
return $prefix;
}
}
-62
View File
@@ -1,62 +0,0 @@
<?php
declare(strict_types=1);
namespace HttpServer\Route\Annotation;
use Snowflake\Annotation\Annotation;
/**
* Class Tcp
* @package HttpServer\Route\Annotation
*/
class Tcp extends Annotation
{
const CONNECT = 'Connect';
const PACKET = 'Packet';
const RECEIVE = 'Receive';
const CLOSE = 'Close';
private string $Message = 'required|not empty';
/**
* @param $controller
* @param $methodName
* @param $events
* @return array
*/
public function createHandler($controller, $methodName, $events)
{
return [$controller, $methodName];
}
/**
* @param $events
* @return bool|void
*/
public function isLegitimate($events)
{
return true;
}
/**
* @param $events
* @param $comment
* @return false|string
*/
public function getName($events, $comment = [])
{
$prefix = 'TCP:ANNOTATION:' . ltrim($events, ':');
if (isset($comment[2]) && !empty($comment[2])) {
return $prefix . ':' . $comment[2];
}
return $prefix;
}
}
-65
View File
@@ -1,65 +0,0 @@
<?php
declare(strict_types=1);
namespace HttpServer\Route\Annotation;
use Snowflake\Annotation\Annotation;
/**
* Class Websocket
* @package Snowflake\Annotation
*/
class Websocket extends Annotation
{
const MESSAGE = 'Message';
const HANDSHAKE = 'Handshake';
const CLOSE = 'Close';
private string $Message = 'required|not empty';
private string $Handshake;
private string $Close;
/**
* @param $controller
* @param $methodName
* @param $events
* @return array
*/
public function createHandler($controller, $methodName, $events)
{
return [$controller, $methodName];
}
/**
* @param $events
* @return bool|void
*/
public function isLegitimate($events)
{
return true;
}
/**
* @param $events
* @param $comment
* @return false|string
*/
public function getName($events, $comment = [])
{
$prefix = 'WEBSOCKET:ANNOTATION:' . ltrim($events, ':');
if (isset($comment[2]) && !empty($comment[2])) {
return $prefix . ':' . $comment[2];
}
return $prefix;
}
}
+2 -2
View File
@@ -12,7 +12,7 @@ namespace HttpServer\Route;
class Any class Any
{ {
private $nodes = []; private array $nodes = [];
/** /**
* Any constructor. * Any constructor.
@@ -29,7 +29,7 @@ class Any
* @param $arguments * @param $arguments
* @return $this * @return $this
*/ */
public function __call($name, $arguments) public function __call($name, $arguments): static
{ {
foreach ($this->nodes as $node) { foreach ($this->nodes as $node) {
$node->{$name}(...$arguments); $node->{$name}(...$arguments);
+7 -7
View File
@@ -32,7 +32,7 @@ class Filter extends Application
* @return BodyFilter|bool * @return BodyFilter|bool
* @throws Exception * @throws Exception
*/ */
public function setBody(array $value) public function setBody(array $value): bool|BodyFilter
{ {
if (empty($value)) { if (empty($value)) {
return true; return true;
@@ -52,7 +52,7 @@ class Filter extends Application
* @return HeaderFilter|bool * @return HeaderFilter|bool
* @throws Exception * @throws Exception
*/ */
public function setHeader(array $value) public function setHeader(array $value): HeaderFilter|bool
{ {
if (empty($value)) { if (empty($value)) {
return true; return true;
@@ -72,7 +72,7 @@ class Filter extends Application
* @return QueryFilter|bool * @return QueryFilter|bool
* @throws Exception * @throws Exception
*/ */
public function setQuery(array $value) public function setQuery(array $value): QueryFilter|bool
{ {
if (empty($value)) { if (empty($value)) {
return true; return true;
@@ -90,7 +90,7 @@ class Filter extends Application
/** /**
* @throws Exception * @throws Exception
*/ */
public function handler() public function handler(): bool
{ {
if (($error = $this->filters()) !== true) { if (($error = $this->filters()) !== true) {
throw new FilterException($error); throw new FilterException($error);
@@ -104,7 +104,7 @@ class Filter extends Application
/** /**
* @return bool * @return bool
*/ */
private function filters() private function filters(): bool
{ {
if (empty($this->_filters)) { if (empty($this->_filters)) {
return true; return true;
@@ -118,9 +118,9 @@ class Filter extends Application
} }
/** /**
* @return bool|mixed * @return mixed
*/ */
private function grant() private function grant(): mixed
{ {
if (!is_callable($this->grant, true)) { if (!is_callable($this->grant, true)) {
return true; return true;
+1 -1
View File
@@ -18,7 +18,7 @@ class BodyFilter extends Filter
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function check() public function check(): bool
{ {
return $this->validator(); return $this->validator();
} }
+1 -1
View File
@@ -27,7 +27,7 @@ abstract class Filter extends Application
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
protected function validator() protected function validator(): bool
{ {
$validator = Validator::getInstance(); $validator = Validator::getInstance();
$validator->setParams($this->params); $validator->setParams($this->params);
+9 -1
View File
@@ -5,12 +5,20 @@ declare(strict_types=1);
namespace HttpServer\Route\Filter; namespace HttpServer\Route\Filter;
use JetBrains\PhpStorm\Pure;
use Throwable; use Throwable;
class FilterException extends \Exception class FilterException extends \Exception
{ {
public function __construct($message = "", $code = 0, Throwable $previous = null)
/**
* FilterException constructor.
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
#[Pure] public function __construct($message = "", $code = 0, Throwable $previous = null)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
+1 -1
View File
@@ -18,7 +18,7 @@ class HeaderFilter extends Filter
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function check() public function check(): bool
{ {
return $this->validator(); return $this->validator();
} }
+1 -1
View File
@@ -18,7 +18,7 @@ class QueryFilter extends Filter
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function check() public function check(): bool
{ {
return $this->validator(); return $this->validator();
} }
+4 -2
View File
@@ -7,6 +7,7 @@ namespace HttpServer\Route;
use Exception; use Exception;
use HttpServer\Application; use HttpServer\Application;
use Snowflake\Exception\ConfigException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
/** /**
@@ -43,9 +44,10 @@ class Handler extends Application
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return Handler * @return Handler|Node|null
* @throws ConfigException
*/ */
public function handler($route, $handler) public function handler($route, $handler): Handler|Node|null
{ {
return $this->router->addRoute($route, $handler, 'receive'); return $this->router->addRoute($route, $handler, 'receive');
} }
-1
View File
@@ -15,7 +15,6 @@ use Annotation\Route\Middleware as RMiddleware;
use Exception; use Exception;
use Annotation\Route\Limits; use Annotation\Route\Limits;
use HttpServer\Route\Dispatch\Dispatch; use HttpServer\Route\Dispatch\Dispatch;
use Snowflake\Core\JSON;
use Snowflake\Snowflake; use Snowflake\Snowflake;
/** /**
+26 -34
View File
@@ -5,18 +5,14 @@ namespace HttpServer\Route;
use Closure; use Closure;
use Exception; use Exception;
use HttpServer\Exception\ExitException;
use HttpServer\Http\Context;
use HttpServer\Http\Request; use HttpServer\Http\Request;
use HttpServer\IInterface\RouterInterface; use HttpServer\IInterface\RouterInterface;
use HttpServer\Application; use HttpServer\Application;
use HttpServer\Route\Annotation\Http; use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Core\JSON;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException; use Snowflake\Exception\ConfigException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine;
defined('ROUTER_TREE') or define('ROUTER_TREE', 1); defined('ROUTER_TREE') or define('ROUTER_TREE', 1);
defined('ROUTER_HASH') or define('ROUTER_HASH', 2); defined('ROUTER_HASH') or define('ROUTER_HASH', 2);
@@ -42,8 +38,6 @@ class Router extends Application implements RouterInterface
public bool $useTree = false; public bool $useTree = false;
private bool $reading = false;
/** /**
* @param Closure $middleware * @param Closure $middleware
@@ -115,7 +109,7 @@ class Router extends Application implements RouterInterface
* @param $path * @param $path
* @return string * @return string
*/ */
private function resolve($path) #[Pure] private function resolve($path): string
{ {
$paths = array_column($this->groupTacks, 'prefix'); $paths = array_column($this->groupTacks, 'prefix');
if (empty($paths)) { if (empty($paths)) {
@@ -182,10 +176,10 @@ class Router extends Application implements RouterInterface
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return mixed * @return Node|null
* @throws ConfigException * @throws ConfigException
*/ */
public function socket($route, $handler): mixed public function socket($route, $handler): ?Node
{ {
return $this->addRoute($route, $handler, 'socket'); return $this->addRoute($route, $handler, 'socket');
} }
@@ -205,10 +199,10 @@ class Router extends Application implements RouterInterface
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return mixed|Node|null * @return Node|null
* @throws * @throws ConfigException
*/ */
public function get($route, $handler) public function get($route, $handler): ?Node
{ {
return $this->addRoute($route, $handler, 'get'); return $this->addRoute($route, $handler, 'get');
} }
@@ -219,7 +213,7 @@ class Router extends Application implements RouterInterface
* @return mixed|Node|null * @return mixed|Node|null
* @throws * @throws
*/ */
public function options($route, $handler) public function options($route, $handler): ?Node
{ {
return $this->addRoute($route, $handler, 'options'); return $this->addRoute($route, $handler, 'options');
} }
@@ -240,8 +234,9 @@ class Router extends Application implements RouterInterface
* @param $route * @param $route
* @param $handler * @param $handler
* @return Any * @return Any
* @throws ConfigException
*/ */
public function any($route, $handler) public function any($route, $handler): Any
{ {
$nodes = []; $nodes = [];
foreach (['get', 'post', 'options', 'put', 'delete'] as $method) { foreach (['get', 'post', 'options', 'put', 'delete'] as $method) {
@@ -253,10 +248,10 @@ class Router extends Application implements RouterInterface
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return mixed|Node|null * @return Node|null
* @throws * @throws ConfigException
*/ */
public function delete($route, $handler) public function delete($route, $handler): ?Node
{ {
return $this->addRoute($route, $handler, 'delete'); return $this->addRoute($route, $handler, 'delete');
} }
@@ -264,10 +259,10 @@ class Router extends Application implements RouterInterface
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return mixed|Node|null * @return Node|null
* @throws * @throws ConfigException
*/ */
public function put($route, $handler) public function put($route, $handler): ?Node
{ {
return $this->addRoute($route, $handler, 'put'); return $this->addRoute($route, $handler, 'put');
} }
@@ -380,7 +375,7 @@ class Router extends Application implements RouterInterface
* @return array * @return array
* '*' * '*'
*/ */
public function split($path) public function split($path): array
{ {
$prefix = $this->addPrefix(); $prefix = $this->addPrefix();
$path = ltrim($path, '/'); $path = ltrim($path, '/');
@@ -403,7 +398,7 @@ class Router extends Application implements RouterInterface
/** /**
* @return array * @return array
*/ */
public function each() public function each(): array
{ {
$paths = []; $paths = [];
foreach ($this->nodes as $node) { foreach ($this->nodes as $node) {
@@ -427,7 +422,7 @@ class Router extends Application implements RouterInterface
* @param array $returns * @param array $returns
* @return array * @return array
*/ */
private function readByArray($array, $returns = []) private function readByArray($array, $returns = []): array
{ {
foreach ($array as $value) { foreach ($array as $value) {
if (empty($value)) { if (empty($value)) {
@@ -450,7 +445,7 @@ class Router extends Application implements RouterInterface
* @param string $paths * @param string $paths
* @return array * @return array
*/ */
private function readByChild($child, $paths = '') private function readByChild($child, $paths = ''): array
{ {
$newPath = []; $newPath = [];
/** @var Node $item */ /** @var Node $item */
@@ -490,11 +485,10 @@ class Router extends Application implements RouterInterface
/** /**
* @param $exception * @param $exception
* @return false|int|mixed|string * @return mixed
* @throws ComponentException * @throws ComponentException
* @throws Exception
*/ */
private function exception($exception) private function exception($exception): mixed
{ {
return Snowflake::app()->getLogger()->exception($exception); return Snowflake::app()->getLogger()->exception($exception);
} }
@@ -502,10 +496,10 @@ class Router extends Application implements RouterInterface
/** /**
* @param Request $request * @param Request $request
* @return Node|false|int|mixed|string|null * @return Node|null 树干搜索
* 树干搜索 * 树干搜索
*/ */
private function find_path(Request $request) private function find_path(Request $request): ?Node
{ {
$method = $request->getMethod(); $method = $request->getMethod();
if (!isset($this->nodes[$method])) { if (!isset($this->nodes[$method])) {
@@ -545,7 +539,7 @@ class Router extends Application implements RouterInterface
* @param $request * @param $request
* @return Node|null * @return Node|null
*/ */
private function search_options($request) private function search_options($request): ?Node
{ {
$method = $request->getMethod(); $method = $request->getMethod();
if (!isset($this->nodes[$method])) { if (!isset($this->nodes[$method])) {
@@ -563,7 +557,7 @@ class Router extends Application implements RouterInterface
* @return Node|null * @return Node|null
* 树杈搜索 * 树杈搜索
*/ */
private function Branch_search($request) private function Branch_search($request): ?Node
{ {
$node = $this->tree_search($request->getExplode(), $request->getMethod()); $node = $this->tree_search($request->getExplode(), $request->getMethod());
if ($node instanceof Node) { if ($node instanceof Node) {
@@ -596,7 +590,6 @@ class Router extends Application implements RouterInterface
private function loadRouteDir($path) private function loadRouteDir($path)
{ {
$files = glob($path . '/*'); $files = glob($path . '/*');
$this->reading = true;
for ($i = 0; $i < count($files); $i++) { for ($i = 0; $i < count($files); $i++) {
if (is_dir($files[$i])) { if (is_dir($files[$i])) {
$this->loadRouteDir($files[$i]); $this->loadRouteDir($files[$i]);
@@ -604,7 +597,6 @@ class Router extends Application implements RouterInterface
$this->loadRouterFile($files[$i]); $this->loadRouterFile($files[$i]);
} }
} }
$this->reading = false;
} }
+4 -7
View File
@@ -9,8 +9,6 @@ use HttpServer\Events\OnConnect;
use HttpServer\Events\OnPacket; use HttpServer\Events\OnPacket;
use HttpServer\Events\OnReceive; use HttpServer\Events\OnReceive;
use HttpServer\Events\OnRequest; use HttpServer\Events\OnRequest;
use HttpServer\Route\Annotation\Http as AnnotationHttp;
use HttpServer\Route\Annotation\Tcp;
use HttpServer\Service\Http; use HttpServer\Service\Http;
use HttpServer\Service\Receive; use HttpServer\Service\Receive;
use HttpServer\Service\Packet; use HttpServer\Service\Packet;
@@ -22,7 +20,6 @@ use Snowflake\Event;
use Snowflake\Exception\ConfigException; use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use HttpServer\Route\Annotation\Websocket as AWebsocket;
use Swoole\Runtime; use Swoole\Runtime;
/** /**
@@ -111,21 +108,21 @@ class Server extends Application
/** /**
* @return void * @return string start server
* *
* start server * start server
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function start() public function start(): string
{ {
$configs = Config::get('servers', true); $configs = Config::get('servers', true);
Snowflake::clearWorkerId(); Snowflake::clearWorkerId();
$baseServer = $this->initCore($configs); $baseServer = $this->initCore($configs);
if (!$baseServer) { if (!$baseServer) {
return; return 'ok';
} }
$baseServer->start(); return $baseServer->start();
} }
+3 -3
View File
@@ -43,11 +43,11 @@ trait Server
/** /**
* @return mixed|void * @return mixed
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
public function onHandlerListener() public function onHandlerListener(): mixed
{ {
$this->on('WorkerStop', $this->createHandler('workerStop')); $this->on('WorkerStop', $this->createHandler('workerStop'));
$this->on('WorkerExit', $this->createHandler('workerExit')); $this->on('WorkerExit', $this->createHandler('workerExit'));
@@ -83,7 +83,7 @@ trait Server
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
protected function createHandler($eventName) protected function createHandler($eventName): array
{ {
$classPrefix = 'HttpServer\Events\On' . ucfirst($eventName); $classPrefix = 'HttpServer\Events\On' . ucfirst($eventName);
if (!class_exists($classPrefix)) { if (!class_exists($classPrefix)) {
+1 -1
View File
@@ -16,7 +16,7 @@ interface ConsumerInterface
* @param Struct $struct * @param Struct $struct
* @return mixed * @return mixed
*/ */
public function onHandler(Struct $struct); public function onHandler(Struct $struct): mixed;
} }
+1 -1
View File
@@ -144,7 +144,7 @@ class Kafka extends \Snowflake\Process\Process
* @param $kafka * @param $kafka
* @return array * @return array
*/ */
private function kafkaConfig($kafka) private function kafkaConfig($kafka): array
{ {
$conf = new Conf(); $conf = new Conf();
$conf->setRebalanceCb([$this, 'rebalanced_cb']); $conf->setRebalanceCb([$this, 'rebalanced_cb']);
+15 -10
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Kafka; namespace Kafka;
use Exception;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -17,10 +18,10 @@ class Logger implements LoggerInterface
/** /**
* @param string $message * @param mixed $message
* @param array $context * @param array $context
*/ */
public function emergency($message, array $context = array()) public function emergency(mixed $message, array $context = array())
{ {
// TODO: Implement emergency() method. // TODO: Implement emergency() method.
var_dump(func_get_args()); var_dump(func_get_args());
@@ -30,14 +31,15 @@ class Logger implements LoggerInterface
* @param string $message * @param string $message
* @param array $context * @param array $context
* @throws ComponentException * @throws ComponentException
* @throws Exception
*/ */
public function alert($message, array $context = array()) public function alert(mixed $message, array $context = array())
{ {
$logger = Snowflake::app()->getLogger(); $logger = Snowflake::app()->getLogger();
$logger->debug($message); $logger->debug($message);
} }
public function critical($message, array $context = array()) public function critical(mixed $message, array $context = array())
{ {
// TODO: Implement critical() method. // TODO: Implement critical() method.
var_dump(func_get_args()); var_dump(func_get_args());
@@ -47,8 +49,9 @@ class Logger implements LoggerInterface
* @param string $message * @param string $message
* @param array $context * @param array $context
* @throws ComponentException * @throws ComponentException
* @throws Exception
*/ */
public function error($message, array $context = array()) public function error(mixed $message, array $context = array())
{ {
$logger = Snowflake::app()->getLogger(); $logger = Snowflake::app()->getLogger();
$logger->error($message); $logger->error($message);
@@ -59,7 +62,7 @@ class Logger implements LoggerInterface
* @param array $context * @param array $context
* @throws ComponentException * @throws ComponentException
*/ */
public function warning($message, array $context = array()) public function warning(mixed $message, array $context = array())
{ {
$logger = Snowflake::app()->getLogger(); $logger = Snowflake::app()->getLogger();
$logger->warning($message); $logger->warning($message);
@@ -70,7 +73,7 @@ class Logger implements LoggerInterface
* @param array $context * @param array $context
* @throws ComponentException * @throws ComponentException
*/ */
public function notice($message, array $context = array()) public function notice(mixed $message, array $context = array())
{ {
$logger = Snowflake::app()->getLogger(); $logger = Snowflake::app()->getLogger();
$logger->info($message); $logger->info($message);
@@ -81,7 +84,7 @@ class Logger implements LoggerInterface
* @param array $context * @param array $context
* @throws ComponentException * @throws ComponentException
*/ */
public function info($message, array $context = array()) public function info(mixed $message, array $context = array())
{ {
$logger = Snowflake::app()->getLogger(); $logger = Snowflake::app()->getLogger();
$logger->info($message); $logger->info($message);
@@ -91,8 +94,9 @@ class Logger implements LoggerInterface
* @param string $message * @param string $message
* @param array $context * @param array $context
* @throws ComponentException * @throws ComponentException
* @throws Exception
*/ */
public function debug($message, array $context = array()) public function debug(mixed $message, array $context = array())
{ {
$logger = Snowflake::app()->getLogger(); $logger = Snowflake::app()->getLogger();
$logger->debug($message); $logger->debug($message);
@@ -103,8 +107,9 @@ class Logger implements LoggerInterface
* @param $message * @param $message
* @param array $context * @param array $context
* @throws ComponentException * @throws ComponentException
* @throws Exception
*/ */
public function log($level, $message, array $context = array()) public function log($level, mixed $message, array $context = array())
{ {
$logger = Snowflake::app()->getLogger(); $logger = Snowflake::app()->getLogger();
$logger->debug($message); $logger->debug($message);
+2 -2
View File
@@ -51,7 +51,7 @@ class Producer extends Component
* @param $servers * @param $servers
* @return Producer * @return Producer
*/ */
public function setBrokers(string $servers) public function setBrokers(string $servers): static
{ {
$this->conf->set('metadata.broker.list', $servers); $this->conf->set('metadata.broker.list', $servers);
return $this; return $this;
@@ -62,7 +62,7 @@ class Producer extends Component
* @param $servers * @param $servers
* @return Producer * @return Producer
*/ */
public function setTopic(string $servers) public function setTopic(string $servers): static
{ {
$this->_topic = $servers; $this->_topic = $servers;
return $this; return $this;
-157
View File
@@ -1,157 +0,0 @@
<?php
declare(strict_types=1);
namespace Snowflake\Abstracts;
use Exception;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
/**
* Class BaseAnnotation
* @package Snowflake\Snowflake\Annotation\Base
*/
abstract class BaseAnnotation extends Component
{
/**
* @param ReflectionClass $reflect
* @param string $method
* @param array $annotations
* @return array
* @throws ReflectionException
* @throws Exception
*/
public function instance(ReflectionClass $reflect, $method = '', $annotations = [])
{
$classMethods = $reflect->getMethods(ReflectionMethod::IS_PUBLIC);
if (!$reflect->isInstantiable()) {
throw new Exception('Class ' . $reflect->getName() . ' cannot be instantiated.');
}
$array = [];
$object = $reflect->newInstance();
if (!empty($method)) {
$array = $this->resolveDocComment($reflect->getMethod($method), $object, $annotations, $array);
} else {
foreach ($classMethods as $classMethod) {
$array = $this->resolveDocComment($classMethod, $object, $annotations, $array);
}
}
return $array;
}
/**
* @param ReflectionMethod $function
* @param $object
* @param $annotations
* @param $array
* @return array
* @throws
*/
protected function resolveDocComment(ReflectionMethod $function, $object, $annotations, $array)
{
$comment = $function->getDocComment();
$array = $this->getDocCommentAnnotation($annotations, $comment);
foreach ($array as $name => $annotation) {
foreach ($annotation as $index => $events) {
if (!isset($events[1])) {
continue;
}
if (!($_key = $this->getName($name, $events))) {
continue;
}
if (isset($item[2])) {
$handler = Snowflake::createObject($events[2]);
} else {
$handler = [$object, $events[1]];
}
if (!isset($array[$annotation])) {
$array[$annotation] = [];
}
$array[$name][] = [$_key, $handler];
}
}
return $array;
}
/**
* @param $object
* @param $events
* @throws NotFindClassException
* @throws ReflectionException
*/
protected function getOrCreate($object, $events)
{
if (isset($item[2])) {
$handler = Snowflake::createObject($events[2]);
} else {
$handler = [$object, $events[1]];
}
}
/**
* @param $annotations
* @param $comment
* @return array
*/
protected function getDocCommentAnnotation($annotations, $comment)
{
$array = [];
foreach ($annotations as $annotation) {
if (!$comment) {
continue;
}
preg_match('/@(' . $annotation . ')\((.*?)\)/', $comment, $events);
if (!isset($events[1])) {
continue;
}
if (!isset($array[$annotation])) {
$array[$annotation] = [];
}
$array[$annotation] = [$annotation, $events];
}
return $array;
}
/**
* @param $rule
* @param $content
* @param $rules
* @return bool
* @throws ReflectionException
* @throws NotFindClassException
* @throws Exception
*/
public function check($rule, $content, $rules)
{
if (empty($rule)) {
return true;
}
$explode = explode('|', $rule);
foreach ($explode as $value) {
$reflect = array_merge($rules[$value], [
'value' => $content
]);
$validator = Snowflake::createObject($reflect);
if (!$validator->check()) {
throw new Exception($validator->getMessage());
}
}
return false;
}
abstract public function runWith($path);
}

Some files were not shown because too many files have changed in this diff Show More