diff --git a/Annotation/Annotation.php b/Annotation/Annotation.php index 3ea59f99..74314bbd 100644 --- a/Annotation/Annotation.php +++ b/Annotation/Annotation.php @@ -7,6 +7,7 @@ namespace Annotation; use ReflectionAttribute; use ReflectionClass; use ReflectionException; +use ReflectionMethod; use Snowflake\Abstracts\Component; use Snowflake\Snowflake; @@ -104,7 +105,7 @@ class Annotation extends Component $reflect = $this->reflectClass($class); if ($reflect->isInstantiable()) { $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); $this->_classes[$reflect->getName()][$method->getName()] = $tmp; diff --git a/Database/ActiveQuery.php b/Database/ActiveQuery.php index 33b93ba1..0167073a 100644 --- a/Database/ActiveQuery.php +++ b/Database/ActiveQuery.php @@ -6,6 +6,7 @@ * Time: 14:42 */ declare(strict_types=1); + namespace Database; use Snowflake\Abstracts\Component; @@ -86,7 +87,7 @@ class ActiveQuery extends Component * @param $value * @return $this */ - public function addParam($key, $value) + public function addParam($key, $value): static { $this->attributes[$key] = $value; return $this; @@ -96,7 +97,7 @@ class ActiveQuery extends Component * @param array $values * @return $this */ - public function addParams(array $values) + public function addParams(array $values): static { foreach ($values as $key => $val) { $this->addParam($key, $val); @@ -108,7 +109,7 @@ class ActiveQuery extends Component * @param $name * @return $this */ - public function with($name) + public function with($name): static { if (empty($name)) { return $this; @@ -126,17 +127,17 @@ class ActiveQuery extends Component * @param bool $isArray * @return $this */ - public function asArray($isArray = TRUE) + public function asArray($isArray = TRUE): static { $this->asArray = $isArray; return $this; } /** - * @return ActiveRecord - * @throws + * @return ActiveRecord|array|null + * @throws Exception */ - public function first() + public function first(): ActiveRecord|array|null { $data = $this->modelClass::getDb() ->createCommand($this->oneLimit()->queryBuilder()) @@ -156,7 +157,7 @@ class ActiveQuery extends Component /** * @return array|Collection */ - public function get() + public function get(): Collection|array { return $this->all(); } @@ -165,7 +166,7 @@ class ActiveQuery extends Component /** * @throws Exception */ - public function flush() + public function flush(): array|bool|int|string|null { $sql = $this->getChange()->truncate($this->getTable()); return $this->command($sql)->flush(); @@ -178,7 +179,7 @@ class ActiveQuery extends Component * @return Pagination * @throws Exception */ - public function page(int $size, callable $callback) + public function page(int $size, callable $callback): Pagination { $pagination = new Pagination($this); $pagination->setOffset(0); @@ -194,7 +195,7 @@ class ActiveQuery extends Component * @return array|null * @throws Exception */ - public function column(string $field, $setKey = '') + public function column(string $field, $setKey = ''): ?array { return $this->all()->column($field, $setKey); } @@ -203,7 +204,7 @@ class ActiveQuery extends Component * @return array|Collection * @throws */ - public function all() + public function all(): Collection|array { $collect = new Collection($this, $this->modelClass::getDb() ->createCommand($this->queryBuilder()) @@ -220,7 +221,7 @@ class ActiveQuery extends Component * @return ActiveRecord * @throws Exception */ - public function populate(ActiveRecord $model, $data) + public function populate(ActiveRecord $model, $data): ActiveRecord { return $this->getWith($model::populate($data)); } @@ -230,7 +231,7 @@ class ActiveQuery extends Component * @param $model * @return mixed */ - public function getWith($model) + public function getWith($model): mixed { if (empty($this->with) || !is_array($this->with)) { return $model; @@ -249,7 +250,7 @@ class ActiveQuery extends Component * @return int * @throws Exception */ - public function count() + public function count(): int { $data = $this->modelClass::getDb() ->createCommand($this->getBuild()->count($this)) @@ -266,7 +267,7 @@ class ActiveQuery extends Component * @return array|Command|bool|int|string * @throws Exception */ - public function batchUpdate(array $data) + public function batchUpdate(array $data): Command|array|bool|int|string { return $this->getDb()->createCommand() ->batchUpdate($this->getTable(), $data, $this->getCondition()) @@ -278,7 +279,7 @@ class ActiveQuery extends Component * @return bool * @throws Exception */ - public function batchInsert(array $data) + public function batchInsert(array $data): bool { return $this->getDb()->createCommand() ->batchInsert($this->getTable(), $data) @@ -301,7 +302,7 @@ class ActiveQuery extends Component * @return bool * @throws Exception */ - public function exists() + public function exists(): bool { $column = $this->modelClass::getDb() ->createCommand($this->queryBuilder()) @@ -309,31 +310,23 @@ class ActiveQuery extends Component return $column !== false; } + /** * @return bool * @throws Exception */ - public function deleteAll() + public function delete(): bool { return $this->modelClass::getDb() ->createCommand($this->queryBuilder()) ->delete(); } - /** - * @return bool - * @throws Exception - */ - public function delete() - { - return $this->deleteAll(); - } - /** * @return string * @throws Exception */ - public function getCondition() + public function getCondition(): string { return $this->getBuild()->getWhere($this->where); } @@ -342,7 +335,7 @@ class ActiveQuery extends Component * @return string * @throws Exception */ - public function queryBuilder() + public function queryBuilder(): string { return $this->getBuild()->getQuery($this); } @@ -353,7 +346,7 @@ class ActiveQuery extends Component * @return Command * @throws Exception */ - private function command($sql, $attr = []) + private function command($sql, $attr = []): Command { if (!empty($attr) && is_array($attr)) { $attr = array_merge($this->attributes, $attr); @@ -368,7 +361,7 @@ class ActiveQuery extends Component * @return Select * @throws Exception */ - public function getBuild() + public function getBuild(): Select { return $this->getDb()->getSchema()->getQueryBuilder(); } @@ -377,7 +370,7 @@ class ActiveQuery extends Component * @return orm\Change * @throws Exception */ - public function getChange() + public function getChange(): orm\Change { return $this->getDb()->getSchema()->getChange(); } @@ -386,7 +379,7 @@ class ActiveQuery extends Component * @return Connection * @throws Exception */ - public function getDb() + public function getDb(): Connection { return $this->modelClass::getDb(); } @@ -395,7 +388,7 @@ class ActiveQuery extends Component * @return mixed * @throws Exception */ - public function getPrimary() + public function getPrimary(): mixed { return $this->modelClass->getPrimary(); } diff --git a/Database/ActiveRecord.php b/Database/ActiveRecord.php index e3b9e015..62e63c61 100644 --- a/Database/ActiveRecord.php +++ b/Database/ActiveRecord.php @@ -14,6 +14,7 @@ use Exception; use Database\Base\BaseActiveRecord; use Snowflake\Core\ArrayAccess; use Snowflake\Error\Logger; +use Snowflake\Exception\ComponentException; use Snowflake\Snowflake; defined('SAVE_FAIL') or define('SAVE_FAIL', 3227); @@ -37,7 +38,7 @@ class ActiveRecord extends BaseActiveRecord /** * @return array */ - public function rules() + public function rules(): array { return []; } @@ -48,7 +49,7 @@ class ActiveRecord extends BaseActiveRecord * @return ActiveRecord|false * @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])) { return false; @@ -64,7 +65,7 @@ class ActiveRecord extends BaseActiveRecord * @return ActiveRecord|false * @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])) { return false; @@ -79,7 +80,7 @@ class ActiveRecord extends BaseActiveRecord * @return ActiveRecord|false * @throws Exception */ - public function increments(array $columns) + public function increments(array $columns): bool|static { if (!$this->mathematics(self::INCR, $columns)) { return false; @@ -96,7 +97,7 @@ class ActiveRecord extends BaseActiveRecord * @return ActiveRecord|false * @throws Exception */ - public function decrements(array $columns) + public function decrements(array $columns): bool|static { if (!$this->mathematics(self::DECR, $columns)) { return false; @@ -108,12 +109,13 @@ class ActiveRecord extends BaseActiveRecord } /** - * @param $attributes - * @param $condition - * @return bool|ActiveRecord|mixed + * @param array $condition + * @param array $attributes + * @return mixed + * @throws ComponentException * @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(); if (!empty($select)) { @@ -138,7 +140,7 @@ class ActiveRecord extends BaseActiveRecord * @return array|bool|int|string|null * @throws Exception */ - private function mathematics($action, $columns, $condition = []) + private function mathematics($action, $columns, $condition = []): int|bool|array|string|null { if (empty($condition)) { $condition = [$this->getPrimary() => $this->getPrimaryValue()]; @@ -155,7 +157,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool * @throws Exception */ - public static function incrAll($column, $value, $condition = []) + public static function incrAll($column, $value, $condition = []): bool { return static::getDb()->createCommand() ->mathematics(self::getTable(), [self::INCR => [$column, $value]], $condition) @@ -170,7 +172,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool * @throws Exception */ - public static function decrAll($column, $value, $condition = []) + public static function decrAll($column, $value, $condition = []): bool { return static::getDb()->createCommand() ->mathematics(self::getTable(), [self::DECR => [$column, $value]], $condition) @@ -183,7 +185,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool * @throws */ - public function update(array $attributes) + public function update(array $attributes): bool { return $this->save($attributes); } @@ -194,7 +196,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool|static * @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->attributes = $params; @@ -223,7 +225,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool * @throws Exception */ - public function delete() + public function delete(): bool { $conditions = $this->_oldAttributes; if (empty($conditions)) { @@ -253,7 +255,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool * @throws Exception */ - public static function batchUpdate($condition, $attributes = []) + public static function batchUpdate($condition, $attributes = []): bool { $condition = static::find()->where($condition); return $condition->batchUpdate($attributes); @@ -263,10 +265,10 @@ class ActiveRecord extends BaseActiveRecord * @param $condition * @param array $attributes * - * @return array|mixed|null|Collection + * @return array|Collection * @throws Exception */ - public static function findAll($condition, $attributes = []) + public static function findAll($condition, $attributes = []): array|Collection { $query = static::find()->where($condition); if (!empty($attributes)) { @@ -277,10 +279,10 @@ class ActiveRecord extends BaseActiveRecord /** * @param $data - * @return array|mixed + * @return mixed * @throws Exception */ - private function resolveObject($data) + private function resolveObject($data): mixed { if (is_numeric($data) || !is_string($data)) { return $data; @@ -303,10 +305,10 @@ class ActiveRecord extends BaseActiveRecord /** - * @return array|mixed + * @return array * @throws Exception */ - public function toArray() + public function toArray(): array { $data = []; foreach ($this->_attributes as $key => $val) { @@ -319,7 +321,7 @@ class ActiveRecord extends BaseActiveRecord * @return array * @throws Exception */ - private function runRelate() + private function runRelate(): array { $relates = []; if (empty($this->_relate)) { @@ -333,13 +335,13 @@ class ActiveRecord extends BaseActiveRecord /** - * @param $modelName + * @param string $modelName * @param $foreignKey * @param $localKey - * @return mixed|ActiveQuery + * @return HasOne * @throws Exception */ - public function hasOne(string $modelName, $foreignKey, $localKey) + public function hasOne(string $modelName, $foreignKey, $localKey): HasOne { if (!$this->has($localKey)) { throw new Exception("Need join table primary key."); @@ -357,10 +359,10 @@ class ActiveRecord extends BaseActiveRecord * @param $modelName * @param $foreignKey * @param $localKey - * @return mixed|ActiveQuery + * @return HasCount * @throws Exception */ - public function hasCount($modelName, $foreignKey, $localKey) + public function hasCount($modelName, $foreignKey, $localKey): HasCount { if (!$this->has($localKey)) { throw new Exception("Need join table primary key."); @@ -378,10 +380,10 @@ class ActiveRecord extends BaseActiveRecord * @param $modelName * @param $foreignKey * @param $localKey - * @return mixed|ActiveQuery + * @return HasMany * @throws Exception */ - public function hasMany($modelName, $foreignKey, $localKey) + public function hasMany($modelName, $foreignKey, $localKey): HasMany { if (!$this->has($localKey)) { throw new Exception("Need join table primary key."); @@ -398,10 +400,10 @@ class ActiveRecord extends BaseActiveRecord * @param $modelName * @param $foreignKey * @param $localKey - * @return mixed|ActiveQuery + * @return HasMany * @throws Exception */ - public function hasIn($modelName, $foreignKey, $localKey) + public function hasIn($modelName, $foreignKey, $localKey): HasMany { if (!$this->has($localKey)) { throw new Exception("Need join table primary key."); @@ -418,7 +420,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool * @throws Exception */ - public function afterDelete() + public function afterDelete(): bool { if (!$this->hasPrimary()) { return TRUE; @@ -434,7 +436,7 @@ class ActiveRecord extends BaseActiveRecord * @return bool * @throws Exception */ - public function beforeDelete() + public function beforeDelete(): bool { if (!$this->hasPrimary()) { return TRUE; diff --git a/Database/Base/AbstractCollection.php b/Database/Base/AbstractCollection.php index becb6a52..17b5b922 100644 --- a/Database/Base/AbstractCollection.php +++ b/Database/Base/AbstractCollection.php @@ -12,6 +12,8 @@ namespace Database\Base; use ArrayIterator; use Database\ActiveQuery; +use JetBrains\PhpStorm\Pure; +use ReflectionException; use Snowflake\Abstracts\Component; use Database\ActiveRecord; use Snowflake\Exception\NotFindClassException; @@ -53,7 +55,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat /** * @return int */ - public function getLength(): int + #[Pure] public function getLength(): int { return count($this->_item); } @@ -86,7 +88,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat /** * @return Traversable|CollectionIterator|ArrayIterator - * @throws \ReflectionException + * @throws ReflectionException * @throws NotFindClassException */ public function getIterator(): Traversable|CollectionIterator|ArrayIterator diff --git a/Database/Base/BaseActiveRecord.php b/Database/Base/BaseActiveRecord.php index 86940a3e..8cfe2f3b 100644 --- a/Database/Base/BaseActiveRecord.php +++ b/Database/Base/BaseActiveRecord.php @@ -11,6 +11,7 @@ namespace Database\Base; use HttpServer\Http\Context; +use ReflectionException; use Snowflake\Abstracts\Component; use Snowflake\Core\JSON; use Database\ActiveQuery; @@ -23,6 +24,7 @@ use Database\Relation; use Snowflake\Error\Logger; use Exception; use Snowflake\Exception\ComponentException; +use Snowflake\Exception\NotFindClassException; use validator\Validator; use Database\IOrm; use Snowflake\Snowflake; @@ -181,7 +183,7 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess * @return null|string * @throws Exception */ - public function getPrimaryValue() + public function getPrimaryValue(): ?string { if (!$this->hasPrimary()) { return null; @@ -190,14 +192,14 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess } /** - * @param $condition + * @param $param * @param $db * @return $this * @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(); if (empty($primary)) { throw new Exception('Primary key cannot be empty.'); @@ -205,9 +207,9 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess if (is_array($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 - * @throws + * @return ActiveQuery + * @throws ReflectionException + * @throws NotFindClassException */ - public static function find() + public static function find():ActiveQuery { return Snowflake::createObject(ActiveQuery::class, [get_called_class()]); } @@ -250,19 +253,19 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess * @return bool * @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 (!$if_condition_is_null) { return false; } - return static::find()->deleteAll(); + return static::find()->delete(); } $model = static::find()->ifNotWhere($if_condition_is_null)->where($condition); if (!empty($attributes)) { $model->bindParams($attributes); } - return $model->deleteAll(); + return $model->delete(); } @@ -659,10 +662,10 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess /** * @param $name - * @return mixed|null + * @return mixed * @throws Exception */ - public function __get($name) + public function __get($name): mixed { $method = 'get' . ucfirst($name); if (method_exists($this, $method . 'Attribute')) { @@ -780,7 +783,7 @@ abstract class BaseActiveRecord extends Component implements IOrm, \ArrayAccess * @return mixed * @throws Exception */ - public static function setDatabaseConnect($bsName) + public static function setDatabaseConnect($bsName): Connection { return Snowflake::app()->db->get($bsName); } diff --git a/Database/Collection.php b/Database/Collection.php index 35ab7fcc..2f814acc 100644 --- a/Database/Collection.php +++ b/Database/Collection.php @@ -6,6 +6,7 @@ * Time: 13:38 */ declare(strict_types=1); + namespace Database; use Database\Base\AbstractCollection; @@ -35,7 +36,7 @@ class Collection extends AbstractCollection * @return array|null * @throws Exception */ - public function values($field) + public function values($field): ?array { if (empty($field) || !is_string($field)) { return NULL; @@ -53,7 +54,7 @@ class Collection extends AbstractCollection * @param string $field * @return array|null */ - public function keyBy(string $field) + public function keyBy(string $field): ?array { $array = $this->toArray(); $column = array_flip(array_column($array, $field)); @@ -67,7 +68,7 @@ class Collection extends AbstractCollection /** * @return $this */ - public function orderRand() + public function orderRand(): static { shuffle($this->_item); return $this; @@ -79,7 +80,7 @@ class Collection extends AbstractCollection * * @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)) { return []; @@ -97,7 +98,7 @@ class Collection extends AbstractCollection * * @return array|null */ - public function column($field, $setKey = '') + public function column($field, $setKey = ''): ?array { $data = $this->toArray(); if (empty($data)) { @@ -115,7 +116,7 @@ class Collection extends AbstractCollection * * @return float|int|null */ - public function sum($field) + public function sum($field): float|int|null { $array = $this->column($field); 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); } @@ -135,7 +136,7 @@ class Collection extends AbstractCollection /** * @return int */ - public function size() + #[Pure] public function size(): int { return (int)count($this->_item); } @@ -144,7 +145,7 @@ class Collection extends AbstractCollection * @return array * @throws */ - public function toArray() + public function toArray(): array { $array = []; foreach ($this as $value) { @@ -161,7 +162,7 @@ class Collection extends AbstractCollection * @throws Exception * 批量删除 */ - public function delete() + public function delete(): bool { $model = $this->model; if (!$model->hasPrimary()) { @@ -177,7 +178,7 @@ class Collection extends AbstractCollection } return $this->model::find() ->in($model->getPrimary(), $ids) - ->deleteAll(); + ->delete(); } /** @@ -185,7 +186,7 @@ class Collection extends AbstractCollection * @return Collection * @throws */ - public function filter(array $condition) + public function filter(array $condition): Collection|static { $_filters = []; if (empty($condition)) { @@ -207,7 +208,7 @@ class Collection extends AbstractCollection * @return bool * @throws Exception */ - private function filterCheck($value, $condition) + private function filterCheck($value, $condition): bool { $_value = $value; if ($_value instanceof ActiveRecord) { @@ -224,9 +225,9 @@ class Collection extends AbstractCollection /** * @param $key * @param $value - * @return ActiveRecord|mixed|null + * @return mixed */ - public function exists($key, $value) + public function exists($key, $value): mixed { foreach ($this as $item) { if ($item->$key === $value) { @@ -239,7 +240,7 @@ class Collection extends AbstractCollection /** * @return bool */ - public function isEmpty() + #[Pure] public function isEmpty(): bool { return $this->size() < 1; } diff --git a/Database/Command.php b/Database/Command.php index b120e7d5..df2ae2b7 100644 --- a/Database/Command.php +++ b/Database/Command.php @@ -43,10 +43,10 @@ class Command extends Component /** - * @return bool|PDOStatement - * @throws + * @return array|bool|int|string|PDOStatement|null + * @throws Exception */ - public function incrOrDecr() + public function incrOrDecr(): array|bool|int|string|PDOStatement|null { return $this->execute(static::EXECUTE); } @@ -54,10 +54,10 @@ class Command extends Component /** * @param bool $isInsert * @param bool $hasAutoIncrement - * @return bool|string - * @throws + * @return int|bool|array|string|null + * @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); } @@ -70,7 +70,7 @@ class Command extends Component * @return Command * @throws Exception */ - public function update($model, $attributes, $condition, $param) + public function update($model, $attributes, $condition, $param): Command { $change = $this->db->getSchema()->getChange(); $sql = $change->update($model, $attributes, $condition, $param); @@ -85,7 +85,7 @@ class Command extends Component * @return Command * @throws Exception */ - public function batchUpdate($tableName, $attributes, $condition) + public function batchUpdate($tableName, $attributes, $condition): Command { $change = $this->db->getSchema()->getChange(); [$sql, $param] = $change->batchUpdate($tableName, $attributes, $condition); @@ -99,7 +99,7 @@ class Command extends Component * @return Command * @throws Exception */ - public function batchInsert($tableName, $attributes) + public function batchInsert($tableName, $attributes): Command { $change = $this->db->getSchema()->getChange(); $attribute_key = array_keys(current($attributes)); @@ -114,7 +114,7 @@ class Command extends Component * @return Command * @throws Exception */ - public function insert($tableName, $attributes, $param) + public function insert($tableName, $attributes, $param): Command { $change = $this->db->getSchema()->getChange(); $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 */ - public function all() + public function all(): int|bool|array|string|null { return $this->execute(static::FETCH_ALL); } @@ -137,7 +137,7 @@ class Command extends Component * @return Command * @throws Exception */ - public function mathematics($tableName, $param, $condition) + public function mathematics($tableName, $param, $condition): static { $change = $this->db->getSchema()->getChange(); $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 */ - public function one() + public function one(): null|array|bool|int|string { return $this->execute(static::FETCH); } /** - * @return bool|int + * @return int|bool|array|string|null * @throws Exception */ - public function fetchColumn() + public function fetchColumn(): int|bool|array|string|null { return $this->execute(static::FETCH_COLUMN); } /** - * @return bool|int + * @return int|bool|array|string|null * @throws Exception */ - public function rowCount() + public function rowCount(): int|bool|array|string|null { return $this->execute(static::ROW_COUNT); } /** - * @return bool|int + * @return int|bool|array|string|null * @throws Exception */ - public function flush() + public function flush(): int|bool|array|string|null { return $this->execute(static::EXECUTE); } /** * @param $type - * @param $isInsert - * @param $hasAutoIncrement - * @return bool|int + * @param null $isInsert + * @param bool $hasAutoIncrement + * @return int|bool|array|string|null * @throws Exception */ - private function execute($type, $isInsert = null, $hasAutoIncrement = true) + private function execute($type, $isInsert = null, $hasAutoIncrement = true): int|bool|array|string|null { try { $time = microtime(true); @@ -211,10 +211,10 @@ class Command extends Component /** * @param $type - * @return array|int|mixed + * @return mixed * @throws Exception */ - private function search($type) + private function search($type): mixed { $connect = $this->db->getConnect($this->sql); if (!($connect instanceof PDO)) { @@ -239,7 +239,7 @@ class Command extends Component * @return bool|string * @throws Exception */ - private function insert_or_change($isInsert, $hasAutoIncrement) + private function insert_or_change($isInsert, $hasAutoIncrement): bool|string { if (!($connection = $this->initPDOStatement())) { return false; @@ -262,7 +262,7 @@ class Command extends Component * 重新构建 * @throws */ - private function initPDOStatement() + private function initPDOStatement(): PDO|bool|null { if (empty($this->sql)) { return null; @@ -281,7 +281,7 @@ class Command extends Component * @param $modelName * @return $this */ - public function setModelName($modelName) + public function setModelName($modelName): static { $this->_modelName = $modelName; return $this; @@ -290,25 +290,25 @@ class Command extends Component /** * @return string */ - public function getModelName() + public function getModelName(): string { return $this->_modelName; } /** - * @return bool|int + * @return int|bool|array|string|null * @throws Exception */ - public function delete() + public function delete(): int|bool|array|string|null { return $this->execute(static::EXECUTE); } /** - * @return bool|int + * @return int|bool|array|string|null * @throws Exception */ - public function exec() + public function exec(): int|bool|array|string|null { return $this->execute(static::EXECUTE); } @@ -317,7 +317,7 @@ class Command extends Component * @param array|null $data * @return $this */ - public function bindValues(array $data = NULL) + public function bindValues(array $data = NULL): static { if (!is_array($this->params)) { $this->params = []; @@ -333,7 +333,7 @@ class Command extends Component * @return $this * @throws Exception */ - public function setSql($sql) + public function setSql($sql): static { $this->sql = $sql; return $this; @@ -342,7 +342,7 @@ class Command extends Component /** * @return string */ - public function getError() + public function getError(): string { return $this->prepare->errorInfo()[2] ?? 'Db 驱动错误.'; } diff --git a/Database/Condition/ArrayCondition.php b/Database/Condition/ArrayCondition.php index f0c1aa97..3d7245ad 100644 --- a/Database/Condition/ArrayCondition.php +++ b/Database/Condition/ArrayCondition.php @@ -7,6 +7,7 @@ namespace Database\Condition; use Database\ActiveQuery; use Database\Base\ConditionClassMap; use Exception; +use JetBrains\PhpStorm\Pure; use Snowflake\Core\Str; use Snowflake\Snowflake; @@ -23,7 +24,7 @@ class ArrayCondition extends Condition * @return mixed * @throws Exception */ - public function builder() + public function builder(): mixed { if ($this->value instanceof Condition) { return $this->value->builder(); @@ -58,7 +59,7 @@ class ArrayCondition extends Condition * @param $value * @return bool */ - private function isMath($value) + #[Pure] private function isMath($value): bool { return isset($value[0]) && in_array($value[0], $this->math); } @@ -68,7 +69,7 @@ class ArrayCondition extends Condition * @return mixed * @throws Exception */ - public function buildOperaCondition($value) + public function buildOperaCondition(array $value): mixed { [$option['opera'], $option['column'], $option['value']] = $value; $strPer = strtoupper($option['opera']); @@ -79,7 +80,7 @@ class ArrayCondition extends Condition } $option = array_merge($option, $class); } else if ($value instanceof ActiveQuery) { - $option['value'] = $value->adaptation(); + $option['value'] = $value->getBuild()->getQuery($value); $option['class'] = ChildCondition::class; } else { $option['class'] = DefaultCondition::class; @@ -94,7 +95,7 @@ class ArrayCondition extends Condition * @param $value * @return string */ - public function buildHashCondition($key, $value) + public function buildHashCondition($key, $value): string { return $this->resolve($key, $value); } diff --git a/Database/Condition/BetweenCondition.php b/Database/Condition/BetweenCondition.php index eba201ab..db9120fd 100644 --- a/Database/Condition/BetweenCondition.php +++ b/Database/Condition/BetweenCondition.php @@ -15,7 +15,7 @@ class BetweenCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { return $this->column . ' BETWEEN ' . $this->value[0] . ' AND ' . $this->value[1]; } diff --git a/Database/Condition/ChildCondition.php b/Database/Condition/ChildCondition.php index 5e758b50..7280750c 100644 --- a/Database/Condition/ChildCondition.php +++ b/Database/Condition/ChildCondition.php @@ -14,7 +14,7 @@ class ChildCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { return $this->column . ' ' . $this->opera . ' (' . $this->value . ')'; } diff --git a/Database/Condition/Condition.php b/Database/Condition/Condition.php index 863685bb..e8521a74 100644 --- a/Database/Condition/Condition.php +++ b/Database/Condition/Condition.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Database\Condition; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\BaseObject; use Snowflake\Core\Str; @@ -66,7 +67,7 @@ abstract class Condition extends BaseObject * $query->ANDWhere('id', '=', 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) { return ''; @@ -83,7 +84,7 @@ abstract class Condition extends BaseObject $explode = explode('(', $columns); $explode = array_shift($explode); - if (strpos($explode, ' ') !== false) { + if (str_contains($explode, ' ')) { $explode = explode(' ', $explode)[0]; } if (!in_array(trim($explode), static::INT_TYPE)) { @@ -97,9 +98,9 @@ abstract class Condition extends BaseObject /** * @param array|null $param - * @return array + * @return array|null */ - protected function format(?array $param) + protected function format(?array $param): ?array { if (!is_array($param)) { return null; @@ -126,7 +127,7 @@ abstract class Condition extends BaseObject * @param string $oprea * @return string */ - public function typeBuilder($column, $value = null, $oprea = '=') + #[Pure] public function typeBuilder($column, $value = null, $oprea = '='): string { if (is_numeric($value)) { if ($value != (int)$value) { diff --git a/Database/Condition/DefaultCondition.php b/Database/Condition/DefaultCondition.php index 51173c87..12e2559e 100644 --- a/Database/Condition/DefaultCondition.php +++ b/Database/Condition/DefaultCondition.php @@ -14,7 +14,7 @@ class DefaultCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { return $this->resolve($this->column, $this->value, $this->opera); } diff --git a/Database/Condition/HashCondition.php b/Database/Condition/HashCondition.php index 3c59abcb..c4bacea7 100644 --- a/Database/Condition/HashCondition.php +++ b/Database/Condition/HashCondition.php @@ -12,7 +12,7 @@ class HashCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { $array = []; if (empty($this->value)) { diff --git a/Database/Condition/InCondition.php b/Database/Condition/InCondition.php index 7f599730..a1a2c6ef 100644 --- a/Database/Condition/InCondition.php +++ b/Database/Condition/InCondition.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Database\Condition; use Database\ActiveQuery; +use Exception; /** * Class InCondition @@ -15,9 +16,9 @@ class InCondition extends Condition /** * @return string - * @throws \Exception + * @throws Exception */ - public function builder() + public function builder(): string { if ($this->value instanceof ActiveQuery) { $this->value = $this->value->getBuild()->getQuery($this->value); diff --git a/Database/Condition/LLikeCondition.php b/Database/Condition/LLikeCondition.php index 78830a32..96c0bf3c 100644 --- a/Database/Condition/LLikeCondition.php +++ b/Database/Condition/LLikeCondition.php @@ -17,7 +17,7 @@ class LLikeCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { if (!is_string($this->value)) { $this->value = array_shift($this->value); diff --git a/Database/Condition/LikeCondition.php b/Database/Condition/LikeCondition.php index 3ed15b85..9e64bacf 100644 --- a/Database/Condition/LikeCondition.php +++ b/Database/Condition/LikeCondition.php @@ -17,7 +17,7 @@ class LikeCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { if (!is_string($this->value)) { $this->value = array_shift($this->value); diff --git a/Database/Condition/MathematicsCondition.php b/Database/Condition/MathematicsCondition.php index e2bf2819..b5c45ca0 100644 --- a/Database/Condition/MathematicsCondition.php +++ b/Database/Condition/MathematicsCondition.php @@ -15,7 +15,7 @@ class MathematicsCondition extends Condition /** * @return mixed */ - public function builder() + public function builder(): mixed { return $this->{strtolower($this->type)}((float)$this->value); } @@ -24,7 +24,7 @@ class MathematicsCondition extends Condition * @param $value * @return string */ - public function eq($value) + public function eq($value): string { return $this->column . ' = ' . $value; } @@ -33,7 +33,7 @@ class MathematicsCondition extends Condition * @param $value * @return string */ - public function neq($value) + public function neq($value): string { return $this->column . ' <> ' . $value; } @@ -42,7 +42,7 @@ class MathematicsCondition extends Condition * @param $value * @return string */ - public function gt($value) + public function gt($value): string { return $this->column . ' > ' . $value; } @@ -51,7 +51,7 @@ class MathematicsCondition extends Condition * @param $value * @return string */ - public function egt($value) + public function egt($value): string { return $this->column . ' >= ' . $value; } @@ -61,7 +61,7 @@ class MathematicsCondition extends Condition * @param $value * @return string */ - public function lt($value) + public function lt($value): string { return $this->column . ' < ' . $value; } @@ -70,7 +70,7 @@ class MathematicsCondition extends Condition * @param $value * @return string */ - public function elt($value) + public function elt($value): string { return $this->column . ' <= ' . $value; } diff --git a/Database/Condition/NotBetweenCondition.php b/Database/Condition/NotBetweenCondition.php index 5f21cfbc..4b3b9152 100644 --- a/Database/Condition/NotBetweenCondition.php +++ b/Database/Condition/NotBetweenCondition.php @@ -14,7 +14,7 @@ class NotBetweenCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { return $this->column . ' NOT BETWEEN ' . $this->value[0] . ' AND ' . $this->value[1]; } diff --git a/Database/Condition/NotInCondition.php b/Database/Condition/NotInCondition.php index 5601f8d2..acffcab4 100644 --- a/Database/Condition/NotInCondition.php +++ b/Database/Condition/NotInCondition.php @@ -14,7 +14,7 @@ class NotInCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { $format = array_filter($this->format($this->value)); diff --git a/Database/Condition/NotLikeCondition.php b/Database/Condition/NotLikeCondition.php index 55197636..20cfc8b4 100644 --- a/Database/Condition/NotLikeCondition.php +++ b/Database/Condition/NotLikeCondition.php @@ -17,7 +17,7 @@ class NotLikeCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { if (!is_string($this->value)) { $this->value = array_shift($this->value); diff --git a/Database/Condition/OrCondition.php b/Database/Condition/OrCondition.php index b2fc6dc1..24c1014e 100644 --- a/Database/Condition/OrCondition.php +++ b/Database/Condition/OrCondition.php @@ -15,7 +15,7 @@ class OrCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { return 'OR ' . $this->resolve($this->column, $this->value, $this->opera); } diff --git a/Database/Condition/RLikeCondition.php b/Database/Condition/RLikeCondition.php index 14088b5f..d6f920fd 100644 --- a/Database/Condition/RLikeCondition.php +++ b/Database/Condition/RLikeCondition.php @@ -17,7 +17,7 @@ class RLikeCondition extends Condition /** * @return string */ - public function builder() + public function builder(): string { if (!is_string($this->value)) { $this->value = array_shift($this->value); diff --git a/Database/Connection.php b/Database/Connection.php index a578ab76..1bea5168 100644 --- a/Database/Connection.php +++ b/Database/Connection.php @@ -11,6 +11,8 @@ declare(strict_types=1); namespace Database; +use JetBrains\PhpStorm\Pure; +use ReflectionException; use Snowflake\Abstracts\Component; use Database\Mysql\Schema; use Database\Orm\Select; @@ -18,6 +20,7 @@ use Exception; use PDO; use Snowflake\Event; use Snowflake\Exception\ComponentException; +use Snowflake\Exception\NotFindClassException; use Snowflake\Snowflake; /** @@ -92,7 +95,7 @@ class Connection extends Component * @return PDO * @throws Exception */ - public function getConnect($sql = NULL) + public function getConnect($sql = NULL): PDO { $connections = Snowflake::app()->connections; $connections->initConnections($this->cds, true, $this->maxNumber); @@ -119,7 +122,7 @@ class Connection extends Component * @return PDO * @throws Exception */ - private function getPdo($sql) + private function getPdo($sql): PDO { if ($this->isWrite($sql)) { $connect = $this->masterInstance(); @@ -130,10 +133,11 @@ class Connection extends Component } /** - * @return mixed|object|Schema - * @throws Exception + * @return mixed + * @throws ReflectionException + * @throws NotFindClassException */ - public function getSchema() + public function getSchema(): mixed { if ($this->_schema === null) { $this->_schema = Snowflake::createObject([ @@ -148,7 +152,7 @@ class Connection extends Component * @param $sql * @return bool */ - public function isWrite($sql) + #[Pure] public function isWrite($sql): bool { if (empty($sql)) return false; @@ -158,10 +162,10 @@ class Connection extends Component } /** - * @return mixed|null + * @return mixed * @throws ComponentException */ - public function getCacheDriver() + public function getCacheDriver(): mixed { if (!$this->enableCache) { return null; @@ -173,7 +177,7 @@ class Connection extends Component * @return PDO * @throws Exception */ - public function masterInstance() + public function masterInstance(): PDO { $config = [ 'cds' => $this->cds, @@ -188,7 +192,7 @@ class Connection extends Component * @return PDO * @throws Exception */ - public function slaveInstance() + public function slaveInstance(): PDO { if (empty($this->slaveConfig)) { return $this->masterInstance(); @@ -203,7 +207,7 @@ class Connection extends Component * @return $this * @throws Exception */ - public function beginTransaction() + public function beginTransaction(): static { $connections = Snowflake::app()->connections; $connections->beginTransaction($this->cds); @@ -214,7 +218,7 @@ class Connection extends Component * @return $this|bool * @throws Exception */ - public function inTransaction() + public function inTransaction(): bool|static { $connections = Snowflake::app()->connections; return $connections->inTransaction($this->cds); @@ -227,7 +231,7 @@ class Connection extends Component public function rollback() { $connections = Snowflake::app()->connections; - return $connections->rollback($this->cds); + $connections->rollback($this->cds); } /** @@ -237,7 +241,7 @@ class Connection extends Component public function commit() { $connections = Snowflake::app()->connections; - return $connections->commit($this->cds); + $connections->commit($this->cds); } /** @@ -245,7 +249,7 @@ class Connection extends Component * @return PDO * @throws Exception */ - public function refresh($sql) + public function refresh($sql): PDO { if ($this->isWrite($sql)) { $instance = $this->masterInstance(); @@ -261,7 +265,7 @@ class Connection extends Component * @return Command * @throws */ - public function createCommand($sql = null, $attributes = []) + public function createCommand($sql = null, $attributes = []): Command { $command = new Command(['db' => $this, 'sql' => $sql]); return $command->bindValues($attributes); @@ -271,7 +275,7 @@ class Connection extends Component * @return Select * @throws Exception */ - public function getBuild() + public function getBuild(): Select { return $this->getSchema()->getQueryBuilder(); } diff --git a/Database/DatabasesProviders.php b/Database/DatabasesProviders.php index a3da9eb9..22977515 100644 --- a/Database/DatabasesProviders.php +++ b/Database/DatabasesProviders.php @@ -35,7 +35,7 @@ class DatabasesProviders extends Providers * @throws ConfigException * @throws Exception */ - public function get($name) + public function get($name): Connection { $application = Snowflake::app(); if ($application->has('databases.' . $name)) { @@ -87,10 +87,10 @@ class DatabasesProviders extends Providers /** * @param $name - * @return array|mixed|null + * @return mixed * @throws ConfigException */ - public function getConfig($name) + public function getConfig($name): mixed { return Config::get('databases.' . $name, true); } diff --git a/Database/Db.php b/Database/Db.php index 3797ed07..5fae723c 100644 --- a/Database/Db.php +++ b/Database/Db.php @@ -25,7 +25,7 @@ class Db /** * @return bool */ - public static function transactionsActive() + public static function transactionsActive(): bool { return static::$isActive; } @@ -65,7 +65,7 @@ class Db * * @return static */ - public static function table($table) + public static function table($table): Db|static { $db = new Db(); $db->from($table); @@ -77,7 +77,7 @@ class Db * @param string $alias * @return string */ - public static function any_value(string $column, string $alias = '') + public static function any_value(string $column, string $alias = ''): string { if (empty($alias)) { $alias = $column . '_any_value'; @@ -90,7 +90,7 @@ class Db * @return mixed * @throws Exception */ - public function get(Connection $db = NULL) + public function get(Connection $db = NULL): mixed { if (empty($db)) { $db = Snowflake::app()->database; @@ -104,17 +104,17 @@ class Db * @param $column * @return string */ - public static function raw($column) + public static function raw($column): string { return '`' . $column . '`'; } /** * @param Connection|null $db - * @return array|mixed + * @return mixed * @throws Exception */ - public function find(Connection $db = NULL) + public function find(Connection $db = NULL): mixed { if (empty($db)) { $db = Snowflake::app()->database; @@ -129,7 +129,7 @@ class Db * @return bool|int * @throws Exception */ - public function count(Connection $db = NULL) + public function count(Connection $db = NULL): bool|int { if (empty($db)) { $db = Snowflake::app()->database; @@ -144,7 +144,7 @@ class Db * @return bool|int * @throws Exception */ - public function exists(Connection $db = NULL) + public function exists(Connection $db = NULL): bool|int { if (empty($db)) { $db = Snowflake::app()->database; @@ -161,7 +161,7 @@ class Db * @return array|bool|int|string|null * @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(); } @@ -173,7 +173,7 @@ class Db * @return array|mixed * @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(); } @@ -183,7 +183,7 @@ class Db * @return array|null * @throws Exception */ - public function values(string $field) + public function values(string $field): ?array { $data = $this->get(); if (empty($data) || empty($field)) { @@ -198,10 +198,10 @@ class Db /** * @param $field - * @return array|mixed|null + * @return mixed * @throws Exception */ - public function value($field) + public function value($field): mixed { $data = $this->find(); if (!empty($field) && isset($data[$field])) { @@ -215,7 +215,7 @@ class Db * @return bool|int * @throws Exception */ - public function delete($db = null) + public function delete($db = null): bool|int { if (empty($db)) { $db = Snowflake::app()->database; @@ -232,7 +232,7 @@ class Db * @return bool|int * @throws Exception */ - public static function drop($table, $db = null) + public static function drop($table, $db = null): bool|int { if (empty($db)) { $db = Snowflake::app()->database; @@ -246,7 +246,7 @@ class Db * @return bool|int * @throws Exception */ - public static function truncate($table, $db = null) + public static function truncate($table, $db = null): bool|int { if (empty($db)) { @@ -259,10 +259,10 @@ class Db /** * @param $table * @param Connection|NULL $db - * @return array|mixed|null + * @return mixed * @throws Exception */ - public static function showCreateSql($table, Connection $db = NULL) + public static function showCreateSql($table, Connection $db = NULL): mixed { if (empty($db)) { @@ -283,7 +283,7 @@ class Db * @return bool|int|null * @throws Exception */ - public static function desc($table, Connection $db = NULL) + public static function desc($table, Connection $db = NULL): bool|int|null { if (empty($db)) { $db = Snowflake::app()->database; @@ -300,10 +300,10 @@ class Db /** * @param string $table * @param Connection|NULL $db - * @return array|mixed|null + * @return mixed * @throws Exception */ - public static function show(string $table, Connection $db = NULL) + public static function show(string $table, Connection $db = NULL): mixed { if (empty($table)) { return null; diff --git a/Database/HasBase.php b/Database/HasBase.php index e1c85d84..3af982af 100644 --- a/Database/HasBase.php +++ b/Database/HasBase.php @@ -21,15 +21,13 @@ abstract class HasBase { /** @var ActiveRecord|Collection */ - protected $data; + protected Collection|ActiveRecord $data; /** * @var IOrm */ protected IOrm $model; - /** @var */ - protected $primaryId; /** @var array */ protected array $value = []; @@ -46,7 +44,7 @@ abstract class HasBase * @param Relation $relation * @throws Exception */ - public function __construct(IOrm $model, $primaryId, $value, Relation $relation) + public function __construct(mixed $model, $primaryId, $value, Relation $relation) { if (!class_exists($model)) { throw new Exception('Model must implement ' . ActiveRecord::class); @@ -64,7 +62,6 @@ abstract class HasBase $this->_relation = $relation->bindIdentification($model, $_model); $this->model = $model; - $this->primaryId = $primaryId; $this->value = $value; } @@ -74,7 +71,7 @@ abstract class HasBase * @param $name * @return mixed */ - public function __get($name) + public function __get($name): mixed { if (empty($this->value)) { return null; diff --git a/Database/HasCount.php b/Database/HasCount.php index 3b5ce5f8..dc0cbd1d 100644 --- a/Database/HasCount.php +++ b/Database/HasCount.php @@ -18,7 +18,7 @@ class HasCount extends HasBase * @return $this * @throws Exception */ - public function __call($name, $arguments) + public function __call($name, $arguments): static { $this->_relation->getQuery($this->model::className())->$name(...$arguments); return $this; @@ -28,7 +28,7 @@ class HasCount extends HasBase * @return array|null|ActiveRecord * @throws Exception */ - public function get() + public function get(): array|ActiveRecord|null { return $this->_relation->count($this->model::className(), $this->value); } diff --git a/Database/HasMany.php b/Database/HasMany.php index bf8f868f..561fb70e 100644 --- a/Database/HasMany.php +++ b/Database/HasMany.php @@ -22,10 +22,10 @@ class HasMany extends HasBase /** * @param $name * @param $arguments - * @return mixed + * @return static * @throws Exception */ - public function __call($name, $arguments) + public function __call($name, $arguments): static { $this->_relation->getQuery($this->model::className())->$name(...$arguments); return $this; @@ -35,7 +35,7 @@ class HasMany extends HasBase * @return array|null|ActiveRecord * @throws Exception */ - public function get() + public function get(): array|ActiveRecord|null { return $this->_relation->get($this->model::className(), $this->value); } diff --git a/Database/HasOne.php b/Database/HasOne.php index 6230cc25..ac63aea7 100644 --- a/Database/HasOne.php +++ b/Database/HasOne.php @@ -24,7 +24,7 @@ class HasOne extends HasBase * @return $this * @throws Exception */ - public function __call($name, $arguments) + public function __call($name, $arguments): static { $this->_relation->getQuery($this->model::className())->$name(...$arguments); return $this; @@ -34,7 +34,7 @@ class HasOne extends HasBase * @return array|null|ActiveRecord * @throws Exception */ - public function get() + public function get(): array|ActiveRecord|null { return $this->_relation->first($this->model::className(), $this->value); } diff --git a/Database/IOrm.php b/Database/IOrm.php index 68342d74..2bb2a3fb 100644 --- a/Database/IOrm.php +++ b/Database/IOrm.php @@ -21,27 +21,27 @@ interface IOrm * @param null $db * @return ActiveRecord */ - public static function findOne($param, $db = NULL); + public static function findOne($param, $db = NULL): static; /** * @return string */ - public static function className(); + public static function className(): string; /** * @return ActiveQuery * return a sql queryBuilder */ - public static function find(); + public static function find(): ActiveQuery; /** * @param $dbName * @return Connection */ - public static function setDatabaseConnect($dbName); + public static function setDatabaseConnect($dbName): Connection; // public static function deleteAll($condition, $attributes); diff --git a/Database/Mysql/Columns.php b/Database/Mysql/Columns.php index 04357456..960fa5ea 100644 --- a/Database/Mysql/Columns.php +++ b/Database/Mysql/Columns.php @@ -11,6 +11,7 @@ declare(strict_types=1); namespace Database\Mysql; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\Component; use Database\Connection; use Exception; @@ -58,7 +59,7 @@ class Columns extends Component * @return $this * @throws Exception */ - public function table(string $table) + public function table(string $table): static { $this->structure($this->table = $table); return $this; @@ -67,7 +68,7 @@ class Columns extends Component /** * @return string */ - public function getTable() + public function getTable(): string { return $this->table; } @@ -75,10 +76,10 @@ class Columns extends Component /** * @param $key * @param $val - * @return float|int|mixed|string + * @return mixed * @throws Exception */ - public function fieldFormat($key, $val) + public function fieldFormat($key, $val): mixed { return $this->encode($val, $this->get_fields($key)); } @@ -88,7 +89,7 @@ class Columns extends Component * @return array * @throws */ - public function populate($data) + public function populate($data): array { $column = $this->get_fields(); foreach ($data as $key => $val) { @@ -102,11 +103,10 @@ class Columns extends Component /** * @param $val - * @param $format - * @return float|int|mixed|string - * @throws + * @param null $format + * @return mixed */ - public function decode($val, $format = null) + public function decode($val, $format = null): mixed { if (empty($format)) { return $val; @@ -125,12 +125,12 @@ class Columns extends Component /** - * @param $name + * @param string $name * @param $value - * @return float|int|mixed|string + * @return mixed * @throws Exception */ - public function _decode(string $name, $value) + public function _decode(string $name, $value): mixed { return $this->decode($value, $this->get_fields($name)); } @@ -138,11 +138,11 @@ class Columns extends Component /** * @param $val - * @param $format - * @return float|int|mixed|string - * @throws + * @param null $format + * @return mixed + * @throws Exception */ - public function encode($val, $format = null) + public function encode($val, $format = null): mixed { if (empty($format)) { return $val; @@ -163,7 +163,7 @@ class Columns extends Component * @param $format * @return bool */ - public function isInt($format) + #[Pure] public function isInt($format): bool { return in_array($format, ['int', 'bigint', 'tinyint', 'smallint', 'mediumint']); } @@ -172,7 +172,7 @@ class Columns extends Component * @param $format * @return bool */ - public function isFloat($format) + #[Pure] public function isFloat($format): bool { return in_array($format, ['float', 'double', 'decimal']); } @@ -181,7 +181,7 @@ class Columns extends Component * @param $format * @return bool */ - public function isJson($format) + #[Pure] public function isJson($format): bool { return in_array($format, ['json']); } @@ -190,7 +190,7 @@ class Columns extends Component * @param $format * @return bool */ - public function isString($format) + #[Pure] public function isString($format): bool { return in_array($format, ['varchar', 'char', 'text', 'longtext', 'tinytext', 'mediumtext']); } @@ -200,7 +200,7 @@ class Columns extends Component * @return array * @throws */ - public function format() + public function format(): array { return $this->columns('Default', 'Field'); } @@ -209,7 +209,7 @@ class Columns extends Component * @return int|string|null * @throws Exception */ - public function getAutoIncrement() + public function getAutoIncrement(): int|string|null { return $this->_auto_increment[$this->table] ?? null; } @@ -219,7 +219,7 @@ class Columns extends Component * * @throws Exception */ - public function getPrimaryKeys() + public function getPrimaryKeys(): array|string|null { if (isset($this->_auto_increment[$this->table])) { return $this->_auto_increment[$this->table]; @@ -232,7 +232,7 @@ class Columns extends Component * * @throws Exception */ - public function getFirstPrimary() + #[Pure] public function getFirstPrimary(): array|string|null { if (isset($this->_auto_increment[$this->table])) { return $this->_auto_increment[$this->table]; @@ -249,7 +249,7 @@ class Columns extends Component * @return array * @throws Exception */ - private function columns($name, $index = null) + private function columns($name, $index = null): array { if (empty($index)) { 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 */ - private function getColumns() + private function getColumns(): array|static { return $this->structure($this->getTable()); } @@ -270,10 +270,10 @@ class Columns extends Component /** * @param $table - * @return $this + * @return array|Columns * @throws Exception */ - private function structure($table) + private function structure($table): array|static { if (!isset($this->columns[$table]) || empty($this->columns[$table])) { $sql = $this->db->getBuild()->getColumn($table); @@ -291,9 +291,9 @@ class Columns extends Component /** * @param $column * @param $table - * @return mixed + * @return array */ - private function resolve(array $column, $table) + private function resolve(array $column, $table): array { foreach ($column as $key => $item) { $this->addPrimary($item, $table); @@ -335,24 +335,24 @@ class Columns extends Component * @param $type * @return string */ - private function clean($type) + private function clean($type): string { - if (strpos($type, ')') === false) { + if (!str_contains($type, ')')) { return $type; } $replace = preg_replace('/\(\d+(,\d+)?\)(\s+\w+)*/', '', $type); - if (strpos(' ', $replace) !== FALSE) { + if (str_contains(' ', $replace)) { $replace = explode(' ', $replace)[1]; } return $replace; } /** - * @param $field - * @return array|string + * @param null $field + * @return array|string|null * @throws Exception */ - public function get_fields($field = null) + public function get_fields($field = null): array|string|null { $fields = $this->columns('Type', 'Field'); if (empty($field)) { diff --git a/Database/Mysql/Schema.php b/Database/Mysql/Schema.php index 6998ba5d..03056af5 100644 --- a/Database/Mysql/Schema.php +++ b/Database/Mysql/Schema.php @@ -28,9 +28,9 @@ class Schema extends Component private ?Change $_change = null; /** - * @return Select + * @return Select|null */ - public function getQueryBuilder() + public function getQueryBuilder(): ?Select { if ($this->_builder === null) { $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) { $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) { $this->_column = new Columns(['db' => $this->db]); diff --git a/Database/Orm/Change.php b/Database/Orm/Change.php index 1a8c2ba7..7773e82b 100644 --- a/Database/Orm/Change.php +++ b/Database/Orm/Change.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Database\Orm; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\BaseObject; use Database\ActiveQuery; use Exception; @@ -26,7 +27,7 @@ class Change extends BaseObject * @return string * @throws Exception */ - public function update(string $model, $attributes, $condition, &$params) + public function update(string $model, $attributes, $condition, &$params): string { if (empty($params)) { throw new Exception("Not has update values."); @@ -55,7 +56,7 @@ class Change extends BaseObject * @return array|string * @throws */ - public function batchUpdate(string $table, array $attributes, $condition) + public function batchUpdate(string $table, array $attributes, $condition): array|string { $param = []; $_attributes = []; @@ -83,7 +84,7 @@ class Change extends BaseObject * @return string * @throws Exception */ - public function mathematics($table, $params, $condition) + public function mathematics($table, $params, $condition): string { $_tmp = $newParam = []; if (isset($params['incr']) && is_array($params['incr'])) { @@ -109,7 +110,7 @@ class Change extends BaseObject * @return array * @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.'; foreach ($params as $key => $val) { @@ -127,7 +128,7 @@ class Change extends BaseObject * @param array $params * @return string */ - public function insertOrUpdateByDUPLICATE($table, array $params) + public function insertOrUpdateByDUPLICATE($table, array $params): string { $keys = implode(',', array_keys($params)); @@ -153,14 +154,14 @@ class Change extends BaseObject * @return string * @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) . ')'); if (empty($params)) { throw new Exception("save data param not find."); } foreach ($params as $key => $val) { - if (strpos($sql, ':' . $key) === FALSE) { + if (!str_contains($sql, ':' . $key)) { throw new Exception("save $key data param not find."); } } @@ -175,7 +176,7 @@ class Change extends BaseObject * @return array * @throws Exception */ - public function batchInsert($table, $attributes, array $params = NULL) + public function batchInsert($table, $attributes, array $params = NULL): array { if (empty($params)) { throw new Exception("save data param not find."); @@ -205,7 +206,7 @@ class Change extends BaseObject * @return string * 构建SQL语句 */ - private function inserts($table, $fields, $data) + #[Pure] private function inserts($table, $fields, $data): string { $query = [ 'INSERT IGNORE INTO', '%s', '(%s)', 'VALUES %s' @@ -223,7 +224,7 @@ class Change extends BaseObject * @return bool|string * @throws Exception */ - public function updateAll($table, $attributes, $condition) + public function updateAll($table, $attributes, $condition): bool|string { $param = []; foreach ($attributes as $key => $val) { @@ -247,7 +248,7 @@ class Change extends BaseObject * @return string * @throws Exception */ - public function delete(ActiveQuery $query) + public function delete(ActiveQuery $query): string { if (empty($query->from)) { $query->from = $query->getTable(); @@ -266,7 +267,7 @@ class Change extends BaseObject * @param string $tableName * @return string */ - public function truncate(string $tableName) + public function truncate(string $tableName): string { return 'TRUNCATE ' . $tableName; } diff --git a/Database/Orm/Condition.php b/Database/Orm/Condition.php index 616b79bd..72cf0568 100644 --- a/Database/Orm/Condition.php +++ b/Database/Orm/Condition.php @@ -3,8 +3,11 @@ declare(strict_types=1); namespace Database\Orm; +use JetBrains\PhpStorm\Pure; +use ReflectionException; use Snowflake\Core\JSON; use Snowflake\Core\Str; +use Snowflake\Exception\NotFindClassException; use Snowflake\Snowflake; use Database\ActiveQuery; use Database\Base\ConditionClassMap; @@ -26,7 +29,7 @@ trait Condition * @return string * @throws Exception */ - public function getWhere($query) + public function getWhere($query): string { return $this->builderWhere($query); } @@ -36,7 +39,7 @@ trait Condition * @param $alias * @return string */ - private function builderAlias($alias) + private function builderAlias($alias): string { return " AS " . $alias; } @@ -46,7 +49,7 @@ trait Condition * @return string * @throws Exception */ - private function builderFrom($table) + private function builderFrom($table): string { if ($table instanceof ActiveQuery) { $table = '(' . $table->getBuild()->getQuery($table) . ')'; @@ -58,7 +61,7 @@ trait Condition * @param $join * @return string */ - private function builderJoin($join) + #[Pure] private function builderJoin($join): string { if (!empty($join)) { return ' ' . implode(' ', $join); @@ -71,7 +74,7 @@ trait Condition * @return string * @throws Exception */ - private function builderWhere($where) + private function builderWhere($where): string { if (empty($where)) { return ''; @@ -101,10 +104,11 @@ trait Condition /** * @param $value - * @return mixed|object|string|null - * @throws Exception + * @return mixed + * @throws ReflectionException + * @throws NotFindClassException */ - private function arrayMap($value) + private function arrayMap($value): mixed { $classMap = ConditionClassMap::$conditionMap; if (isset($value[0])) { @@ -125,10 +129,11 @@ trait Condition /** * @param $value - * @return mixed|object - * @throws Exception + * @return mixed + * @throws NotFindClassException + * @throws ReflectionException */ - private function classMap($value) + private function classMap($value): mixed { [$option['opera'], $option['column'], $option['value']] = $value; @@ -146,7 +151,7 @@ trait Condition * @param $group * @return string */ - private function builderGroup($group) + private function builderGroup($group): string { if (empty($group)) { return ''; @@ -158,7 +163,7 @@ trait Condition * @param $order * @return string */ - private function builderOrder($order) + private function builderOrder($order): string { if (!empty($order)) { return ' ORDER BY ' . implode(',', $order); @@ -171,7 +176,7 @@ trait Condition * @param ActiveQuery $query * @return string */ - private function builderLimit(ActiveQuery $query) + private function builderLimit(ActiveQuery $query): string { $limit = $query->limit; if (!is_numeric($limit) || $limit < 1) { @@ -192,7 +197,7 @@ trait Condition * @param bool $isSearch * @return int|string */ - public function valueEncode($value, $isSearch = false) + public function valueEncode($value, $isSearch = false): int|string { if ($isSearch) { return $value; diff --git a/Database/Orm/Select.php b/Database/Orm/Select.php index 58882822..e88a9ca9 100644 --- a/Database/Orm/Select.php +++ b/Database/Orm/Select.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Database\Orm; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\BaseObject; use Database\ActiveQuery; use Database\Sql; @@ -24,17 +25,17 @@ class Select extends BaseObject * @return string * @throws Exception */ - public function getQuery($query) + public function getQuery(ActiveQuery|Sql|Db $query): string { return $this->generate($query, false); } /** - * @param ActiveQuery|Db|mixed $query + * @param ActiveQuery|Db|Sql $query * @return string * @throws Exception */ - public function count($query) + public function count(ActiveQuery|Db|Sql $query): string { return $this->generate($query, true); } @@ -45,7 +46,7 @@ class Select extends BaseObject * @return string * @throws Exception */ - private function generate($query, $isCount = false) + private function generate(ActiveQuery|Db|Sql $query, $isCount = false): string { if (empty($query->from)) { $query->from = $query->getTable(); @@ -78,7 +79,7 @@ class Select extends BaseObject * @param bool $isCount * @return string */ - private function builderSelect($select = NULL, $isCount = false) + #[Pure] private function builderSelect($select = NULL, $isCount = false): string { if ($isCount === true) { return 'SELECT COUNT(*)'; @@ -97,7 +98,7 @@ class Select extends BaseObject * @param $table * @return string */ - public function getColumn($table) + public function getColumn($table): string { return 'SHOW FULL FIELDS FROM ' . $table; } diff --git a/Database/Pagination.php b/Database/Pagination.php index cfc020fc..425cc006 100644 --- a/Database/Pagination.php +++ b/Database/Pagination.php @@ -52,10 +52,10 @@ class Pagination extends Component /** - * @param Closure|array $callback + * @param array|Closure $callback * @throws Exception */ - public function setCallback($callback) + public function setCallback(array|Closure $callback) { if (!is_callable($callback, true)) { throw new Exception('非法回调函数~'); @@ -68,7 +68,7 @@ class Pagination extends Component * @param int $number * @return Pagination */ - public function setOffset(int $number) + public function setOffset(int $number): static { if ($number < 0) { $number = 0; @@ -82,7 +82,7 @@ class Pagination extends Component * @param int $number * @return Pagination */ - public function setLimit(int $number) + public function setLimit(int $number): static { if ($number < 1) { $number = 100; @@ -96,9 +96,9 @@ class Pagination extends Component /** * @param int $number - * @return Pagination|void + * @return Pagination */ - public function setMax(int $number) + public function setMax(int $number): static { if ($number < 0) { return $this; @@ -125,7 +125,7 @@ class Pagination extends Component * @param $param * @return array */ - public function loop($param) + public function loop($param): array { if ($this->_max > 0 && $this->_length >= $this->_max) { return $this->output(); @@ -145,7 +145,7 @@ class Pagination extends Component /** * @return array */ - public function output() + public function output(): array { return []; } @@ -172,7 +172,7 @@ class Pagination extends Component * 解释器 * @return mixed */ - private function executed($callback, $data, $param) + private function executed($callback, $data, $param): mixed { $this->_group->add(1); return Coroutine::create(function ($callback, $data, $param): void { @@ -192,7 +192,7 @@ class Pagination extends Component /** * @return array|Collection */ - private function get() + private function get(): Collection|array { if ($this->_length + $this->_limit > $this->_max) { $this->_limit = $this->_length + $this->_limit - $this->_max; diff --git a/Database/Relation.php b/Database/Relation.php index 7a39c0da..91919daa 100644 --- a/Database/Relation.php +++ b/Database/Relation.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Database; +use Exception; use Snowflake\Abstracts\Component; /** @@ -23,7 +24,7 @@ class Relation extends Component * @param ActiveQuery $query * @return $this */ - public function bindIdentification(string $identification, ActiveQuery $query) + public function bindIdentification(string $identification, ActiveQuery $query): static { $this->_query[$identification] = $query; return $this; @@ -33,19 +34,18 @@ class Relation extends Component * @param $name * @return ActiveQuery|null */ - public function getQuery(string $name) + public function getQuery(string $name): ?ActiveQuery { return $this->_query[$name] ?? null; } /** - * @param $identification + * @param string $identification * @param $localValue - * @return ActiveRecord|mixed - * @throws + * @return mixed */ - public function first(string $identification, $localValue) + public function first(string $identification, $localValue): mixed { $_identification = $identification . '_first_' . $localValue; if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) { @@ -62,12 +62,12 @@ class Relation extends Component /** - * @param $identification + * @param string $identification * @param $localValue - * @return ActiveRecord|mixed - * @throws + * @return mixed + * @throws Exception */ - public function count(string $identification, $localValue) + public function count(string $identification, $localValue): mixed { $_identification = $identification . '_count_' . $localValue; if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) { @@ -84,12 +84,11 @@ class Relation extends Component /** - * @param $identification + * @param string $identification * @param $localValue - * @return array|Collection|mixed|null - * @throws + * @return mixed */ - public function get(string $identification, $localValue) + public function get(string $identification, $localValue): mixed { if (is_array($localValue)) { $_identification = $identification . '_get_' . implode('_', $localValue); diff --git a/Database/Sql.php b/Database/Sql.php index 5006aa24..0b923808 100644 --- a/Database/Sql.php +++ b/Database/Sql.php @@ -11,6 +11,7 @@ namespace Database; use Database\Orm\Select; use Database\Traits\QueryTrait; +use Exception; /** * Class Sql @@ -23,9 +24,9 @@ class Sql /** * @return string - * @throws \Exception + * @throws Exception */ - public function getSql() + public function getSql(): string { return (new Select())->getQuery($this); } diff --git a/Database/Traits/QueryTrait.php b/Database/Traits/QueryTrait.php index 9b236ba5..f4ba91b4 100644 --- a/Database/Traits/QueryTrait.php +++ b/Database/Traits/QueryTrait.php @@ -21,763 +21,765 @@ use Exception; */ trait QueryTrait { - public array $where = []; - public array $select = []; - public array $join = []; - public array $order = []; - public ?int $offset = NULL; - public ?int $limit = NULL; - public string $group = ''; - public string $from = ''; - public string $alias = 't1'; - public array $filter = []; - - public bool $ifNotWhere = false; - - /** - * @var ActiveRecord - */ - public ActiveRecord $modelClass; - - /** - * clear - */ - public function clear() - { - $this->where = []; - $this->select = []; - $this->join = []; - $this->order = []; - $this->offset = NULL; - $this->limit = NULL; - $this->group = ''; - $this->from = ''; - $this->alias = 't1'; - $this->filter = []; - } - - /** - * @param $bool - * @return $this - */ - public function ifNotWhere($bool) - { - $this->ifNotWhere = $bool; - return $this; - } - - /** - * @return string - * @throws Exception - */ - public function getTable() - { - return $this->modelClass::getTable(); - } - - - /** - * @param $column - * @return $this - */ - public function isNull($column) - { - $this->where[] = $column . ' IS NULL'; - return $this; - } - - - /** - * @param $column - * @return $this - */ - public function isEmpty($column) - { - $this->where[] = $column . ' = \'\''; - return $this; - } - - /** - * @param $column - * @return $this - */ - public function isNotEmpty($column) - { - $this->where[] = $column . ' <> \'\''; - return $this; - } - - /** - * @param $column - * @return $this - */ - public function isNotNull($column) - { - $this->where[] = $column . ' IS NOT NULL'; - return $this; - } - - /** - * @param $columns - * @return $this - * @throws Exception - */ - public function filter($columns) - { - if (!$columns) { - return $this; - } - if (is_callable($columns, TRUE)) { - return call_user_func($columns, $this); - } - if (is_string($columns)) { - $columns = explode(',', $columns); - } - if (!is_array($columns)) { - return $this; - } - $this->filter = $columns; - return $this; - } - - /** - * @param string $alias - * - * @return $this - * - * select * from tableName as t1 - */ - public function alias($alias = 't1') - { - $this->alias = $alias; - return $this; - } - - /** - * @param string|\Closure $tableName - * - * @return $this - * - */ - public function from($tableName) - { - $this->from = $tableName; - return $this; - } - - /** - * @param string $tableName - * @param string $alias - * @param null $on - * @param array|null $param - * @return $this - * $query->join([$tableName, ['userId'=>'uuvOd']], $param) - * $query->join([$tableName, ['userId'=>'uuvOd'], $param]) - * $query->join($tableName, ['userId'=>'uuvOd',$param]) - */ - private function join(string $tableName, string $alias, $on = NULL, array $param = NULL) - { - if (empty($on)) { - return $this; - } - $join[] = $tableName . ' AS ' . $alias; - $join[] = 'ON ' . $this->onCondition($alias, $on); - if (empty($join)) { - return $this; - } - - $this->join[] = implode(' ', $join); - if (!empty($param)) { - $this->addParams($param); - } - - return $this; - } - - /** - * @param $alias - * @param $on - * @return string - */ - private function onCondition($alias, $on) - { - $array = []; - foreach ($on as $key => $item) { - if (strpos($item, '.') === false) { - $this->addParam($key, $item); - } else { - $explode = explode('.', $item); - if (isset($explode[1]) && ($explode[0] == $alias || $this->alias == $explode[0])) { - $array[] = $key . '=' . $item; - } else { - $this->addParam($key, $item); - } - } - } - return implode(' AND ', $array); - } - - /** - * @param $tableName - * @param $alias - * @param $onCondition - * @param null $param - * @return $this - * @throws Exception - */ - public function leftJoin(string $tableName, string $alias, $onCondition, $param = NULL) - { - if (class_exists($tableName)) { - if (!in_array(ActiveRecord::class, class_implements($tableName))) { - throw new Exception('Model must implement ' . $tableName); - } - $tableName = $tableName::getTable(); - } - return $this->join(...["LEFT JOIN " . $tableName, $alias, $onCondition, $param]); - } - - /** - * @param $tableName - * @param $alias - * @param $onCondition - * @param null $param - * @return $this - * @throws Exception - */ - public function rightJoin($tableName, $alias, $onCondition, $param = NULL) - { - if (class_exists($tableName)) { - if (!in_array(ActiveRecord::class, class_implements($tableName))) { - throw new Exception('Model must implement ' . $tableName); - } - $tableName = $tableName::getTable(); - } - return $this->join(...["RIGHT JOIN " . $tableName, $alias, $onCondition, $param]); - } - - /** - * @param $tableName - * @param $alias - * @param $onCondition - * @param null $param - * @return $this - * @throws Exception - */ - public function innerJoin($tableName, $alias, $onCondition, $param = NULL) - { - if (class_exists($tableName)) { - if (!in_array(ActiveRecord::class, class_implements($tableName))) { - throw new Exception('Model must implement ' . $tableName); - } - $tableName = $tableName::getTable(); - } - return $this->join(...["INNER JOIN " . $tableName, $alias, $onCondition, $param]); - } - - /** - * @param $array - * - * @return string - */ - private function toString($array) - { - $tmp = []; - if (!is_array($array)) { - return $array; - } - foreach ($array as $key => $val) { - if (is_array($val)) { - $tmp[] = $this->toString($array); - } else { - $tmp[] = $key . '=:' . $key; - $this->attributes[':' . $key] = $val; - } - } - return implode(' AND ', $tmp); - } - - /** - * @param $field - * - * @return $this - */ - public function sum($field) - { - $this->select[] = 'SUM(' . $field . ') AS ' . $field; - return $this; - } - - /** - * @param $field - * @return $this - */ - public function max($field) - { - $this->select[] = 'MAX(' . $field . ') AS ' . $field; - return $this; - } - - /** - * @param string $lngField - * @param string $latField - * @param int $lng1 - * @param int $lat1 - * - * @return $this - */ - public function distance(string $lngField, string $latField, int $lng1, int $lat1) - { - $sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat1 * PI() / 180 - $lat1 * PI() / 180) / 2),2) + COS($lat1 * PI() / 180) * COS($latField * PI() / 180) * POW(SIN(($lng1 * PI() / 180 - $lngField * PI() / 180) / 2),2))) * 1000) AS distance"; - $this->select[] = $sql; - return $this; - } - - /** - * @param $column - * @param string $sort - * - * @return $this - * - * [ - * 'addTime', - * 'descTime desc' - * ] - */ - public function orderBy($column, $sort = 'DESC') - { - if (empty($column)) { - return $this; - } - if (is_string($column)) { - return $this->addOrder(...func_get_args()); - } - - foreach ($column as $key => $val) { - $this->addOrder($val); - } - - return $this; - } - - /** - * @param $column - * @param string $sort - * - * @return $this - * - */ - private function addOrder($column, $sort = 'DESC') - { - $column = trim($column); - - if (func_num_args() == 1 || strpos($column, ' ') !== FALSE) { - $this->order[] = $column; - } else { - $this->order[] = "$column $sort"; - } - return $this; - } - - /** - * @param array|string $column - * - * @return $this - */ - public function select($column = '*') - { - if ($column == '*') { - $this->select = $column; - } else { - if (!is_array($column)) { - $column = explode(',', $column); - } - foreach ($column as $key => $val) { - $this->select[] = $val; - } - } - return $this; - } - - /** - * @return $this - */ - public function orderRand() - { - $this->order[] = 'RAND()'; - return $this; - } - - /** - * @param array $conditionArray - * - * @return $this|array|ActiveQuery - * @throws Exception - */ - public function or(array $conditionArray = []) - { - $conditions = []; - if (empty($conditionArray) || count($conditionArray) < 2) { - return $this; - } - - $select = new Select(); - - $conditions[] = $select->getWhere($this->where); - $conditions[] = $select->getWhere($conditionArray); - if (empty($conditions[count($conditions) - 1])) { - return $this; - } - $this->where = ['(' . implode(' OR ', $conditions) . ')']; - - return $this; - } - - /** - * @param $columns - * @param string $oprea - * @param null $value - * - * @return array|ActiveQuery|mixed - * @throws Exception - */ - public function and($columns, $value = NULL, $oprea = '=') - { - if (!is_numeric($value) && !is_bool($value)) { - $value = '\'' . $value . '\''; - } - $this->where[] = $columns . $oprea . $value; - return $this; - } - - /** - * @param $limit - * @return $this - */ - public function plunk($limit) - { - $this->offset = 0; - $this->limit = $limit; - return $this; - } - - /** - * @param $columns - * @param string $value - * @return $this - * @throws Exception - */ - public function like($columns, string $value) - { - if (empty($columns) || empty($value)) { - return $this; - } - - if (is_array($columns)) { - $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; - } - - $this->where[] = ['LIKE', $columns, $value]; - - return $this; - } - - /** - * @param $columns - * @param string $value - * @return $this - * @throws Exception - */ - public function lLike($columns, string $value) - { - if (empty($columns) || empty($value)) { - return $this; - } - - if (is_array($columns)) { - $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; - } - - $this->where[] = ['LLike', $columns, rtrim($value, '%')]; - - return $this; - } - - /** - * @param $columns - * @param string $value - * @return $this - * @throws Exception - */ - public function rLike($columns, string $value) - { - if (empty($columns) || empty($value)) { - return $this; - } - - if (is_array($columns)) { - $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; - } - - $this->where[] = ['RLike', $columns, ltrim($value, '%')]; - - return $this; - } - - - /** - * @param $columns - * @param string $value - * @return $this - * @throws Exception - */ - public function notLike($columns, string $value) - { - if (empty($columns) || empty($value)) { - return $this; - } - - if (is_array($columns)) { - $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; - } - - $this->where[] = ['NOT LIKE', $columns, ltrim($value, '%')]; - - return $this; - } - - /** - * @param string $column - * @param int $value - * @return $this - * @throws Exception - */ - public function eq(string $column, $value) - { - $this->where[] = ['EQ', $column, $value]; - - return $this; - } - - - /** - * @param string $column - * @param int $value - * @return $this - * @throws Exception - */ - public function neq(string $column, $value) - { - $this->where[] = ['NEQ', $column, $value]; - - return $this; - } - - - /** - * @param string $column - * @param int $value - * @return $this - * @throws Exception - */ - public function gt(string $column, $value) - { - $this->where[] = ['GT', $column, $value]; - - return $this; - } - - /** - * @param string $column - * @param int $value - * @return $this - * @throws Exception - */ - public function egt(string $column, $value) - { - $this->where[] = ['EGT', $column, $value]; - - return $this; - } - - - /** - * @param string $column - * @param int $value - * @return $this - * @throws Exception - */ - public function lt(string $column, $value) - { - $this->where[] = ['LT', $column, $value]; - - return $this; - } - - /** - * @param string $column - * @param int $value - * @return $this - * @throws Exception - */ - public function elt(string $column, $value) - { - $this->where[] = ['ELT', $column, $value]; - - return $this; - } - - /** - * @param $columns - * @param $value - * @return $this - * @throws Exception - */ - public function in($columns, $value) - { - if ($value instanceof \Closure) { - $value = $this->makeNewQuery($value); - } else if (empty($value) || !is_array($value)) { - $value = [-1]; - } else { - $value = array_filter($value, function ($value) { - return $value !== null; - }); - $value = array_unique($value); - } - $this->where[] = ['IN', $columns, $value]; - return $this; - } - - - /** - * @param $value - * @return string - * @throws Exception - */ - public function makeNewQuery($value) - { - $activeQuery = new ActiveQuery($this->modelClass); - call_user_func($value, $activeQuery); - if (empty($activeQuery->from)) { - $activeQuery->from($activeQuery->modelClass::getTable()); - } - return $activeQuery; - } - - - /** - * @param $columns - * @param $value - * @return $this - * @throws Exception - */ - public function notIn($columns, $value) - { - $this->where[] = ['NOT IN', $columns, $value]; - - return $this; - } - - /** - * @param string $column - * @param string $start - * @param string $end - * @return $this - * @throws Exception - */ - public function between(string $column, string $start, string $end) - { - if (empty($column) || empty($start) || empty($end)) { - return $this; - } - $this->where[] = ['BETWEEN', $column, [$start, $end]]; - - return $this; - } - - /** - * @param string $column - * @param string $start - * @param string $end - * @return $this - * @throws Exception - */ - public function notBetween(string $column, string $start, string $end) - { - if (empty($column) || empty($start) || empty($end)) { - return $this; - } - - $this->where[] = ['NOT BETWEEN', $column, [$start, $end]]; - - return $this; - } - - /** - * @param array $params - * - * @return $this - */ - public function bindParams(array $params = []) - { - if (empty($params)) { - return $this; - } - $this->attributes = $params; - return $this; - } - - /** - * @param array|callable $conditions - * @return $this - */ - public function where($conditions) - { - if ($conditions instanceof \Closure) { - call_user_func($conditions, $this); - } else { - if (is_string($conditions)) { - $conditions = [$conditions]; - } - $this->where[] = $conditions; - } - return $this; - } - - /** - * @param string $name - * @param string|null $having - * - * @return $this - */ - public function groupBy(string $name, string $having = NULL) - { - $this->group = $name; - if (empty($having)) { - return $this; - } - $this->group .= ' HAVING ' . $having; - return $this; - } - - /** - * @param int $offset - * @param int $limit - * - * @return $this - */ - public function limit(int $offset, int $limit = 20) - { - $this->offset = $offset; - $this->limit = $limit; - return $this; - } - - - public function oneLimit() - { - $this->limit = 1; - return $this; - } + public array $where = []; + public array $select = []; + public array $join = []; + public array $order = []; + public ?int $offset = NULL; + public ?int $limit = NULL; + public string $group = ''; + public string $from = ''; + public string $alias = 't1'; + public array $filter = []; + + public bool $ifNotWhere = false; + + /** + * @var ActiveRecord + */ + public ActiveRecord $modelClass; + + /** + * clear + */ + public function clear() + { + $this->where = []; + $this->select = []; + $this->join = []; + $this->order = []; + $this->offset = NULL; + $this->limit = NULL; + $this->group = ''; + $this->from = ''; + $this->alias = 't1'; + $this->filter = []; + } + + /** + * @param $bool + * @return $this + */ + public function ifNotWhere($bool): static + { + $this->ifNotWhere = $bool; + return $this; + } + + /** + * @return string + * @throws Exception + */ + public function getTable(): string + { + return $this->modelClass::getTable(); + } + + + /** + * @param $column + * @return $this + */ + public function isNull($column): static + { + $this->where[] = $column . ' IS NULL'; + return $this; + } + + + /** + * @param $column + * @return $this + */ + public function isEmpty($column): static + { + $this->where[] = $column . ' = \'\''; + return $this; + } + + /** + * @param $column + * @return $this + */ + public function isNotEmpty($column): static + { + $this->where[] = $column . ' <> \'\''; + return $this; + } + + /** + * @param $column + * @return $this + */ + public function isNotNull($column): static + { + $this->where[] = $column . ' IS NOT NULL'; + return $this; + } + + /** + * @param $columns + * @return $this + * @throws Exception + */ + public function filter($columns): static + { + if (!$columns) { + return $this; + } + if (is_callable($columns, TRUE)) { + return call_user_func($columns, $this); + } + if (is_string($columns)) { + $columns = explode(',', $columns); + } + if (!is_array($columns)) { + return $this; + } + $this->filter = $columns; + return $this; + } + + /** + * @param string $alias + * + * @return $this + * + * select * from tableName as t1 + */ + public function alias($alias = 't1'): static + { + $this->alias = $alias; + return $this; + } + + /** + * @param string|\Closure $tableName + * + * @return $this + */ + public function from(string|\Closure $tableName): static + { + $this->from = $tableName; + return $this; + } + + /** + * @param string $tableName + * @param string $alias + * @param null $on + * @param array|null $param + * @return $this + * $query->join([$tableName, ['userId'=>'uuvOd']], $param) + * $query->join([$tableName, ['userId'=>'uuvOd'], $param]) + * $query->join($tableName, ['userId'=>'uuvOd',$param]) + */ + private function join(string $tableName, string $alias, $on = NULL, array $param = NULL): static + { + if (empty($on)) { + return $this; + } + $join[] = $tableName . ' AS ' . $alias; + $join[] = 'ON ' . $this->onCondition($alias, $on); + if (empty($join)) { + return $this; + } + + $this->join[] = implode(' ', $join); + if (!empty($param)) { + $this->addParams($param); + } + + return $this; + } + + /** + * @param $alias + * @param $on + * @return string + */ + private function onCondition($alias, $on): string + { + $array = []; + foreach ($on as $key => $item) { + if (!str_contains($item, '.')) { + $this->addParam($key, $item); + } else { + $explode = explode('.', $item); + if (isset($explode[1]) && ($explode[0] == $alias || $this->alias == $explode[0])) { + $array[] = $key . '=' . $item; + } else { + $this->addParam($key, $item); + } + } + } + return implode(' AND ', $array); + } + + /** + * @param $tableName + * @param $alias + * @param $onCondition + * @param null $param + * @return $this + * @throws Exception + */ + public function leftJoin(string $tableName, string $alias, $onCondition, $param = NULL): static + { + if (class_exists($tableName)) { + if (!in_array(ActiveRecord::class, class_implements($tableName))) { + throw new Exception('Model must implement ' . $tableName); + } + $tableName = $tableName::getTable(); + } + return $this->join(...["LEFT JOIN " . $tableName, $alias, $onCondition, $param]); + } + + /** + * @param $tableName + * @param $alias + * @param $onCondition + * @param null $param + * @return $this + * @throws Exception + */ + public function rightJoin($tableName, $alias, $onCondition, $param = NULL): static + { + if (class_exists($tableName)) { + if (!in_array(ActiveRecord::class, class_implements($tableName))) { + throw new Exception('Model must implement ' . $tableName); + } + $tableName = $tableName::getTable(); + } + return $this->join(...["RIGHT JOIN " . $tableName, $alias, $onCondition, $param]); + } + + /** + * @param $tableName + * @param $alias + * @param $onCondition + * @param null $param + * @return $this + * @throws Exception + */ + public function innerJoin($tableName, $alias, $onCondition, $param = NULL): static + { + if (class_exists($tableName)) { + if (!in_array(ActiveRecord::class, class_implements($tableName))) { + throw new Exception('Model must implement ' . $tableName); + } + $tableName = $tableName::getTable(); + } + return $this->join(...["INNER JOIN " . $tableName, $alias, $onCondition, $param]); + } + + /** + * @param $array + * + * @return string + */ + private function toString($array): string + { + $tmp = []; + if (!is_array($array)) { + return $array; + } + foreach ($array as $key => $val) { + if (is_array($val)) { + $tmp[] = $this->toString($array); + } else { + $tmp[] = $key . '=:' . $key; + $this->attributes[':' . $key] = $val; + } + } + return implode(' AND ', $tmp); + } + + /** + * @param $field + * + * @return $this + */ + public function sum($field): static + { + $this->select[] = 'SUM(' . $field . ') AS ' . $field; + return $this; + } + + /** + * @param $field + * @return $this + */ + public function max($field): static + { + $this->select[] = 'MAX(' . $field . ') AS ' . $field; + return $this; + } + + /** + * @param string $lngField + * @param string $latField + * @param int $lng1 + * @param int $lat1 + * + * @return $this + */ + public function distance(string $lngField, string $latField, int $lng1, int $lat1): static + { + $sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat1 * PI() / 180 - $lat1 * PI() / 180) / 2),2) + COS($lat1 * PI() / 180) * COS($latField * PI() / 180) * POW(SIN(($lng1 * PI() / 180 - $lngField * PI() / 180) / 2),2))) * 1000) AS distance"; + $this->select[] = $sql; + return $this; + } + + /** + * @param $column + * @param string $sort + * + * @return $this + * + * [ + * 'addTime', + * 'descTime desc' + * ] + */ + public function orderBy($column, $sort = 'DESC'): static + { + if (empty($column)) { + return $this; + } + if (is_string($column)) { + return $this->addOrder(...func_get_args()); + } + + foreach ($column as $key => $val) { + $this->addOrder($val); + } + + return $this; + } + + /** + * @param $column + * @param string $sort + * + * @return $this + * + */ + private function addOrder($column, $sort = 'DESC'): static + { + $column = trim($column); + + if (func_num_args() == 1 || str_contains($column, ' ')) { + $this->order[] = $column; + } else { + $this->order[] = "$column $sort"; + } + return $this; + } + + /** + * @param array|string $column + * + * @return $this + */ + public function select($column = '*'): static + { + if ($column == '*') { + $this->select = $column; + } else { + if (!is_array($column)) { + $column = explode(',', $column); + } + foreach ($column as $key => $val) { + $this->select[] = $val; + } + } + return $this; + } + + /** + * @return $this + */ + public function orderRand(): static + { + $this->order[] = 'RAND()'; + return $this; + } + + /** + * @param array $conditionArray + * + * @return $this|array|ActiveQuery + * @throws Exception + */ + public function or(array $conditionArray = []): static + { + $conditions = []; + if (empty($conditionArray) || count($conditionArray) < 2) { + return $this; + } + + $select = new Select(); + + $conditions[] = $select->getWhere($this->where); + $conditions[] = $select->getWhere($conditionArray); + if (empty($conditions[count($conditions) - 1])) { + return $this; + } + $this->where = ['(' . implode(' OR ', $conditions) . ')']; + + return $this; + } + + /** + * @param $columns + * @param string $oprea + * @param null $value + * + * @return array|ActiveQuery|mixed + * @throws Exception + */ + public function and($columns, $value = NULL, $oprea = '='): static + { + if (!is_numeric($value) && !is_bool($value)) { + $value = '\'' . $value . '\''; + } + $this->where[] = $columns . $oprea . $value; + return $this; + } + + /** + * @param $limit + * @return $this + */ + public function plunk($limit): static + { + $this->offset = 0; + $this->limit = $limit; + return $this; + } + + /** + * @param $columns + * @param string $value + * @return $this + * @throws Exception + */ + public function like($columns, string $value): static + { + if (empty($columns) || empty($value)) { + return $this; + } + + if (is_array($columns)) { + $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; + } + + $this->where[] = ['LIKE', $columns, $value]; + + return $this; + } + + /** + * @param $columns + * @param string $value + * @return $this + * @throws Exception + */ + public function lLike($columns, string $value): static + { + if (empty($columns) || empty($value)) { + return $this; + } + + if (is_array($columns)) { + $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; + } + + $this->where[] = ['LLike', $columns, rtrim($value, '%')]; + + return $this; + } + + /** + * @param $columns + * @param string $value + * @return $this + * @throws Exception + */ + public function rLike($columns, string $value): static + { + if (empty($columns) || empty($value)) { + return $this; + } + + if (is_array($columns)) { + $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; + } + + $this->where[] = ['RLike', $columns, ltrim($value, '%')]; + + return $this; + } + + + /** + * @param $columns + * @param string $value + * @return $this + * @throws Exception + */ + public function notLike($columns, string $value): static + { + if (empty($columns) || empty($value)) { + return $this; + } + + if (is_array($columns)) { + $columns = 'CONCAT(' . implode(',^,', $columns) . ')'; + } + + $this->where[] = ['NOT LIKE', $columns, ltrim($value, '%')]; + + return $this; + } + + /** + * @param string $column + * @param int $value + * @return $this + * @throws Exception + */ + public function eq(string $column, int $value): static + { + $this->where[] = ['EQ', $column, $value]; + + return $this; + } + + + /** + * @param string $column + * @param int $value + * @return $this + * @throws Exception + */ + public function neq(string $column, int $value): static + { + $this->where[] = ['NEQ', $column, $value]; + + return $this; + } + + + /** + * @param string $column + * @param int $value + * @return $this + * @throws Exception + */ + public function gt(string $column, int $value): static + { + $this->where[] = ['GT', $column, $value]; + + return $this; + } + + /** + * @param string $column + * @param int $value + * @return $this + * @throws Exception + */ + public function egt(string $column, int $value): static + { + $this->where[] = ['EGT', $column, $value]; + + return $this; + } + + + /** + * @param string $column + * @param int $value + * @return $this + * @throws Exception + */ + public function lt(string $column, int $value): static + { + $this->where[] = ['LT', $column, $value]; + + return $this; + } + + /** + * @param string $column + * @param int $value + * @return $this + * @throws Exception + */ + public function elt(string $column, int $value): static + { + $this->where[] = ['ELT', $column, $value]; + + return $this; + } + + /** + * @param $columns + * @param $value + * @return $this + * @throws Exception + */ + public function in($columns, $value): static + { + if ($value instanceof \Closure) { + $value = $this->makeNewQuery($value); + } else if (empty($value) || !is_array($value)) { + $value = [-1]; + } else { + $value = array_filter($value, function ($value) { + return $value !== null; + }); + $value = array_unique($value); + } + $this->where[] = ['IN', $columns, $value]; + return $this; + } + + + /** + * @param $value + * @return ActiveQuery + * @throws Exception + */ + public function makeNewQuery($value): ActiveQuery + { + $activeQuery = new ActiveQuery($this->modelClass); + call_user_func($value, $activeQuery); + if (empty($activeQuery->from)) { + $activeQuery->from($activeQuery->modelClass::getTable()); + } + return $activeQuery; + } + + + /** + * @param $columns + * @param $value + * @return $this + * @throws Exception + */ + public function notIn($columns, $value): static + { + $this->where[] = ['NOT IN', $columns, $value]; + + return $this; + } + + /** + * @param string $column + * @param string $start + * @param string $end + * @return $this + * @throws Exception + */ + public function between(string $column, string $start, string $end): static + { + if (empty($column) || empty($start) || empty($end)) { + return $this; + } + $this->where[] = ['BETWEEN', $column, [$start, $end]]; + + return $this; + } + + /** + * @param string $column + * @param string $start + * @param string $end + * @return $this + * @throws Exception + */ + public function notBetween(string $column, string $start, string $end): static + { + if (empty($column) || empty($start) || empty($end)) { + return $this; + } + + $this->where[] = ['NOT BETWEEN', $column, [$start, $end]]; + + return $this; + } + + /** + * @param array $params + * + * @return $this + */ + public function bindParams(array $params = []): static + { + if (empty($params)) { + return $this; + } + $this->attributes = $params; + return $this; + } + + /** + * @param array|callable $conditions + * @return $this + */ + public function where(callable|array $conditions): static + { + if ($conditions instanceof \Closure) { + call_user_func($conditions, $this); + } else { + if (is_string($conditions)) { + $conditions = [$conditions]; + } + $this->where[] = $conditions; + } + return $this; + } + + /** + * @param string $name + * @param string|null $having + * + * @return $this + */ + public function groupBy(string $name, string $having = NULL): static + { + $this->group = $name; + if (empty($having)) { + return $this; + } + $this->group .= ' HAVING ' . $having; + return $this; + } + + /** + * @param int $offset + * @param int $limit + * + * @return $this + */ + public function limit(int $offset, int $limit = 20): static + { + $this->offset = $offset; + $this->limit = $limit; + return $this; + } + + + /** + * @return $this + */ + public function oneLimit(): static + { + $this->limit = 1; + return $this; + } } diff --git a/Gii/Command.php b/Gii/Command.php index e4a960fa..13f44763 100644 --- a/Gii/Command.php +++ b/Gii/Command.php @@ -27,7 +27,7 @@ class Command extends \Console\Command * @return array * @throws Exception */ - public function onHandler(Input $dtl) + public function onHandler(Input $dtl): array { /** @var Gii $gii */ $gii = Snowflake::app()->get('gii'); diff --git a/Gii/Gii.php b/Gii/Gii.php index 0d02139a..90a6b54d 100644 --- a/Gii/Gii.php +++ b/Gii/Gii.php @@ -12,6 +12,8 @@ namespace Gii; use Database\Connection; use Database\Db; use Exception; +use JetBrains\PhpStorm\ArrayShape; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\Input; use Snowflake\Exception\ComponentException; use Snowflake\Exception\ConfigException; @@ -52,7 +54,7 @@ class Gii * @throws ConfigException * @throws Exception */ - public function run(?Connection $db, $input) + public function run(?Connection $db, $input): array { $this->input = $input; if (!empty($db)) $this->db = $db; @@ -90,8 +92,9 @@ class Gii * @return array * @throws ComponentException * @throws ConfigException + * @throws Exception */ - private function getModel($make, $input) + private function getModel($make, $input): array { if (!$this->db) { $db = $this->input->get('databases', 'db'); @@ -120,7 +123,7 @@ class Gii * * @throws Exception */ - private function getTable($controller, $model) + private function getTable($controller, $model): array { $tables = $this->getFields($this->getTables()); if (empty($tables)) { @@ -145,7 +148,7 @@ class Gii * @return string * @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->setConnection($this->db); @@ -163,7 +166,7 @@ class Gii * @return string * @throws Exception */ - private function generateController(array $data) + private function generateController(array $data): string { $controller = new GiiController($data['classFileName'], $data['fields']); $controller->setConnection($this->db); @@ -177,10 +180,10 @@ class Gii } /** - * @return array|null + * @return array|string|null * @throws Exception */ - private function getTables() + private function getTables(): array|string|null { if (empty($this->tableName)) { return $this->showAll(); @@ -199,7 +202,7 @@ class Gii * @return array * @throws Exception */ - private function showAll() + private function showAll(): array { $res = []; $_tables = Db::findAllBySql('show tables', [], $this->db); @@ -214,10 +217,10 @@ class Gii /** * @param $table - * @return bool|int + * @return bool|int|null * @throws Exception */ - private function getIndex($table) + private function getIndex($table): bool|int|null { $data = Db::findAllBySql('SHOW INDEX FROM ' . $table, [], $this->db); @@ -230,7 +233,7 @@ class Gii * @return array * @throws */ - private function getFields($tables) + private function getFields($tables): array { $res = []; if (!is_array($tables)) { @@ -254,7 +257,7 @@ class Gii * @return array * @throws Exception */ - public function createModelFile($tableName, $tables) + public function createModelFile($tableName, $tables): array { $res = $visible = $fields = $keys = []; foreach ($tables as $_key => $_val) { @@ -289,7 +292,7 @@ class Gii * @return string * 创建变量注释 */ - private function createVisible($field) + private function createVisible($field): string { return ' * @property $' . $field; @@ -301,7 +304,7 @@ class Gii * @return string * 暂时不知道干嘛用的 */ - private function createSetFunc($field, $comment) + #[Pure] private function createSetFunc($field, $comment): string { return ' ' . str_pad('\'' . $field . '\'', 20, ' ', STR_PAD_RIGHT) . '=> \'' . (empty($comment) ? ucfirst($field) : $comment) . '\','; @@ -312,18 +315,13 @@ class Gii * @return string * 构建类名称 */ - private function getClassName($tableName) + private function getClassName($tableName): string { $res = []; foreach (explode('_', $tableName) as $n => $val) { $res[] = ucfirst($val); } - - $name = ucfirst(rtrim($this->db->tablePrefix, '_')); - return implode('', $res); - - return str_replace($name, '', implode('', $res)) . 'Comply'; } } diff --git a/Gii/GiiBase.php b/Gii/GiiBase.php index 3c83fb92..cd908efc 100644 --- a/Gii/GiiBase.php +++ b/Gii/GiiBase.php @@ -6,6 +6,9 @@ namespace Gii; use Database\Connection; +use JetBrains\PhpStorm\ArrayShape; +use JetBrains\PhpStorm\Pure; +use ReflectionClass; use Snowflake\Abstracts\Input; /** @@ -15,22 +18,22 @@ use Snowflake\Abstracts\Input; abstract class GiiBase { - public $fileList = []; + public array $fileList = []; /** @var Input */ - protected $input; + protected Input $input; - public $modelPath = APP_PATH . '/app/Models/'; - public $modelNamespace = 'App\Models\\'; + public string $modelPath = APP_PATH . '/app/Models/'; + public string $modelNamespace = 'App\Models\\'; - public $controllerPath = APP_PATH . '/app/Http/Controllers/'; - public $controllerNamespace = 'App\\Http\\Controllers\\'; + public string $controllerPath = APP_PATH . '/app/Http/Controllers/'; + public string $controllerNamespace = 'App\\Http\\Controllers\\'; - public $module = null; + public ?string $module = null; - public $rules = []; - public $type = [ + public array $rules = []; + public array $type = [ 'int' => ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'], 'string' => ['char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext', 'enum'], 'date' => ['date'], @@ -40,10 +43,9 @@ abstract class GiiBase 'timestamp' => ['timestamp'], 'float' => ['float', 'double', 'decimal',], ]; - public $tableName = NULL; + public ?string $tableName = NULL; - /** @var Connection */ - public $db; + public ?Connection $db = null; /** * @param string $modelPath @@ -96,12 +98,12 @@ abstract class GiiBase /** - * @param \ReflectionClass $object + * @param ReflectionClass $object * @param $className * * @return string */ - public function getUseContent($object, $className) + public function getUseContent(ReflectionClass $object, $className): string { if (empty($object)) { return ''; @@ -126,10 +128,10 @@ abstract class GiiBase /** * @param $fields - * @return mixed|null + * @return mixed 返回表主键 * 返回表主键 */ - public function getPrimaryKey($fields) + public function getPrimaryKey($fields): mixed { $condition = ['PRI', 'UNI']; foreach ($fields as $field) { @@ -147,7 +149,7 @@ abstract class GiiBase * @param $className * @return string */ - private function getFilePath($className) + private function getFilePath($className): string { if (strpos($className, '\\')) { $className = str_replace('\\', '/', $className); @@ -160,13 +162,13 @@ abstract class GiiBase } /** - * @param \ReflectionClass $object + * @param ReflectionClass $object * @param $className * @param $method * @return string * @throws \Exception */ - public function getFuncLineContent($object, $className, $method) + public function getFuncLineContent(ReflectionClass $object, $className, $method): string { $fun = $object->getMethod($method); @@ -180,7 +182,7 @@ abstract class GiiBase /** * @return array */ - protected function getModelPath() + protected function getModelPath(): array { $dbName = $this->db->id; if (empty($dbName) || $dbName == 'db') { @@ -217,7 +219,7 @@ abstract class GiiBase * @param $val * @return string */ - protected function checkIsRequired($val) + #[Pure] protected function checkIsRequired($val): string { return strtolower($val['Null']) == 'no' && $val['Default'] === NULL ? 'true' : 'false'; } @@ -225,7 +227,7 @@ abstract class GiiBase /** * @return array */ - public function getFileLists() + public function getFileLists(): array { return $this->fileList; } diff --git a/Gii/GiiController.php b/Gii/GiiController.php index 7754b907..3eae73d7 100644 --- a/Gii/GiiController.php +++ b/Gii/GiiController.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Gii; +use Exception; use Snowflake\Snowflake; /** @@ -13,9 +14,9 @@ use Snowflake\Snowflake; class GiiController extends GiiBase { - public $className; + public string $className = ''; - public $fields; + public array $fields = []; public function __construct($className, $fields) { @@ -26,9 +27,9 @@ class GiiController extends GiiBase /** * @return string - * @throws \Exception + * @throws Exception */ - public function generate() + public function generate(): string { $path = $this->getControllerPath(); $modelPath = $this->getModelPath(); @@ -70,7 +71,7 @@ use {$model_namespace}\\{$managerName}; } $historyModel = "use {$model_namespace}\\{$managerName};"; - if (strpos($html, $historyModel) === false) { + if (!str_contains($html, $historyModel)) { $html .= $historyModel; } @@ -125,7 +126,7 @@ class {$controllerName}Controller extends Controller /** * @return array */ - private function getControllerPath() + private function getControllerPath(): array { $dbName = $this->db->id; if (empty($dbName) || $dbName == 'db') { @@ -159,7 +160,7 @@ class {$controllerName}Controller extends Controller * @return string * 新增 */ - public function controllerMethodAdd($fields, $className, $object = NULL) + public function controllerMethodAdd($fields, $className, $object = NULL): string { return ' /** @@ -184,7 +185,7 @@ class {$controllerName}Controller extends Controller * @return string * 通用 */ - public function controllerMethodLoadParam($fields, $className, $object = NULL) + public function controllerMethodLoadParam($fields, $className, $object = NULL): string { return ' /** @@ -205,7 +206,7 @@ class {$controllerName}Controller extends Controller * @return string * 构建更新 */ - public function controllerMethodUpdate($fields, $className, $object = NULL) + public function controllerMethodUpdate($fields, $className, $object = NULL): string { return ' /** @@ -234,7 +235,7 @@ class {$controllerName}Controller extends Controller * @return string * 构建更新 */ - public function controllerMethodBatchDelete($fields, $className, $object = NULL) + public function controllerMethodBatchDelete($fields, $className, $object = NULL): string { return ' /** @@ -269,7 +270,7 @@ class {$controllerName}Controller extends Controller * @return string * 构建详情 */ - public function controllerMethodDetail($fields, $className, $managerName) + public function controllerMethodDetail($fields, $className, $managerName): string { return ' /** @@ -293,7 +294,7 @@ class {$controllerName}Controller extends Controller * @return string * 构建删除操作 */ - public function controllerMethodDelete($fields, $className, $managerName) + public function controllerMethodDelete($fields, $className, $managerName): string { return ' /** @@ -329,7 +330,7 @@ class {$controllerName}Controller extends Controller * @return string * 构建查询列表 */ - public function controllerMethodList($fields, $className, $managerName, $object = NULL) + public function controllerMethodList($fields, $className, $managerName, $object = NULL): string { return ' /** @@ -366,7 +367,7 @@ class {$controllerName}Controller extends Controller '; } - private function getData($fields) + private function getData($fields): string { $html = ''; @@ -439,7 +440,12 @@ class {$controllerName}Controller extends Controller return $html; } - private function getMaxLength($fields) + + /** + * @param $fields + * @return int + */ + private function getMaxLength($fields): int { $length = 0; foreach ($fields as $key => $val) { @@ -448,7 +454,11 @@ class {$controllerName}Controller extends Controller return $length; } - private function getWhere($fields) + /** + * @param $fields + * @return string + */ + private function getWhere($fields): string { $html = ''; diff --git a/Gii/GiiInterceptor.php b/Gii/GiiInterceptor.php index 2d26f187..b54726c4 100644 --- a/Gii/GiiInterceptor.php +++ b/Gii/GiiInterceptor.php @@ -15,17 +15,14 @@ use Snowflake\Snowflake; class GiiInterceptor extends GiiBase { - public $tableName; - public $visible; - public $res; - public $fields; + public ?string $tableName = null; /** * @return string[] * @throws Exception */ - public function generate() + public function generate(): array { $managerName = $this->input->get('name', null); diff --git a/Gii/GiiLimits.php b/Gii/GiiLimits.php index 74352a94..dfa5395e 100644 --- a/Gii/GiiLimits.php +++ b/Gii/GiiLimits.php @@ -15,17 +15,14 @@ use Snowflake\Snowflake; class GiiLimits extends GiiBase { - public $tableName; - public $visible; - public $res; - public $fields; + public ?string $tableName = ''; /** * @return string[] * @throws Exception */ - public function generate() + public function generate(): array { $managerName = $this->input->get('name', null); diff --git a/Gii/GiiMiddleware.php b/Gii/GiiMiddleware.php index c4070d5e..f8ec7a17 100644 --- a/Gii/GiiMiddleware.php +++ b/Gii/GiiMiddleware.php @@ -15,17 +15,12 @@ use Snowflake\Snowflake; class GiiMiddleware extends GiiBase { - public $tableName; - public $visible; - public $res; - public $fields; - /** - * @return string[] + * @return array * @throws Exception */ - public function generate() + public function generate(): array { $managerName = $this->input->get('name', null); diff --git a/Gii/GiiModel.php b/Gii/GiiModel.php index dc1eddf0..4b40c76a 100644 --- a/Gii/GiiModel.php +++ b/Gii/GiiModel.php @@ -5,6 +5,8 @@ declare(strict_types=1); namespace Gii; use Database\Db; +use Exception; +use ReflectionException; use Snowflake\Snowflake; /** @@ -14,11 +16,10 @@ use Snowflake\Snowflake; class GiiModel extends GiiBase { - public $classFileName; - public $tableName; - public $visible; - public $res; - public $fields; + public ?string $classFileName; + public ?array $visible; + public ?array $res; + public ?array $fields; /** * ModelFile constructor. @@ -28,7 +29,7 @@ class GiiModel extends GiiBase * @param $res * @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->tableName = $tableName; @@ -38,10 +39,10 @@ class GiiModel extends GiiBase } /** - * @throws \ReflectionException - * @throws \Exception + * @throws ReflectionException + * @throws Exception */ - public function generate() + public function generate(): string { $class = ''; $modelPath = $this->getModelPath(); @@ -75,7 +76,7 @@ use Database\ActiveRecord;'; $createSql = $this->setCreateSql($this->tableName); - if (strpos($html, $createSql) === false) { + if (!str_contains($html, $createSql)) { $html .= ' ' . $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 = []; 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; } - if (strpos($html, 'get' . ucfirst($field['Field']) . 'Attribute') === false) { + if (!str_contains($html, 'get' . ucfirst($field['Field']) . 'Attribute')) { $strings[] = $get_function; } } @@ -247,7 +253,7 @@ class ' . $managerName . ' extends ActiveRecord * @return string * 创建表名称 */ - private function createTableName($field) + private function createTableName($field): string { $prefixed = $this->db->tablePrefix; @@ -271,7 +277,7 @@ class ' . $managerName . ' extends ActiveRecord * @return string * 创建效验规则 */ - private function createRules($fields) + private function createRules($fields): string { $data = []; foreach ($fields as $key => $val) { @@ -325,7 +331,7 @@ class ' . $managerName . ' extends ActiveRecord * @param $val * @return string */ - public function getLength($val) + public function getLength($val): string { $data = []; foreach ($val as $key => $_val) { @@ -339,7 +345,7 @@ class ' . $managerName . ' extends ActiveRecord if (empty($data)) return ''; $string = []; foreach ($data as $key => $_val) { - if (is_string($key) && strpos($key, ',') !== false) { + if (is_string($key) && str_contains($key, ',')) { $key = '[' . $key . ']'; } if (count($_val) == 1) { @@ -359,12 +365,12 @@ class ' . $managerName . ' extends ActiveRecord * @param $fields * @return string */ - public function getUnique($fields) + public function getUnique($fields): string { $data = []; foreach ($fields as $_key => $_val) { if ($_val['Extra'] == 'auto_increment') continue; - if (strpos($_val['Type'], 'unique') !== FALSE) { + if (str_contains($_val['Type'], 'unique')) { $data[] = $_val['Field']; } } @@ -379,7 +385,7 @@ class ' . $managerName . ' extends ActiveRecord * @param $val * @return string */ - public function getRequired($val) + public function getRequired($val): string { $data = []; foreach ($val as $_key => $_val) { @@ -409,7 +415,7 @@ class ' . $managerName . ' extends ActiveRecord * 'field' ,'字段類型' ,'是否必填' ,'字段长度' , '字段解释', * ) */ - private function createPrimary($fields) + private function createPrimary($fields): ?string { $field = $this->getPrimaryKey($fields); if (empty($field)) { @@ -422,7 +428,7 @@ class ' . $managerName . ' extends ActiveRecord /** * @return string */ - private function createDatabaseSource() + private function createDatabaseSource(): string { return ' /** @@ -439,9 +445,9 @@ class ' . $managerName . ' extends ActiveRecord /** * @param $table * @return string - * @throws \Exception + * @throws Exception */ - private function setCreateSql($table) + private function setCreateSql($table): string { $text = Db::showCreateSql($table, $this->db)['Create Table'] ?? ''; diff --git a/Gii/GiiTask.php b/Gii/GiiTask.php index 0c3c4e6e..f1dce09e 100644 --- a/Gii/GiiTask.php +++ b/Gii/GiiTask.php @@ -14,18 +14,12 @@ use Snowflake\Snowflake; class GiiTask extends GiiBase { - public $classFileName; - public $tableName; - public $visible; - public $res; - public $fields; - /** * @return string[] * @throws Exception */ - public function generate() + public function generate(): array { $managerName = $this->input->get('name', null); diff --git a/HttpServer/Abstracts/Callback.php b/HttpServer/Abstracts/Callback.php index 111f481f..ac29a7c5 100644 --- a/HttpServer/Abstracts/Callback.php +++ b/HttpServer/Abstracts/Callback.php @@ -86,7 +86,7 @@ abstract class Callback extends Application * @throws \PHPMailer\PHPMailer\Exception * @throws ConfigException */ - private function createEmail() + private function createEmail(): PHPMailer { $mail = new PHPMailer(true); $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output diff --git a/HttpServer/Abstracts/ServerBase.php b/HttpServer/Abstracts/ServerBase.php index b730f314..2a888f80 100644 --- a/HttpServer/Abstracts/ServerBase.php +++ b/HttpServer/Abstracts/ServerBase.php @@ -25,7 +25,7 @@ abstract class ServerBase extends Application /** * @return Server */ - public function getServer() + public function getServer(): Server { return $this->server; } diff --git a/HttpServer/Action.php b/HttpServer/Action.php index 8c4ebb43..14aaf259 100644 --- a/HttpServer/Action.php +++ b/HttpServer/Action.php @@ -5,6 +5,7 @@ namespace HttpServer; use Exception; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\Input; use Snowflake\Exception\ComponentException; use Snowflake\Snowflake; @@ -87,7 +88,7 @@ trait Action /** * WorkerId Iterator */ - private function masterIdCheck() + private function masterIdCheck(): bool { echo '.'; $files = new \DirectoryIterator($this->getWorkerPath()); @@ -110,7 +111,7 @@ trait Action /** * @return string */ - private function getWorkerPath() + #[Pure] private function getWorkerPath(): string { return "glob://" . ltrim(APP_PATH, '/') . '/storage/worker/*.sock'; } @@ -120,7 +121,7 @@ trait Action * @param $port * @return bool|array */ - private function isUse($port) + private function isUse($port): bool|array { if (empty($port)) { return false; diff --git a/HttpServer/Application.php b/HttpServer/Application.php index bc287a64..4f32c5f4 100644 --- a/HttpServer/Application.php +++ b/HttpServer/Application.php @@ -28,23 +28,23 @@ class Application extends HttpService } /** - * @param $methods + * @param $name * @return mixed * @throws Exception */ - public function __get($methods) + public function __get($name): mixed { - if (method_exists($this, $methods)) { - return $this->{$methods}(); + if (method_exists($this, $name)) { + return $this->{$name}(); } - $handler = 'get' . ucfirst($methods); + $handler = 'get' . ucfirst($name); if (method_exists($this, $handler)) { return $this->{$handler}(); } - if (property_exists($this, $methods)) { - return $this->$methods; + if (property_exists($this, $name)) { + 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); } diff --git a/HttpServer/Client/Client.php b/HttpServer/Client/Client.php index 0500ed94..c16b52d9 100644 --- a/HttpServer/Client/Client.php +++ b/HttpServer/Client/Client.php @@ -10,7 +10,7 @@ declare(strict_types=1); namespace HttpServer\Client; use Exception; -use Swoole\Coroutine; +use JetBrains\PhpStorm\Pure; use Swoole\Coroutine\Http\Client as SClient; /** @@ -22,17 +22,17 @@ class Client extends ClientAbstracts /** * @param string $method - * @param $url - * @param array $data - * @return array|mixed|Result + * @param $path + * @param array $params + * @return array|string|Result * @throws Exception */ - public function request(string $method, $url, $data = []) + public function request(string $method, $path, $params = []): array|string|Result { return $this->setMethod($method) ->coroutine( - $this->matchHost($url), - $this->paramEncode($data) + $this->matchHost($path), + $this->paramEncode($params) ); } @@ -40,11 +40,11 @@ class Client extends ClientAbstracts /** * @param $url * @param array $data - * @return array|mixed|Result + * @return array|string|Result * @throws Exception * 使用swoole协程方式请求 */ - private function coroutine($url, $data = []) + private function coroutine($url, $data = []): array|string|Result { try { $client = $this->generate_client($data, ...$url); @@ -77,7 +77,7 @@ class Client extends ClientAbstracts * @param $path * @return SClient */ - private function generate_client($data, $host, $isHttps, $path) + private function generate_client($data, $host, $isHttps, $path): SClient { if ($isHttps || $this->isSSL()) { $client = new SClient($host, 443, $this->isSSL()); @@ -112,7 +112,7 @@ class Client extends ClientAbstracts /** * @return array */ - private function settings() + #[Pure] private function settings(): array { $sslCert = $this->getSslCertFile(); $sslKey = $this->getSslKeyFile(); diff --git a/HttpServer/Client/ClientAbstracts.php b/HttpServer/Client/ClientAbstracts.php index d75c887a..44186be1 100644 --- a/HttpServer/Client/ClientAbstracts.php +++ b/HttpServer/Client/ClientAbstracts.php @@ -6,6 +6,7 @@ namespace HttpServer\Client; use Closure; use Exception; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\Component; use Snowflake\Core\Help; use Snowflake\Core\JSON; @@ -57,33 +58,32 @@ abstract class ClientAbstracts extends Component implements IClient /** * @return static */ - public static function NewRequest() + #[Pure] public static function NewRequest(): static { return new static(); } /** - * @param $url - * @param array $data - * @return array|mixed|Result + * @param $path + * @param array $params + * @return array|int|string|Result * @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 array $data - * @return array|mixed|Result - * @throws + * @param string $path + * @param array $params + * @return array|int|string|Result */ - 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 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); } /** - * @param $url - * @param array $data - * @return array|mixed|Result - * @throws + * @param string $path + * @param array $params + * @return array|int|string|Result */ - public function get($url, $data = []) + public function get(string $path, array $params = []): array|int|string|Result { - return $this->request(self::GET, $url, $data); - } - - /** - * @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); + return $this->request(self::GET, $path, $params); } /** * @param string $path * @param array $params - * @return mixed - * @throws Exception + * @return array|int|string|Result */ - 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); @@ -155,10 +151,9 @@ abstract class ClientAbstracts extends Component implements IClient /** * @param string $path * @param array $params - * @return mixed - * @throws Exception + * @return array|int|string|Result */ - 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); } @@ -175,7 +170,7 @@ abstract class ClientAbstracts extends Component implements IClient /** * @return int */ - protected function getHostPort() + protected function getHostPort(): int { if (!empty($this->getPort())) { return $this->getPort(); @@ -196,10 +191,6 @@ abstract class ClientAbstracts extends Component implements IClient $this->host = System::gethostbyname($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 */ - public function setHeaders(array $headers) + public function setHeaders(array $header): array { - if (empty($headers)) { + if (empty($header)) { return []; } - foreach ($headers as $key => $val) { + foreach ($header as $key => $val) { $this->header[$key] = $val; } 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 */ - public function setMethod(string $method): self + public function setMethod(string $value): self { - $this->method = $method; + $this->method = $value; 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 */ - public function getPort(): int + #[Pure] public function getPort(): int { if ($this->isSSL()) { return 443; @@ -496,7 +487,7 @@ abstract class ClientAbstracts extends Component implements IClient * @param $host * @return string|string[] */ - protected function replaceHost($host) + protected function replaceHost($host): array|string { if ($this->isHttp($host)) { return str_replace('http://', '', $host); @@ -512,7 +503,7 @@ abstract class ClientAbstracts extends Component implements IClient * @param $url * @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); } @@ -521,18 +512,18 @@ abstract class ClientAbstracts extends Component implements IClient * @param $url * @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 * @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 * @return mixed */ - protected function mergeParams($newData) + protected function mergeParams($newData): mixed { if (empty($this->getData())) { return $this->toRequest($newData); @@ -559,9 +550,9 @@ abstract class ClientAbstracts extends Component implements IClient /** * @param $data - * @return false|mixed|string + * @return string */ - protected function toRequest($data) + protected function toRequest($data): string { if (is_string($data)) { return $data; @@ -572,9 +563,9 @@ abstract class ClientAbstracts extends Component implements IClient } else if (isset($this->header['content-type'])) { $contentType = $this->header['content-type']; } - if (strpos($contentType, 'json') !== false) { + if (str_contains($contentType, 'json')) { return Help::toJson($data); - } else if (strpos($contentType, 'xml') !== false) { + } else if (str_contains($contentType, 'xml')) { return Help::toXml($data); } else { return http_build_query($data); @@ -585,21 +576,21 @@ abstract class ClientAbstracts extends Component implements IClient /** * @param $data * @param $body - * @return mixed + * @return array */ - protected function resolve($data, $body) + protected function resolve($data, $body): array { if (is_array($body)) { return $body; } $type = $data['content-type'] ?? $data['Content-Type'] ?? 'text/html'; - if (strpos($type, 'text/html') !== false) { + if (str_contains($type, 'text/html')) { return $body; - } else if (strpos($type, 'json') !== false) { + } else if (str_contains($type, 'json')) { return json_decode($body, true); - } else if (strpos($type, 'xml') !== false) { + } else if (str_contains($type, 'xml')) { return Help::xmlToArray($body); - } else if (strpos($type, 'plain') !== false) { + } else if (str_contains($type, 'plain')) { return Help::toArray($body); } return $body; @@ -609,12 +600,12 @@ abstract class ClientAbstracts extends Component implements IClient /** * @param $body * @param $_data - * @param $header - * @param $statusCode - * @return array|mixed|Result + * @param array $header + * @param int $statusCode + * @return mixed 构建返回体 * 构建返回体 */ - protected function structure($body, $_data, $header = [], $statusCode = 200) + protected function structure($body, $_data, $header = [], $statusCode = 200): mixed { if ($this->callback instanceof Closure) { $result = call_user_func($this->callback, $body, $_data, $header); @@ -631,7 +622,7 @@ abstract class ClientAbstracts extends Component implements IClient * @param $statusCode * @return Result */ - private function parseResult($body, $header, $statusCode) + private function parseResult($body, $header, $statusCode): Result { if (is_string($body)) { $result['code'] = 0; @@ -649,9 +640,9 @@ abstract class ClientAbstracts extends Component implements IClient /** * @param $body - * @return array|mixed|string + * @return mixed */ - protected function searchMessageByData($body) + protected function searchMessageByData($body): mixed { $parent = []; if (empty($this->errorMsgField)) { @@ -682,7 +673,7 @@ abstract class ClientAbstracts extends Component implements IClient * @return bool * check isPost Request */ - public function isPost() + #[Pure] public function isPost(): bool { return strtolower($this->method) === self::POST; } @@ -693,7 +684,7 @@ abstract class ClientAbstracts extends Component implements IClient * * check isGet Request */ - public function isGet() + #[Pure] public function isGet(): bool { return strtolower($this->method) === self::GET; } @@ -704,7 +695,7 @@ abstract class ClientAbstracts extends Component implements IClient * @return array|string * 将请求参数进行编码 */ - protected function paramEncode($arr) + #[Pure] protected function paramEncode($arr): array|string { if (!is_array($arr)) { return $arr; @@ -722,15 +713,15 @@ abstract class ClientAbstracts extends Component implements IClient /** * @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) { return $this->defaultString($string); } [$isHttps, $domain, $port, $path] = $parse; - if (strpos($domain, ':' . $port) !== false) { + if (str_contains($domain, ':' . $port)) { $domain = str_replace(':' . $port, '', $domain); } $this->port = $isHttps ? 443 : $this->port; @@ -753,7 +744,7 @@ abstract class ClientAbstracts extends Component implements IClient * @param $string * @return array */ - private function defaultString($string) + private function defaultString($string): array { $host = $this->getHost(); if ($string == '/') { @@ -770,7 +761,7 @@ abstract class ClientAbstracts extends Component implements IClient * @param $params * @return string */ - protected function joinGetParams($path, $params) + #[Pure] protected function joinGetParams($path, $params): string { if (empty($params)) { return $path; @@ -778,7 +769,7 @@ abstract class ClientAbstracts extends Component implements IClient if (!is_string($params)) { $params = http_build_query($params); } - if (strpos($path, '?') !== false) { + if (str_contains($path, '?')) { [$path, $getParams] = explode('?', $path); } if (!isset($getParams) || empty($getParams)) { @@ -795,7 +786,7 @@ abstract class ClientAbstracts extends Component implements IClient * @param $header * @return Result */ - protected function fail($code, $message, $data = [], $header = []) + protected function fail($code, $message, $data = [], $header = []): Result { return new Result([ 'code' => $code, diff --git a/HttpServer/Client/Curl.php b/HttpServer/Client/Curl.php index 938a848e..0b083c11 100644 --- a/HttpServer/Client/Curl.php +++ b/HttpServer/Client/Curl.php @@ -5,6 +5,7 @@ namespace HttpServer\Client; use Exception; +use JetBrains\PhpStorm\Pure; /** * Class Curl @@ -14,13 +15,13 @@ class Curl extends ClientAbstracts { /** - * @param $path * @param $method + * @param $path * @param array $params - * @return bool|string + * @return Result|bool|array|string * @throws Exception */ - public function request($method, $path, $params = []) + public function request($method, $path, $params = []): Result|bool|array|string { if ($method == self::GET) { $path = $this->joinGetParams($path, $params); @@ -33,10 +34,10 @@ class Curl extends ClientAbstracts * @param $path * @param $method * @param $params - * @return mixed|resource + * @return mixed * @throws Exception */ - private function getCurlHandler($path, $method, $params) + private function getCurlHandler($path, $method, $params): mixed { [$host, $isHttps, $path] = $this->matchHost($path); @@ -71,7 +72,7 @@ class Curl extends ClientAbstracts * @return bool * @throws Exception */ - private function curlHandlerSslSet($resource) + private function curlHandlerSslSet($resource): bool { if (!empty($this->ssl_key)) { if (!file_exists($this->ssl_key)) { @@ -129,10 +130,10 @@ class Curl extends ClientAbstracts /** * @param $curl - * @return bool|string + * @return Result|bool|array|string * @throws Exception */ - private function execute($curl) + private function execute($curl): Result|bool|array|string { $output = curl_exec($curl); if ($output === false) { @@ -146,10 +147,10 @@ class Curl extends ClientAbstracts * @param $curl * @param $output * @param array $params - * @return array|Result|mixed + * @return mixed * @throws Exception */ - private function parseResponse($curl, $output, $params = []) + private function parseResponse($curl, $output, $params = []): mixed { curl_close($curl); if ($output === FALSE) { @@ -170,9 +171,9 @@ class Curl extends ClientAbstracts * @return array * @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.'); } @@ -193,7 +194,7 @@ class Curl extends ClientAbstracts * @param $headers * @return array */ - private function headerFormat($headers) + private function headerFormat($headers): array { $_tmp = []; foreach ($headers as $key => $val) { @@ -208,7 +209,7 @@ class Curl extends ClientAbstracts /** * @return array */ - private function parseHeaderMat() + #[Pure] private function parseHeaderMat(): array { $headers = []; foreach ($this->getHeader() as $key => $val) { diff --git a/HttpServer/Client/Http2.php b/HttpServer/Client/Http2.php index 90e9999b..d4c119f3 100644 --- a/HttpServer/Client/Http2.php +++ b/HttpServer/Client/Http2.php @@ -25,10 +25,10 @@ class Http2 extends Component * @param $path * @param array $params * @param int $timeout - * @return mixed + * @return Result * @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->send($this->getRequest($domain, $path, 'GET', $params)); @@ -41,10 +41,10 @@ class Http2 extends Component * @param $path * @param array $params * @param int $timeout - * @return mixed + * @return Result * @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->send($this->getRequest($domain, $path, 'POST', $params)); @@ -57,10 +57,10 @@ class Http2 extends Component * @param $path * @param array $params * @param int $timeout - * @return mixed + * @return Result * @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->send($this->getRequest($domain, $path, 'DELETE', $params)); @@ -76,7 +76,7 @@ class Http2 extends Component * @return mixed * @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->send($this->getRequest($domain, $path, 'PUT', $params)); @@ -92,7 +92,7 @@ class Http2 extends Component * @return Request * @throws Exception */ - public function getRequest($domain, $path, $method, $params) + public function getRequest($domain, $path, $method, $params): Request { if (Context::hasContext($domain . $path)) { $req = Context::getContext($domain . $path); @@ -123,7 +123,7 @@ class Http2 extends Component * @return H2Client * @throws Exception */ - private function getClient($domain, $path, $timeout = -1) + private function getClient($domain, $path, $timeout = -1): H2Client { if (Context::hasContext($domain)) { return Context::getContext($domain); diff --git a/HttpServer/Client/HttpClient.php b/HttpServer/Client/HttpClient.php index 4ed3a2f8..5a7a4f46 100644 --- a/HttpServer/Client/HttpClient.php +++ b/HttpServer/Client/HttpClient.php @@ -4,6 +4,7 @@ namespace HttpServer\Client; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\Component; use Snowflake\Snowflake; use Swoole\Coroutine; @@ -28,7 +29,7 @@ class HttpClient extends Component /** * @return Http2 */ - public static function http2() + #[Pure] public static function http2(): Http2 { return Snowflake::app()->http2; } diff --git a/HttpServer/Client/HttpParse.php b/HttpServer/Client/HttpParse.php index 6ad68d7e..5500beb3 100644 --- a/HttpServer/Client/HttpParse.php +++ b/HttpServer/Client/HttpParse.php @@ -44,7 +44,7 @@ class HttpParse * @return string * @throws Exception */ - public static function parse($data) + public static function parse($data): string { $tmp = []; if (is_string($data)) { @@ -65,7 +65,7 @@ class HttpParse * @return string * @throws Exception */ - private static function ifElse($t, $qt) + private static function ifElse($t, $qt): string { if (is_numeric($qt)) { return $t . '=' . $qt; diff --git a/HttpServer/Client/Result.php b/HttpServer/Client/Result.php index 1e3b6109..9fa1412e 100644 --- a/HttpServer/Client/Result.php +++ b/HttpServer/Client/Result.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace HttpServer\Client; use Exception; +use JetBrains\PhpStorm\Pure; /** * Class Result @@ -45,7 +46,7 @@ class Result * @param $data * @return $this */ - public function setAssignment($data) + public function setAssignment($data): static { foreach ($data as $key => $val) { if (!property_exists($this, $key)) { @@ -59,9 +60,9 @@ class Result /** * @param $name - * @return mixed|null + * @return mixed */ - public function __get($name) + public function __get($name): mixed { return $this->$name; } @@ -69,9 +70,9 @@ class Result /** * @param $name * @param $value - * @return $this|void + * @return $this */ - public function __set($name, $value) + public function __set($name, $value): static { $this->$name = $value; @@ -81,7 +82,7 @@ class Result /** * @return array */ - public function getHeaders() + public function getHeaders(): array { $_tmp = []; if (!is_array($this->header)) { @@ -103,7 +104,7 @@ class Result /** * @return array */ - public function getTime() + public function getTime(): array { return [ 'startTime' => $this->startTime, @@ -118,7 +119,7 @@ class Result * @return $this * @throws Exception */ - public function setAttr($key, $data) + public function setAttr($key, $data): static { if (!property_exists($this, $key)) { throw new Exception('未查找到相应对象属性'); @@ -131,7 +132,7 @@ class Result * @param int $status * @return bool */ - public function isResultsOK($status = 0) + public function isResultsOK($status = 0): bool { if (!$this->httpIsOk()) { return false; @@ -142,7 +143,7 @@ class Result /** * @return bool */ - public function httpIsOk() + #[Pure] public function httpIsOk(): bool { return in_array($this->httpStatus, [100, 101, 200, 201, 202, 203, 204, 205, 206]); } @@ -150,7 +151,7 @@ class Result /** * @return mixed */ - public function getBody() + public function getBody(): mixed { return $this->data; } @@ -158,7 +159,7 @@ class Result /** * @return mixed */ - public function getMessage() + public function getMessage(): mixed { return $this->message; } @@ -166,7 +167,7 @@ class Result /** * @return mixed */ - public function getCode() + public function getCode(): mixed { return $this->code; } diff --git a/HttpServer/Command.php b/HttpServer/Command.php index 501120f8..c25f4985 100644 --- a/HttpServer/Command.php +++ b/HttpServer/Command.php @@ -27,11 +27,11 @@ class Command extends \Console\Command /** * @param Input $dtl - * @return mixed|void + * @return string * @throws Exception * @throws ConfigException */ - public function onHandler(Input $dtl) + public function onHandler(Input $dtl): string { $manager = Snowflake::app()->server; $manager->setDaemon($dtl->get('daemon', 0)); @@ -48,7 +48,7 @@ class Command extends \Console\Command if ($dtl->get('action') == 'stop') { return 'shutdown success.'; } - $manager->start(); + return $manager->start(); } } diff --git a/HttpServer/Controller.php b/HttpServer/Controller.php index 6492d66d..7fa2d03c 100644 --- a/HttpServer/Controller.php +++ b/HttpServer/Controller.php @@ -15,8 +15,6 @@ use Exception; use HttpServer\Route\Router; use Kafka\Producer; use Snowflake\Abstracts\BaseGoto; -use Snowflake\Annotation\Annotation; -use Snowflake\Cache\Memcached; use Snowflake\Cache\Redis; use Snowflake\Error\Logger; use Snowflake\Event; @@ -30,7 +28,6 @@ use Snowflake\Snowflake; * Class WebController * @package Snowflake\Snowflake\Web * @property BaseGoto $goto - * @property Annotation $annotation * @property Event $event * @property Router $router * @property SPool $pool @@ -38,7 +35,6 @@ use Snowflake\Snowflake; * @property Server $server * @property DatabasesProviders $db * @property Connection $connections - * @property Memcached $memcached * @property Logger $logger * @property Jwt $jwt * @property Client $client @@ -131,23 +127,23 @@ class Controller extends Application /** - * @param $methods + * @param $name * @return mixed * @throws ComponentException */ - public function __get($methods): mixed + public function __get($name): mixed { // TODO: Change the autogenerated stub - if (property_exists($this, $methods)) { - return $this->$methods; + if (property_exists($this, $name)) { + return $this->$name; } - $method = 'get' . ucfirst($methods); + $method = 'get' . ucfirst($name); if (method_exists($this, $method)) { return $this->{$method}(); } - return Snowflake::app()->get($methods); + return Snowflake::app()->get($name); } diff --git a/HttpServer/Events/OnClose.php b/HttpServer/Events/OnClose.php index f59b1531..b9644e10 100644 --- a/HttpServer/Events/OnClose.php +++ b/HttpServer/Events/OnClose.php @@ -6,10 +6,6 @@ namespace HttpServer\Events; use Annotation\Route\Socket; 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 Snowflake\Event; use Snowflake\Exception\ComponentException; @@ -17,7 +13,6 @@ use Snowflake\Snowflake; use Swoole\Coroutine; use Swoole\Server; use Exception; -use Swoole\Http\Server as HServer; use Swoole\WebSocket\Server as WServer; /** diff --git a/HttpServer/Events/OnFinish.php b/HttpServer/Events/OnFinish.php index 7a1c7cff..d36f6fd8 100644 --- a/HttpServer/Events/OnFinish.php +++ b/HttpServer/Events/OnFinish.php @@ -8,6 +8,10 @@ use Exception; use HttpServer\Abstracts\Callback; use Swoole\Server; +/** + * Class OnFinish + * @package HttpServer\Events + */ class OnFinish extends Callback { /** diff --git a/HttpServer/Events/OnHandshake.php b/HttpServer/Events/OnHandshake.php index f9de6ede..085d8f4e 100644 --- a/HttpServer/Events/OnHandshake.php +++ b/HttpServer/Events/OnHandshake.php @@ -7,7 +7,6 @@ namespace HttpServer\Events; use Annotation\Route\Socket; use Exception; use HttpServer\Abstracts\Callback; -use HttpServer\Route\Annotation\Websocket as AWebsocket; use Snowflake\Event; use Snowflake\Exception\ComponentException; use Snowflake\Snowflake; @@ -62,7 +61,7 @@ class OnHandshake extends Callback * @param int $code * @return false */ - private function disconnect($response, $code = 500) + private function disconnect($response, $code = 500): bool { $response->status($code); $response->end(); @@ -73,10 +72,10 @@ class OnHandshake extends Callback /** * @param SRequest $request * @param SResponse $response - * @return mixed|void - * @throws Exception + * @return void + * @throws ComponentException */ - public function onHandler(SRequest $request, SResponse $response) + public function onHandler(SRequest $request, SResponse $response): void { Coroutine::defer(function () { fire(Event::EVENT_AFTER_REQUEST); diff --git a/HttpServer/Events/OnManagerStart.php b/HttpServer/Events/OnManagerStart.php index 466c5c4b..5ddd2555 100644 --- a/HttpServer/Events/OnManagerStart.php +++ b/HttpServer/Events/OnManagerStart.php @@ -4,12 +4,11 @@ declare(strict_types=1); namespace HttpServer\Events; +use Exception; use HttpServer\Abstracts\Callback; use Snowflake\Abstracts\Config; use Snowflake\Event; use Snowflake\Snowflake; -use Swoole\Coroutine\System; -use Swoole\Process; use Swoole\Server; class OnManagerStart extends Callback @@ -17,7 +16,7 @@ class OnManagerStart extends Callback /** * @param Server $server - * @throws \Exception + * @throws Exception */ public function onHandler(Server $server) { diff --git a/HttpServer/Events/OnManagerStop.php b/HttpServer/Events/OnManagerStop.php index 57a248d5..079e8b64 100644 --- a/HttpServer/Events/OnManagerStop.php +++ b/HttpServer/Events/OnManagerStop.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace HttpServer\Events; +use Exception; use HttpServer\Abstracts\Callback; use Snowflake\Event; use Snowflake\Snowflake; @@ -18,7 +19,7 @@ class OnManagerStop extends Callback /** * @param $server - * @throws \Exception + * @throws Exception */ public function onHandler(Server $server) { diff --git a/HttpServer/Events/OnPacket.php b/HttpServer/Events/OnPacket.php index 5361ebbf..6dc75b27 100644 --- a/HttpServer/Events/OnPacket.php +++ b/HttpServer/Events/OnPacket.php @@ -6,7 +6,6 @@ namespace HttpServer\Events; use Closure; use HttpServer\Abstracts\Callback; -use Snowflake\Core\JSON; use Snowflake\Event; use Snowflake\Snowflake; use Swoole\Server; @@ -36,7 +35,7 @@ class OnPacket extends Callback * @return mixed * @throws Exception */ - public function onHandler(Server $server, string $data, array $clientInfo) + public function onHandler(Server $server, string $data, array $clientInfo): mixed { try { $data = DataResolve::unpack($this->unpack, $clientInfo['address'], $clientInfo['port'], $data); diff --git a/HttpServer/Events/OnReceive.php b/HttpServer/Events/OnReceive.php index 3aa60eff..e59b78eb 100644 --- a/HttpServer/Events/OnReceive.php +++ b/HttpServer/Events/OnReceive.php @@ -36,7 +36,7 @@ class OnReceive extends Callback * @return mixed * @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 { $client = $server->getClientInfo($fd, $reID); diff --git a/HttpServer/Events/OnRequest.php b/HttpServer/Events/OnRequest.php index 6233388d..f1366aca 100644 --- a/HttpServer/Events/OnRequest.php +++ b/HttpServer/Events/OnRequest.php @@ -7,13 +7,9 @@ namespace HttpServer\Events; use Exception; use HttpServer\Abstracts\Callback; use HttpServer\Exception\ExitException; -use HttpServer\Http\Context; use HttpServer\Http\Request as HRequest; use HttpServer\Http\Response as HResponse; -use HttpServer\Route\Node; -use HttpServer\Service\Http; use ReflectionException; -use Snowflake\Abstracts\Config; use Snowflake\Core\JSON; use Snowflake\Event; use Snowflake\Exception\ComponentException; diff --git a/HttpServer/Events/OnShutdown.php b/HttpServer/Events/OnShutdown.php index 8c65cef0..b859a71d 100644 --- a/HttpServer/Events/OnShutdown.php +++ b/HttpServer/Events/OnShutdown.php @@ -6,18 +6,10 @@ namespace HttpServer\Events; use Exception; 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\Exception\ComponentException; -use Snowflake\Exception\ConfigException; use Snowflake\Snowflake; -use Swoole\Coroutine; use Swoole\Server; -use Closure; /** * Class OnShutdown diff --git a/HttpServer/Events/OnStart.php b/HttpServer/Events/OnStart.php index 459ff343..4cf204ac 100644 --- a/HttpServer/Events/OnStart.php +++ b/HttpServer/Events/OnStart.php @@ -4,12 +4,11 @@ declare(strict_types=1); namespace HttpServer\Events; +use Exception; use HttpServer\Abstracts\Callback; use Snowflake\Abstracts\Config; use Snowflake\Event; use Snowflake\Snowflake; -use Swoole\Coroutine\System; -use Swoole\Process; use Swoole\Server; class OnStart extends Callback @@ -17,7 +16,7 @@ class OnStart extends Callback /** * @param Server $server - * @throws \Exception + * @throws Exception */ public function onHandler(Server $server) { diff --git a/HttpServer/Events/OnWorkerStart.php b/HttpServer/Events/OnWorkerStart.php index 12e67a91..d5268a90 100644 --- a/HttpServer/Events/OnWorkerStart.php +++ b/HttpServer/Events/OnWorkerStart.php @@ -6,15 +6,10 @@ namespace HttpServer\Events; use Exception; 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\Error\Logger; use Snowflake\Event; use Snowflake\Exception\ConfigException; use Snowflake\Snowflake; -use Swoole\Coroutine\System; use Swoole\Server; /** diff --git a/HttpServer/Events/OnWorkerStop.php b/HttpServer/Events/OnWorkerStop.php index 8dbdd1c2..796cda10 100644 --- a/HttpServer/Events/OnWorkerStop.php +++ b/HttpServer/Events/OnWorkerStop.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace HttpServer\Events; +use Exception; use HttpServer\Abstracts\Callback; /** @@ -17,7 +18,7 @@ class OnWorkerStop extends Callback /** * @param $server * @param $worker_id - * @throws \Exception + * @throws Exception */ public function onHandler($server, $worker_id) { diff --git a/HttpServer/Events/Utility/DataResolve.php b/HttpServer/Events/Utility/DataResolve.php index 478266d3..064ad094 100644 --- a/HttpServer/Events/Utility/DataResolve.php +++ b/HttpServer/Events/Utility/DataResolve.php @@ -65,11 +65,11 @@ class DataResolve * @param $address * @param $port * @param $data - * @return array|mixed + * @return mixed * @throws NotFindClassException * @throws ReflectionException */ - private static function callbackResolve($callback, $address, $port, $data) + private static function callbackResolve($callback, $address, $port, $data): mixed { if ($callback instanceof Closure) { if (empty($address) && empty($port)) { diff --git a/HttpServer/Exception/AuthException.php b/HttpServer/Exception/AuthException.php index 1272fe36..7c24955b 100644 --- a/HttpServer/Exception/AuthException.php +++ b/HttpServer/Exception/AuthException.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace HttpServer\Exception; +use JetBrains\PhpStorm\Pure; use Throwable; /** @@ -17,8 +18,15 @@ use Throwable; */ 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); } diff --git a/HttpServer/Exception/ExitException.php b/HttpServer/Exception/ExitException.php index 3475161f..6293e44a 100644 --- a/HttpServer/Exception/ExitException.php +++ b/HttpServer/Exception/ExitException.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace HttpServer\Exception; +use JetBrains\PhpStorm\Pure; use Throwable; /** @@ -19,7 +20,7 @@ class ExitException extends \Exception * @param int $code * @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); } diff --git a/HttpServer/Http/Context.php b/HttpServer/Http/Context.php index 67f7c43f..2bae7ae9 100644 --- a/HttpServer/Http/Context.php +++ b/HttpServer/Http/Context.php @@ -145,10 +145,10 @@ class Context extends BaseContext } /** - * @param $id - * @param null $key + * @param string $id + * @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)) { return; diff --git a/HttpServer/Http/Formatter/HtmlFormatter.php b/HttpServer/Http/Formatter/HtmlFormatter.php index 4c54c80a..200145ca 100644 --- a/HttpServer/Http/Formatter/HtmlFormatter.php +++ b/HttpServer/Http/Formatter/HtmlFormatter.php @@ -10,6 +10,7 @@ declare(strict_types=1); namespace HttpServer\Http\Formatter; +use Exception; use Snowflake\Core\JSON; use HttpServer\Application; use Swoole\Http\Response; @@ -32,7 +33,7 @@ class HtmlFormatter extends Application implements IFormatter /** * @param $context * @return $this - * @throws \Exception + * @throws Exception */ public function send($context): static { diff --git a/HttpServer/Http/Formatter/XmlFormatter.php b/HttpServer/Http/Formatter/XmlFormatter.php index fcb69065..30e4cb80 100644 --- a/HttpServer/Http/Formatter/XmlFormatter.php +++ b/HttpServer/Http/Formatter/XmlFormatter.php @@ -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; $this->clear(); diff --git a/HttpServer/Http/Request.php b/HttpServer/Http/Request.php index 804b35ee..cdb711aa 100644 --- a/HttpServer/Http/Request.php +++ b/HttpServer/Http/Request.php @@ -6,7 +6,10 @@ namespace HttpServer\Http; use Exception; use HttpServer\Application; use HttpServer\IInterface\AuthIdentity; +use JetBrains\PhpStorm\Pure; +use ReflectionException; use Snowflake\Core\JSON; +use Snowflake\Exception\ComponentException; use Snowflake\Exception\NotFindClassException; use Snowflake\Snowflake; use function router; @@ -77,7 +80,7 @@ class Request extends Application /** * @return bool */ - public function isFavicon() + public function isFavicon(): bool { return $this->getUri() === 'favicon.ico'; } @@ -85,7 +88,7 @@ class Request extends Application /** * @return mixed */ - public function getIdentity() + public function getIdentity(): mixed { return $this->_grant; } @@ -93,7 +96,7 @@ class Request extends Application /** * @return bool */ - public function isHead() + public function isHead(): bool { $result = $this->headers->getHeader('request_method') == 'head'; if ($result) { @@ -108,7 +111,7 @@ class Request extends Application * @param $status * @return mixed */ - public function setStatus($status) + public function setStatus($status): mixed { return $this->statusCode = $status; } @@ -116,7 +119,7 @@ class Request extends Application /** * @return int */ - public function getStatus() + public function getStatus(): int { return $this->statusCode; } @@ -124,7 +127,7 @@ class Request extends Application /** * @return bool */ - public function getIsPackage() + public function getIsPackage(): bool { return $this->headers->getHeader('request_method') == 'package'; } @@ -132,7 +135,7 @@ class Request extends Application /** * @return bool */ - public function getIsReceive() + public function getIsReceive(): bool { return $this->headers->getHeader('request_method') == 'receive'; } @@ -150,7 +153,7 @@ class Request extends Application /** * @return bool */ - public function hasGrant() + public function hasGrant(): bool { return $this->_grant !== null; } @@ -159,7 +162,7 @@ class Request extends Application /** * @return string */ - public function parseUri() + public function parseUri(): string { $array = []; $explode = explode('/', $this->headers->getHeader('request_uri')); @@ -175,15 +178,15 @@ class Request extends Application /** * @return string[] */ - public function getExplode() + public function getExplode(): array { return $this->explode; } /** - * @return mixed|string + * @return string */ - public function getCurrent() + #[Pure] public function getCurrent(): string { return current($this->explode); } @@ -191,7 +194,7 @@ class Request extends Application /** * @return string */ - public function getUri() + public function getUri(): string { if (!$this->headers) { return 'command exec.'; @@ -207,10 +210,10 @@ class Request extends Application /** - * @return mixed|string - * @throws Exception + * @return mixed + * @throws ComponentException */ - public function adapter() + public function adapter(): mixed { if (!$this->isHead()) { return router()->dispatch(); @@ -222,7 +225,7 @@ class Request extends Application /** * @return string|null */ - public function getPlatform() + public function getPlatform(): ?string { $user = $this->headers->getHeader('user-agent'); $match = preg_match('/\(.*\)?/', $user, $output); @@ -245,7 +248,7 @@ class Request extends Application /** * @return bool */ - public function isIos() + public function isIos(): bool { return $this->getPlatform() == static::PLATFORM_IPHONE; } @@ -253,7 +256,7 @@ class Request extends Application /** * @return bool */ - public function isAndroid() + public function isAndroid(): bool { return $this->getPlatform() == static::PLATFORM_ANDROID; } @@ -261,7 +264,7 @@ class Request extends Application /** * @return bool */ - public function isMacOs() + public function isMacOs(): bool { return $this->getPlatform() == static::PLATFORM_MAC_OX; } @@ -269,7 +272,7 @@ class Request extends Application /** * @return bool */ - public function isWindows() + public function isWindows(): bool { return $this->getPlatform() == static::PLATFORM_WINDOWS; } @@ -277,7 +280,7 @@ class Request extends Application /** * @return bool */ - public function getIsPost() + public function getIsPost(): bool { return $this->getMethod() == 'post'; } @@ -286,7 +289,7 @@ class Request extends Application * @return bool * @throws Exception */ - public function getIsHttp() + public function getIsHttp(): bool { return true; } @@ -294,7 +297,7 @@ class Request extends Application /** * @return bool */ - public function getIsOption() + public function getIsOption(): bool { return $this->getMethod() == 'options'; } @@ -302,7 +305,7 @@ class Request extends Application /** * @return bool */ - public function getIsGet() + public function getIsGet(): bool { return $this->getMethod() == 'get'; } @@ -310,7 +313,7 @@ class Request extends Application /** * @return bool */ - public function getIsDelete() + public function getIsDelete(): bool { 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'); if (empty($method)) { @@ -332,7 +335,7 @@ class Request extends Application /** * @return bool */ - public function getIsCli() + public function getIsCli(): bool { return $this->isCli === TRUE; } @@ -357,7 +360,7 @@ class Request extends Application /** * @return mixed|null */ - public function getIp() + #[Pure] public function getIp() { $headers = $this->headers->getHeaders(); if (!empty($headers['x-forwarded-for'])) return $headers['x-forwarded-for']; @@ -369,7 +372,7 @@ class Request extends Application /** * @return string */ - public function getRuntime() + #[Pure] public function getRuntime(): string { return sprintf('%.5f', microtime(TRUE) - $this->startTime); } @@ -377,7 +380,7 @@ class Request extends Application /** * @return string */ - public function getDebug() + public function getDebug(): string { $mainstay = sprintf("%.6f", microtime(true)); // 带毫秒的时间戳 @@ -402,7 +405,7 @@ class Request extends Application * @param $router * @return bool */ - public function is($router) + public function is($router): bool { return $this->getUri() == trim($router, '/'); } @@ -410,7 +413,7 @@ class Request extends Application /** * @return bool */ - public function isNotFound() + public function isNotFound(): bool { return JSON::to(404, 'Page ' . $this->getUri() . ' not found.'); } @@ -419,10 +422,10 @@ class Request extends Application /** * @param $request * @return mixed - * @throws \ReflectionException + * @throws ReflectionException * @throws NotFindClassException */ - public static function create($request) + public static function create($request): Request { $sRequest = Context::setContext('request', Snowflake::createObject(Request::class)); $sRequest->fd = $request->fd; diff --git a/HttpServer/Route/Annotation/Http.php b/HttpServer/Route/Annotation/Http.php deleted file mode 100644 index 0ca37821..00000000 --- a/HttpServer/Route/Annotation/Http.php +++ /dev/null @@ -1,257 +0,0 @@ -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; - } - -} diff --git a/HttpServer/Route/Annotation/Tcp.php b/HttpServer/Route/Annotation/Tcp.php deleted file mode 100644 index de4a273a..00000000 --- a/HttpServer/Route/Annotation/Tcp.php +++ /dev/null @@ -1,62 +0,0 @@ -nodes as $node) { $node->{$name}(...$arguments); diff --git a/HttpServer/Route/Filter.php b/HttpServer/Route/Filter.php index 1b662b3f..b9c34a56 100644 --- a/HttpServer/Route/Filter.php +++ b/HttpServer/Route/Filter.php @@ -32,7 +32,7 @@ class Filter extends Application * @return BodyFilter|bool * @throws Exception */ - public function setBody(array $value) + public function setBody(array $value): bool|BodyFilter { if (empty($value)) { return true; @@ -52,7 +52,7 @@ class Filter extends Application * @return HeaderFilter|bool * @throws Exception */ - public function setHeader(array $value) + public function setHeader(array $value): HeaderFilter|bool { if (empty($value)) { return true; @@ -72,7 +72,7 @@ class Filter extends Application * @return QueryFilter|bool * @throws Exception */ - public function setQuery(array $value) + public function setQuery(array $value): QueryFilter|bool { if (empty($value)) { return true; @@ -90,7 +90,7 @@ class Filter extends Application /** * @throws Exception */ - public function handler() + public function handler(): bool { if (($error = $this->filters()) !== true) { throw new FilterException($error); @@ -104,7 +104,7 @@ class Filter extends Application /** * @return bool */ - private function filters() + private function filters(): bool { if (empty($this->_filters)) { 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)) { return true; diff --git a/HttpServer/Route/Filter/BodyFilter.php b/HttpServer/Route/Filter/BodyFilter.php index 32e63b9a..66b59193 100644 --- a/HttpServer/Route/Filter/BodyFilter.php +++ b/HttpServer/Route/Filter/BodyFilter.php @@ -18,7 +18,7 @@ class BodyFilter extends Filter * @return bool * @throws Exception */ - public function check() + public function check(): bool { return $this->validator(); } diff --git a/HttpServer/Route/Filter/Filter.php b/HttpServer/Route/Filter/Filter.php index 6acd37da..7eb9b4a2 100644 --- a/HttpServer/Route/Filter/Filter.php +++ b/HttpServer/Route/Filter/Filter.php @@ -27,7 +27,7 @@ abstract class Filter extends Application * @return bool * @throws Exception */ - protected function validator() + protected function validator(): bool { $validator = Validator::getInstance(); $validator->setParams($this->params); diff --git a/HttpServer/Route/Filter/FilterException.php b/HttpServer/Route/Filter/FilterException.php index e84b8b82..e3fc5c4c 100644 --- a/HttpServer/Route/Filter/FilterException.php +++ b/HttpServer/Route/Filter/FilterException.php @@ -5,12 +5,20 @@ declare(strict_types=1); namespace HttpServer\Route\Filter; +use JetBrains\PhpStorm\Pure; use Throwable; 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); } diff --git a/HttpServer/Route/Filter/HeaderFilter.php b/HttpServer/Route/Filter/HeaderFilter.php index 9ec8750b..274f01e7 100644 --- a/HttpServer/Route/Filter/HeaderFilter.php +++ b/HttpServer/Route/Filter/HeaderFilter.php @@ -18,7 +18,7 @@ class HeaderFilter extends Filter * @return bool * @throws Exception */ - public function check() + public function check(): bool { return $this->validator(); } diff --git a/HttpServer/Route/Filter/QueryFilter.php b/HttpServer/Route/Filter/QueryFilter.php index 918383cb..524a4fb7 100644 --- a/HttpServer/Route/Filter/QueryFilter.php +++ b/HttpServer/Route/Filter/QueryFilter.php @@ -18,7 +18,7 @@ class QueryFilter extends Filter * @return bool * @throws Exception */ - public function check() + public function check(): bool { return $this->validator(); } diff --git a/HttpServer/Route/Handler.php b/HttpServer/Route/Handler.php index c9cd0592..611c0c8c 100644 --- a/HttpServer/Route/Handler.php +++ b/HttpServer/Route/Handler.php @@ -7,6 +7,7 @@ namespace HttpServer\Route; use Exception; use HttpServer\Application; +use Snowflake\Exception\ConfigException; use Snowflake\Snowflake; /** @@ -43,9 +44,10 @@ class Handler extends Application /** * @param $route * @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'); } diff --git a/HttpServer/Route/Middleware.php b/HttpServer/Route/Middleware.php index 2de7e953..8cea2383 100644 --- a/HttpServer/Route/Middleware.php +++ b/HttpServer/Route/Middleware.php @@ -15,7 +15,6 @@ use Annotation\Route\Middleware as RMiddleware; use Exception; use Annotation\Route\Limits; use HttpServer\Route\Dispatch\Dispatch; -use Snowflake\Core\JSON; use Snowflake\Snowflake; /** diff --git a/HttpServer/Route/Router.php b/HttpServer/Route/Router.php index 5d2a9c4d..6daab921 100644 --- a/HttpServer/Route/Router.php +++ b/HttpServer/Route/Router.php @@ -5,18 +5,14 @@ namespace HttpServer\Route; use Closure; use Exception; -use HttpServer\Exception\ExitException; -use HttpServer\Http\Context; use HttpServer\Http\Request; use HttpServer\IInterface\RouterInterface; use HttpServer\Application; -use HttpServer\Route\Annotation\Http; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\Config; -use Snowflake\Core\JSON; use Snowflake\Exception\ComponentException; use Snowflake\Exception\ConfigException; use Snowflake\Snowflake; -use Swoole\Coroutine; defined('ROUTER_TREE') or define('ROUTER_TREE', 1); defined('ROUTER_HASH') or define('ROUTER_HASH', 2); @@ -42,8 +38,6 @@ class Router extends Application implements RouterInterface public bool $useTree = false; - private bool $reading = false; - /** * @param Closure $middleware @@ -115,7 +109,7 @@ class Router extends Application implements RouterInterface * @param $path * @return string */ - private function resolve($path) + #[Pure] private function resolve($path): string { $paths = array_column($this->groupTacks, 'prefix'); if (empty($paths)) { @@ -182,10 +176,10 @@ class Router extends Application implements RouterInterface /** * @param $route * @param $handler - * @return mixed + * @return Node|null * @throws ConfigException */ - public function socket($route, $handler): mixed + public function socket($route, $handler): ?Node { return $this->addRoute($route, $handler, 'socket'); } @@ -205,10 +199,10 @@ class Router extends Application implements RouterInterface /** * @param $route * @param $handler - * @return mixed|Node|null - * @throws + * @return Node|null + * @throws ConfigException */ - public function get($route, $handler) + public function get($route, $handler): ?Node { return $this->addRoute($route, $handler, 'get'); } @@ -219,7 +213,7 @@ class Router extends Application implements RouterInterface * @return mixed|Node|null * @throws */ - public function options($route, $handler) + public function options($route, $handler): ?Node { return $this->addRoute($route, $handler, 'options'); } @@ -240,8 +234,9 @@ class Router extends Application implements RouterInterface * @param $route * @param $handler * @return Any + * @throws ConfigException */ - public function any($route, $handler) + public function any($route, $handler): Any { $nodes = []; foreach (['get', 'post', 'options', 'put', 'delete'] as $method) { @@ -253,10 +248,10 @@ class Router extends Application implements RouterInterface /** * @param $route * @param $handler - * @return mixed|Node|null - * @throws + * @return Node|null + * @throws ConfigException */ - public function delete($route, $handler) + public function delete($route, $handler): ?Node { return $this->addRoute($route, $handler, 'delete'); } @@ -264,10 +259,10 @@ class Router extends Application implements RouterInterface /** * @param $route * @param $handler - * @return mixed|Node|null - * @throws + * @return Node|null + * @throws ConfigException */ - public function put($route, $handler) + public function put($route, $handler): ?Node { return $this->addRoute($route, $handler, 'put'); } @@ -380,7 +375,7 @@ class Router extends Application implements RouterInterface * @return array * '*' */ - public function split($path) + public function split($path): array { $prefix = $this->addPrefix(); $path = ltrim($path, '/'); @@ -403,7 +398,7 @@ class Router extends Application implements RouterInterface /** * @return array */ - public function each() + public function each(): array { $paths = []; foreach ($this->nodes as $node) { @@ -427,7 +422,7 @@ class Router extends Application implements RouterInterface * @param array $returns * @return array */ - private function readByArray($array, $returns = []) + private function readByArray($array, $returns = []): array { foreach ($array as $value) { if (empty($value)) { @@ -450,7 +445,7 @@ class Router extends Application implements RouterInterface * @param string $paths * @return array */ - private function readByChild($child, $paths = '') + private function readByChild($child, $paths = ''): array { $newPath = []; /** @var Node $item */ @@ -490,11 +485,10 @@ class Router extends Application implements RouterInterface /** * @param $exception - * @return false|int|mixed|string + * @return mixed * @throws ComponentException - * @throws Exception */ - private function exception($exception) + private function exception($exception): mixed { return Snowflake::app()->getLogger()->exception($exception); } @@ -502,10 +496,10 @@ class Router extends Application implements RouterInterface /** * @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(); if (!isset($this->nodes[$method])) { @@ -545,7 +539,7 @@ class Router extends Application implements RouterInterface * @param $request * @return Node|null */ - private function search_options($request) + private function search_options($request): ?Node { $method = $request->getMethod(); if (!isset($this->nodes[$method])) { @@ -563,7 +557,7 @@ class Router extends Application implements RouterInterface * @return Node|null * 树杈搜索 */ - private function Branch_search($request) + private function Branch_search($request): ?Node { $node = $this->tree_search($request->getExplode(), $request->getMethod()); if ($node instanceof Node) { @@ -596,7 +590,6 @@ class Router extends Application implements RouterInterface private function loadRouteDir($path) { $files = glob($path . '/*'); - $this->reading = true; for ($i = 0; $i < count($files); $i++) { if (is_dir($files[$i])) { $this->loadRouteDir($files[$i]); @@ -604,7 +597,6 @@ class Router extends Application implements RouterInterface $this->loadRouterFile($files[$i]); } } - $this->reading = false; } diff --git a/HttpServer/Server.php b/HttpServer/Server.php index c2905f0a..b9d762be 100644 --- a/HttpServer/Server.php +++ b/HttpServer/Server.php @@ -9,8 +9,6 @@ use HttpServer\Events\OnConnect; use HttpServer\Events\OnPacket; use HttpServer\Events\OnReceive; use HttpServer\Events\OnRequest; -use HttpServer\Route\Annotation\Http as AnnotationHttp; -use HttpServer\Route\Annotation\Tcp; use HttpServer\Service\Http; use HttpServer\Service\Receive; use HttpServer\Service\Packet; @@ -22,7 +20,6 @@ use Snowflake\Event; use Snowflake\Exception\ConfigException; use Snowflake\Exception\NotFindClassException; use Snowflake\Snowflake; -use HttpServer\Route\Annotation\Websocket as AWebsocket; use Swoole\Runtime; /** @@ -111,21 +108,21 @@ class Server extends Application /** - * @return void + * @return string start server * * start server * @throws ConfigException * @throws Exception */ - public function start() + public function start(): string { $configs = Config::get('servers', true); Snowflake::clearWorkerId(); $baseServer = $this->initCore($configs); if (!$baseServer) { - return; + return 'ok'; } - $baseServer->start(); + return $baseServer->start(); } diff --git a/HttpServer/Service/Abstracts/Server.php b/HttpServer/Service/Abstracts/Server.php index 4a3b76e7..915cbd93 100644 --- a/HttpServer/Service/Abstracts/Server.php +++ b/HttpServer/Service/Abstracts/Server.php @@ -43,11 +43,11 @@ trait Server /** - * @return mixed|void + * @return mixed * @throws NotFindClassException * @throws ReflectionException */ - public function onHandlerListener() + public function onHandlerListener(): mixed { $this->on('WorkerStop', $this->createHandler('workerStop')); $this->on('WorkerExit', $this->createHandler('workerExit')); @@ -83,7 +83,7 @@ trait Server * @throws ReflectionException * @throws Exception */ - protected function createHandler($eventName) + protected function createHandler($eventName): array { $classPrefix = 'HttpServer\Events\On' . ucfirst($eventName); if (!class_exists($classPrefix)) { diff --git a/Kafka/ConsumerInterface.php b/Kafka/ConsumerInterface.php index 903d74a0..6625b4ab 100644 --- a/Kafka/ConsumerInterface.php +++ b/Kafka/ConsumerInterface.php @@ -16,7 +16,7 @@ interface ConsumerInterface * @param Struct $struct * @return mixed */ - public function onHandler(Struct $struct); + public function onHandler(Struct $struct): mixed; } diff --git a/Kafka/Kafka.php b/Kafka/Kafka.php index 340bc1ba..c2394d06 100644 --- a/Kafka/Kafka.php +++ b/Kafka/Kafka.php @@ -144,7 +144,7 @@ class Kafka extends \Snowflake\Process\Process * @param $kafka * @return array */ - private function kafkaConfig($kafka) + private function kafkaConfig($kafka): array { $conf = new Conf(); $conf->setRebalanceCb([$this, 'rebalanced_cb']); diff --git a/Kafka/Logger.php b/Kafka/Logger.php index aa21cd21..5be18401 100644 --- a/Kafka/Logger.php +++ b/Kafka/Logger.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Kafka; +use Exception; use Psr\Log\LoggerInterface; use Snowflake\Exception\ComponentException; use Snowflake\Snowflake; @@ -17,10 +18,10 @@ class Logger implements LoggerInterface /** - * @param string $message + * @param mixed $message * @param array $context */ - public function emergency($message, array $context = array()) + public function emergency(mixed $message, array $context = array()) { // TODO: Implement emergency() method. var_dump(func_get_args()); @@ -30,14 +31,15 @@ class Logger implements LoggerInterface * @param string $message * @param array $context * @throws ComponentException + * @throws Exception */ - public function alert($message, array $context = array()) + public function alert(mixed $message, array $context = array()) { $logger = Snowflake::app()->getLogger(); $logger->debug($message); } - public function critical($message, array $context = array()) + public function critical(mixed $message, array $context = array()) { // TODO: Implement critical() method. var_dump(func_get_args()); @@ -47,8 +49,9 @@ class Logger implements LoggerInterface * @param string $message * @param array $context * @throws ComponentException + * @throws Exception */ - public function error($message, array $context = array()) + public function error(mixed $message, array $context = array()) { $logger = Snowflake::app()->getLogger(); $logger->error($message); @@ -59,7 +62,7 @@ class Logger implements LoggerInterface * @param array $context * @throws ComponentException */ - public function warning($message, array $context = array()) + public function warning(mixed $message, array $context = array()) { $logger = Snowflake::app()->getLogger(); $logger->warning($message); @@ -70,7 +73,7 @@ class Logger implements LoggerInterface * @param array $context * @throws ComponentException */ - public function notice($message, array $context = array()) + public function notice(mixed $message, array $context = array()) { $logger = Snowflake::app()->getLogger(); $logger->info($message); @@ -81,7 +84,7 @@ class Logger implements LoggerInterface * @param array $context * @throws ComponentException */ - public function info($message, array $context = array()) + public function info(mixed $message, array $context = array()) { $logger = Snowflake::app()->getLogger(); $logger->info($message); @@ -91,8 +94,9 @@ class Logger implements LoggerInterface * @param string $message * @param array $context * @throws ComponentException + * @throws Exception */ - public function debug($message, array $context = array()) + public function debug(mixed $message, array $context = array()) { $logger = Snowflake::app()->getLogger(); $logger->debug($message); @@ -103,8 +107,9 @@ class Logger implements LoggerInterface * @param $message * @param array $context * @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->debug($message); diff --git a/Kafka/Producer.php b/Kafka/Producer.php index 5a64a8fe..3a21cd4f 100644 --- a/Kafka/Producer.php +++ b/Kafka/Producer.php @@ -51,7 +51,7 @@ class Producer extends Component * @param $servers * @return Producer */ - public function setBrokers(string $servers) + public function setBrokers(string $servers): static { $this->conf->set('metadata.broker.list', $servers); return $this; @@ -62,7 +62,7 @@ class Producer extends Component * @param $servers * @return Producer */ - public function setTopic(string $servers) + public function setTopic(string $servers): static { $this->_topic = $servers; return $this; diff --git a/System/Abstracts/BaseAnnotation.php b/System/Abstracts/BaseAnnotation.php deleted file mode 100644 index 160d0dbd..00000000 --- a/System/Abstracts/BaseAnnotation.php +++ /dev/null @@ -1,157 +0,0 @@ -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); - -} diff --git a/System/Abstracts/BaseApplication.php b/System/Abstracts/BaseApplication.php index 08efb80f..9dd74a0f 100644 --- a/System/Abstracts/BaseApplication.php +++ b/System/Abstracts/BaseApplication.php @@ -18,9 +18,7 @@ use HttpServer\Route\Router; use HttpServer\Server; use JetBrains\PhpStorm\Pure; use Kafka\Producer; -use Snowflake\Annotation\Annotation; use Annotation\Annotation as SAnnotation; -use Snowflake\Cache\Memcached; use Snowflake\Cache\Redis; use Snowflake\Di\Service; use Snowflake\Error\ErrorHandler; @@ -38,7 +36,6 @@ use Database\DatabasesProviders; /** * Class BaseApplication * @package Snowflake\Snowflake\Base - * @property Annotation $annotation * @property Event $event * @property Router $router * @property SPool $pool @@ -46,7 +43,6 @@ use Database\DatabasesProviders; * @property Server $server * @property DatabasesProviders $db * @property Connection $connections - * @property Memcached $memcached * @property Logger $logger * @property Jwt $jwt * @property SAnnotation $attributes @@ -283,16 +279,6 @@ abstract class BaseApplication extends Service } - /** - * @return Annotation - * @throws ComponentException - */ - public function getAnnotation(): Annotation - { - return $this->get('annotation'); - } - - /** * @return Connection * @throws ComponentException @@ -389,7 +375,6 @@ abstract class BaseApplication extends Service $this->setComponents([ 'error' => ['class' => ErrorHandler::class], 'event' => ['class' => Event::class], - 'annotation' => ['class' => Annotation::class], 'connections' => ['class' => Connection::class], 'redis_connections' => ['class' => SRedis::class], 'pool' => ['class' => SPool::class], diff --git a/System/Abstracts/BaseGoto.php b/System/Abstracts/BaseGoto.php index 346ac963..979a405b 100644 --- a/System/Abstracts/BaseGoto.php +++ b/System/Abstracts/BaseGoto.php @@ -16,12 +16,12 @@ class BaseGoto extends Component { /** - * @param $message + * @param string $message * @param int $statusCode - * @return mixed|void - * @throws Exception + * @return mixed + * @throws ExitException */ - public function end(string $message, $statusCode = 200) + public function end(string $message, $statusCode = 200): mixed { throw new ExitException(JSON::to(12350, $message), $statusCode); } diff --git a/System/Abstracts/BaseObject.php b/System/Abstracts/BaseObject.php index 337e418d..9d415293 100644 --- a/System/Abstracts/BaseObject.php +++ b/System/Abstracts/BaseObject.php @@ -10,6 +10,7 @@ declare(strict_types=1); namespace Snowflake\Abstracts; use Exception; +use JetBrains\PhpStorm\Pure; use Snowflake\Error\Logger; use Snowflake\Snowflake; @@ -44,7 +45,7 @@ class BaseObject implements Configure /** * @return string */ - public static function className() + #[Pure] public static function className(): string { return get_called_class(); } @@ -72,7 +73,7 @@ class BaseObject implements Configure * @return mixed * @throws Exception */ - public function __get($name) + public function __get($name): mixed { $method = 'get' . ucfirst($name); if (method_exists($this, $method)) { @@ -89,7 +90,7 @@ class BaseObject implements Configure * @return bool * @throws Exception */ - public function addError($message, $model = 'app') + public function addError($message, $model = 'app'): bool { if ($message instanceof \Throwable) { $this->error($message->getMessage(), $message->getFile(), $message->getLine()); @@ -109,9 +110,8 @@ class BaseObject implements Configure * @param mixed $message * @param string $method * @param string $file - * @throws */ - public function debug($message, string $method = __METHOD__, string $file = __FILE__) + public function debug(mixed $message, string $method = __METHOD__, string $file = __FILE__) { if (!is_string($message)) { $message = print_r($message, true); @@ -125,9 +125,8 @@ class BaseObject implements Configure * @param mixed $message * @param string $method * @param string $file - * @throws */ - public function info($message, string $method = __METHOD__, string $file = __FILE__) + public function info(mixed $message, string $method = __METHOD__, string $file = __FILE__) { if (!is_string($message)) { $message = print_r($message, true); @@ -140,9 +139,8 @@ class BaseObject implements Configure * @param mixed $message * @param string $method * @param string $file - * @throws */ - public function success($message, string $method = __METHOD__, string $file = __FILE__) + public function success(mixed $message, string $method = __METHOD__, string $file = __FILE__) { if (!is_string($message)) { $message = print_r($message, true); @@ -157,7 +155,7 @@ class BaseObject implements Configure * @param string $method * @param string $file */ - public function warning($message, string $method = __METHOD__, string $file = __FILE__) + public function warning(mixed $message, string $method = __METHOD__, string $file = __FILE__) { if (!is_string($message)) { $message = print_r($message, true); @@ -172,7 +170,7 @@ class BaseObject implements Configure * @param null $method * @param null $file */ - public function error($message, $method = null, $file = null) + public function error(mixed $message, $method = null, $file = null) { if (!empty($file)) { echo "\033[41;37m[ERROR][" . date('Y-m-d H:i:s') . ']: ' . $file . "\033[0m"; diff --git a/System/Abstracts/Component.php b/System/Abstracts/Component.php index fdcc18c6..20f28019 100644 --- a/System/Abstracts/Component.php +++ b/System/Abstracts/Component.php @@ -6,10 +6,12 @@ * Time: 14:28 */ declare(strict_types=1); + namespace Snowflake\Abstracts; use Exception; +use JetBrains\PhpStorm\Pure; use Snowflake\Snowflake; /** @@ -48,7 +50,7 @@ class Component extends BaseObject * @param null $callback * @return bool */ - public function hasEvent($name, $callback = null) + #[Pure] public function hasEvent($name, $callback = null): bool { if (!isset($this->_events[$name])) { return false; @@ -94,19 +96,21 @@ class Component extends BaseObject /** * @param $name * @param null $handler - * @return mixed + * @return void */ - public function off($name, $handler = NULL) + public function off($name, $handler = NULL): void { $aEvents = Snowflake::app()->event; if (!isset($this->_events[$name])) { - return $aEvents->of($name, $handler); + $aEvents->of($name, $handler); + return; } if (empty($handler)) { unset($this->_events[$name]); - return $aEvents->of($name, $handler); + $aEvents->of($name, $handler); + return; } foreach ($this->_events[$name] as $key => $val) { @@ -117,7 +121,7 @@ class Component extends BaseObject break; } - return $aEvents->of($name, $handler); + $aEvents->of($name, $handler); } /** @@ -150,7 +154,7 @@ class Component extends BaseObject * @return mixed * @throws Exception */ - public function __get($name) + public function __get($name): mixed { if (property_exists($this, $name)) { return $this->$name ?? null; diff --git a/System/Abstracts/Config.php b/System/Abstracts/Config.php index fd3d0735..e8571e1c 100644 --- a/System/Abstracts/Config.php +++ b/System/Abstracts/Config.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace Snowflake\Abstracts; use Exception; +use JetBrains\PhpStorm\Pure; use Snowflake\Exception\ConfigException; use Snowflake\Abstracts\Component; use Snowflake\Snowflake; @@ -29,7 +30,7 @@ class Config extends Component /** * @return mixed */ - public function getData() + public function getData(): mixed { return $this->data; } @@ -40,7 +41,7 @@ class Config extends Component * @param $value * @return mixed */ - public function setData($key, $value) + public function setData($key, $value): mixed { return $this->data[$key] = $value; } @@ -52,10 +53,10 @@ class Config extends Component * @return mixed * @throws */ - public static function get($key, $try = FALSE, $default = null) + public static function get($key, $try = FALSE, $default = null): mixed { $instance = Snowflake::app()->config->getData(); - if (strpos($key, '.') === false) { + if (!str_contains($key, '.')) { return isset($instance[$key]) ? $instance[$key] : $default; } foreach (explode('.', $key) as $value) { @@ -82,7 +83,7 @@ class Config extends Component * @return mixed * @throws Exception */ - public static function set($key, $value) + public static function set($key, $value): mixed { $config = Snowflake::app()->config; return $config->setData($key, $value); @@ -93,7 +94,7 @@ class Config extends Component * @param bool $must_not_null * @return bool */ - public static function has($key, $must_not_null = false) + #[Pure] public static function has($key, $must_not_null = false): bool { $config = Snowflake::app()->config; if (!isset($config->data[$key])) { diff --git a/System/Abstracts/Input.php b/System/Abstracts/Input.php index ffeb3cad..4f973a11 100644 --- a/System/Abstracts/Input.php +++ b/System/Abstracts/Input.php @@ -29,7 +29,7 @@ class Input /** * @return string */ - public function getCommandName() + public function getCommandName(): string { return $this->_command; } @@ -40,7 +40,7 @@ class Input * @param null $default * @return mixed|null */ - public function get($key, $default = null) + public function get($key, $default = null): mixed { return $this->_argv[$key] ?? $default; } @@ -50,7 +50,7 @@ class Input * @param $value * @return $this */ - public function set($key, $value) + public function set($key, $value): static { $this->_argv[$key] = $value; return $this; @@ -60,7 +60,7 @@ class Input /** * @return false|string */ - public function toJson() + public function toJson(): bool|string { return json_encode($this->_argv, JSON_UNESCAPED_UNICODE); } @@ -71,7 +71,7 @@ class Input * @return array * @throws Exception */ - public function resolve($parameters) + public function resolve($parameters): array { $arrays = []; $parameters = array_slice($parameters, 1); @@ -90,7 +90,7 @@ class Input /** * @return string */ - public function getCommand() + public function getCommand(): string { return $this->_command; } diff --git a/System/Abstracts/Listener.php b/System/Abstracts/Listener.php index b2c76291..f05bdb80 100644 --- a/System/Abstracts/Listener.php +++ b/System/Abstracts/Listener.php @@ -19,7 +19,7 @@ abstract class Listener extends Component implements IListener * @return string * @throws \Exception */ - public function getName() + public function getName(): string { if (empty($this->trigger)) { throw new \Exception('Listener name con\'t empty.'); diff --git a/System/Abstracts/Pool.php b/System/Abstracts/Pool.php index dda24be4..469d94f5 100644 --- a/System/Abstracts/Pool.php +++ b/System/Abstracts/Pool.php @@ -5,6 +5,7 @@ namespace Snowflake\Abstracts; use Exception; +use JetBrains\PhpStorm\Pure; use Swoole\Coroutine; use Swoole\Coroutine\Channel; @@ -37,10 +38,10 @@ abstract class Pool extends Component /** * @param $name - * @return mixed + * @return array * @throws Exception */ - protected function get($name) + protected function get($name): array { [$timeout, $connection] = $this->_items[$name]->pop(); if (!$this->checkCanUse($name, $timeout, $connection)) { @@ -56,12 +57,12 @@ abstract class Pool extends Component * @param false $isMaster * @return string */ - public function name($cds, $isMaster = false) + #[Pure] public function name($cds, $isMaster = false): string { if ($isMaster === true) { - return hash('sha256',$cds . 'master'); + return hash('sha256', $cds . 'master'); } else { - return hash('sha256',$cds . 'slave'); + return hash('sha256', $cds . 'slave'); } } @@ -74,7 +75,7 @@ abstract class Pool extends Component * 检查连接可靠性 * @throws Exception */ - public function checkCanUse($name, $time, $client) + public function checkCanUse(string $name, int $time, mixed $client): mixed { throw new Exception('Undefined system processing function.'); } @@ -83,7 +84,7 @@ abstract class Pool extends Component * @param $name * @throws Exception */ - public function desc($name) + public function desc(string $name) { throw new Exception('Undefined system processing function.'); } @@ -93,16 +94,16 @@ abstract class Pool extends Component * @param $isMaster * @throws Exception */ - public function getConnection(array $config, $isMaster) + public function getConnection(array $config, bool $isMaster) { throw new Exception('Undefined system processing function.'); } /** * @param $name - * @return mixed + * @return bool */ - public function hasItem($name) + public function hasItem(string $name): bool { return $this->size($name) > 0; } @@ -112,7 +113,7 @@ abstract class Pool extends Component * @param $name * @return mixed */ - public function size($name) + public function size(string $name): mixed { if (!isset($this->_items[$name])) { return 0; @@ -125,7 +126,7 @@ abstract class Pool extends Component * @param $name * @param $client */ - public function push($name, $client) + public function push(string $name, mixed $client) { $this->_items[$name]->push([time(), $client]); unset($client); @@ -133,9 +134,9 @@ abstract class Pool extends Component /** - * @param $name + * @param string $name */ - public function clean($name) + public function clean(string $name) { if (!isset($this->_items[$name])) { return; @@ -150,7 +151,7 @@ abstract class Pool extends Component /** * @return Channel[] */ - protected function getChannels() + protected function getChannels(): array { return $this->_items; } diff --git a/System/Annotation/Annotation.php b/System/Annotation/Annotation.php deleted file mode 100644 index bce54f41..00000000 --- a/System/Annotation/Annotation.php +++ /dev/null @@ -1,282 +0,0 @@ - Http::class, - 'tcp' => Tcp::class, - 'websocket' => Websocket::class - ]; - - /** - * @param $name - * @param $class - * @return mixed - * @throws - */ - public function register($name, $class) - { - if (!isset($this->_classMap[$name]) || is_string($this->_classMap[$name])) { - $this->_classMap[$name] = Snowflake::createObject($class); - } - return $this->_classMap[$name]; - } - - - /** - * @param $path - * @param $namespace - * @throws ReflectionException - */ - public function registration_notes($path = '', $namespace = '') - { - if (empty($path)) { - $path = $this->path; - } - if (empty($namespace)) { - $namespace = $this->namespace; - } - $this->scanning(rtrim($path, '/'), $namespace, get_called_class()); - } - - /** - * @param ReflectionClass $reflect - * @param string $className - * @throws ReflectionException - * @throws Exception - * @Message(updatePosition) - * 注入注解 - */ - private function resolve(ReflectionClass $reflect, string $className) - { - $controller = $reflect->newInstance(); - - $annotations = $this->getAnnotation($className); - $methods = $reflect->getMethods(\ReflectionMethod::IS_PUBLIC); - foreach ($methods as $function) { - foreach ($annotations as $annotation) { - $comment = $function->getDocComment(); - $methodName = $function->getName(); - if (!$comment) { - continue; - } - - preg_match('/@(' . $annotation . ')\((.*?)\)/', $comment, $events); - if (!isset($events[1])) { - continue; - } - if (!$this->isLegitimate($events)) { - continue; - } - $this->push($this->getName($annotation, $events), [$controller, $methodName]); - } - } - } - - - /** - * @param $name - * @return mixed - * @throws Exception - */ - public function get($name) - { - if (!isset($this->_classMap[$name])) { - throw new Exception('Undefined analytic class ' . $name . '.'); - } - return $this->_classMap[$name]; - } - - - /** - * @param $events - * @throws Exception - */ - public function isLegitimate($events) - { - throw new Exception('Undefined analytic function isLegitimate.'); - } - - - /** - * @param $function - * @param $events - * @throws Exception - */ - public function getName($function, $events) - { - throw new Exception('Undefined analytic function getName.'); - } - - - /** - * @param $controller - * @param $methodName - * @param $events - * @throws Exception - */ - public function createHandler($controller, $methodName, $events) - { - throw new Exception('Undefined analytic function.'); - } - - - /** - * @param string $path - * @param $namespace - * @param $className - * @throws ReflectionException - */ - protected function scanning(string $path, $namespace, $className) - { - $di = Snowflake::getDi(); - foreach (glob($path . '/*') as $file) { - if (is_dir($file)) { - $this->scanning($path, $namespace, $className); - } - - $explode = explode('/', $file); - - $class = str_replace('.php', '', end($explode)); - - $this->resolve($di->getReflect($namespace . '\\' . $class), $className); - } - } - - /** - * @param $path - * @param array $params - * @return bool|mixed - */ - public function runWith($path, $params = []) - { - if (!$this->has($path)) { - return null; - } - $callback = $this->_Scan_directory[$path]; - if (!isset($this->params[$path])) { - return $callback(...$params); - } - return $callback(...$this->params[$path]); - } - - - /** - * @param $name - * @param $callback - * @param array $params - */ - public function push($name, $callback, $params = []) - { - $this->_Scan_directory[$name] = $callback; - if (!empty($params)) { - $this->params[$name] = $params; - } - } - - - /** - * @param $name - * @return array|null[] - */ - public function pop($name) - { - if (isset($this->_Scan_directory[$name])) { - return [$this->_Scan_directory[$name], $this->params[$name] ?? []]; - } - return [null, null]; - } - - - /** - * @param $path - * @return bool|mixed - */ - public function has($path) - { - return isset($this->_Scan_directory[$path]); - } - - - /** - * @param $name - * @return mixed|null - * @throws ReflectionException - * @throws NotFindClassException - * @throws Exception - */ - public function __get($name) - { - if (!isset($this->_classMap[$name])) { - return parent::__get($name); // TODO: Change the autogenerated stub - } - if (!is_object($this->_classMap[$name])) { - $this->_classMap[$name] = Snowflake::createObject($this->_classMap[$name]); - } - return $this->_classMap[$name]; - } - - /** - * @param ReflectionClass $reflect - * @return array - */ - protected function getPrivates(ReflectionClass $reflect) - { - $arrays = []; - $properties = $reflect->getProperties(ReflectionMethod::IS_PRIVATE); - foreach ($properties as $property) { - $arrays[] = $property->getName(); - } - return $arrays; - } - - - /** - * @param string $class - * @return string[] - * @throws ReflectionException - */ - public function getAnnotation(string $class) - { - $reflect = Snowflake::getDi()->getReflect($class); - - return $this->getPrivates($reflect); - } - - -} diff --git a/System/Application.php b/System/Application.php index 72f4eb68..9409a747 100644 --- a/System/Application.php +++ b/System/Application.php @@ -20,6 +20,7 @@ use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Input; use Snowflake\Abstracts\Kernel; use Snowflake\Exception\NotFindClassException; +use stdClass; use Swoole\Timer; /** @@ -54,7 +55,7 @@ class Application extends BaseApplication * @return $this * @throws */ - public function import(string $service) + public function import(string $service): static { if (!class_exists($service)) { throw new NotFindClassException($service); @@ -71,7 +72,7 @@ class Application extends BaseApplication * @param $kernel * @return $this */ - public function commands(Kernel $kernel) + public function commands(Kernel $kernel): static { foreach ($kernel->getCommands() as $command) { $this->register($command); @@ -93,20 +94,22 @@ class Application extends BaseApplication /** - * @param $argv - * @return bool|string|void - * @throws + * @param Input $argv + * @return bool|string + * @throws Exception + * @throws NotFindClassException + * @throws \ReflectionException */ - public function start(Input $argv) + public function start(Input $argv): bool|string { $this->set('input', $argv); try { $manager = Snowflake::app()->get('console'); $manager->setParameters($argv); $class = $manager->search(); - response()->send($manager->execCommand($class)); + return response()->send($manager->execCommand($class)); } catch (\Throwable $exception) { - response()->send(implode("\n", [ + return response()->send(implode("\n", [ 'Msg: ' . $exception->getMessage(), 'Line: ' . $exception->getLine(), 'File: ' . $exception->getFile() @@ -119,10 +122,10 @@ class Application extends BaseApplication /** * @param $className * @param null $abstracts - * @return mixed + * @return stdClass * @throws Exception */ - public function make($className, $abstracts = null) + public function make($className, $abstracts = null): stdClass { return make($className, $abstracts); } diff --git a/System/Cache/File.php b/System/Cache/File.php index ff829ccb..ae6b7a46 100644 --- a/System/Cache/File.php +++ b/System/Cache/File.php @@ -6,10 +6,12 @@ * Time: 14:51 */ declare(strict_types=1); + namespace Snowflake\Cache; use Exception; +use JetBrains\PhpStorm\Pure; use Snowflake\Abstracts\Component; use Swoole\Coroutine\System; @@ -32,8 +34,9 @@ class File extends Component implements ICache /** * @param $key * @param $val + * @return string|int */ - public function set($key, $val) + public function set($key, $val): string|int { if (is_array($val) || is_object($val)) { $val = serialize($val); @@ -42,15 +45,15 @@ class File extends Component implements ICache if (!$this->exists($tmpFile)) { touch($tmpFile); } - System::writeFile($tmpFile, $val, LOCK_EX); + return System::writeFile($tmpFile, $val, LOCK_EX); } /** * @param $key * @param array $hashKeys - * @return mixed|void + * @return array|bool */ - public function hMget($key, array $hashKeys) + public function hMGet($key, array $hashKeys): array|bool { $hash = $this->get($key); if (!is_array($hash)) { @@ -67,9 +70,9 @@ class File extends Component implements ICache /** * @param $key * @param array $val - * @return mixed|void + * @return mixed */ - public function hMset($key, array $val) + public function hMSet($key, array $val): mixed { $hash = $this->get($key); if (!is_array($hash)) { @@ -81,11 +84,11 @@ class File extends Component implements ICache } /** - * @param $key - * @param $hashKey - * @return mixed|void + * @param string $key + * @param string $hashKey + * @return string|int|bool */ - public function hget($key, $hashKey) + public function hGet(string $key, string $hashKey): string|int|bool|null { $hash = $this->get($key); if (!is_array($hash)) { @@ -98,9 +101,9 @@ class File extends Component implements ICache * @param $key * @param $hashKey * @param $hashValue - * @return mixed|void + * @return mixed */ - public function hset($key, $hashKey, $hashValue) + public function hSet($key, $hashKey, $hashValue): mixed { $hash = $this->get($key); if (!is_array($hash)) { @@ -116,20 +119,20 @@ class File extends Component implements ICache * @param $key * @return bool */ - public function exists($key) + #[Pure] public function exists($key): bool { return file_exists($key); } /** * @param $key - * @return mixed|null + * @return mixed|bool */ - public function get($key) + public function get($key): string|bool { $tmpFile = $this->getCacheKey($key); if (!$this->exists($tmpFile)) { - return NULL; + return false; } $content = file_get_contents($tmpFile); return unserialize($content); @@ -140,8 +143,8 @@ class File extends Component implements ICache * @return string * @throws */ - private function getCacheKey($key) + private function getCacheKey($key): string { - return storage($key,'cache'); + return storage($key, 'cache'); } } diff --git a/System/Cache/ICache.php b/System/Cache/ICache.php index 6cb31006..8280ef65 100644 --- a/System/Cache/ICache.php +++ b/System/Cache/ICache.php @@ -6,6 +6,7 @@ * Time: 16:35 */ declare(strict_types=1); + namespace Snowflake\Cache; /** @@ -17,36 +18,36 @@ interface ICache /** * @param $key * @param $val - * @return mixed + * @return string|int */ - public function set($key, $val); + public function set($key, $val): string|int; /** * @param $key - * @return mixed + * @return string|int|bool */ - public function get($key); + public function get($key): string|int|bool; /** * @param $key - * @param $hashKeys - * @return mixed + * @param array $hashKeys + * @return array|bool|null */ - public function hMget($key, array $hashKeys); + public function hMGet($key, array $hashKeys): array|bool|null; /** * @param $key * @param array $val * @return mixed */ - public function hMset($key, array $val); + public function hMSet($key, array $val): mixed; /** - * @param $key - * @param $hashKey - * @return mixed + * @param string $key + * @param string $hashKey + * @return string|int|bool */ - public function hget($key, $hashKey); + public function hGet(string $key, string $hashKey): string|int|bool; /** * @param $key @@ -54,11 +55,11 @@ interface ICache * @param $hashValue * @return mixed */ - public function hset($key, $hashKey, $hashValue); + public function hSet($key, $hashKey, $hashValue): mixed; /** * @param $key * @return bool */ - public function exists($key); + public function exists($key): bool; } diff --git a/System/Cache/Memcached.php b/System/Cache/Memcached.php deleted file mode 100644 index f4fc10b7..00000000 --- a/System/Cache/Memcached.php +++ /dev/null @@ -1,154 +0,0 @@ -event; - $event->on(Event::RELEASE_ALL, [$this, 'destroy']); - $event->on(Event::EVENT_AFTER_REQUEST, [$this, 'release']); - - $id = Config::get('id', false, 'system'); - $this->_memcached = new \Memcached($id); - $this->addServer(); - } - - /** - * @return \Memcached - * @throws Exception - */ - public function getConnect() - { - return $this->_memcached; - } - - - /** - * @throws ConfigException - * @throws Exception - */ - private function addServer() - { - $array = []; - $memcached = Config::get('cache.memcached'); - if (isset($memcached[0])) { - foreach ($memcached as $value) { - $array[] = [$value['host'], $value['port'], $value['weight']]; - } - $isConnected = $this->_memcached->addServers($array); - } else { - $array[] = Config::get('cache.memcached.host', true); - $array[] = Config::get('cache.memcached.port', true); - $array[] = Config::get('cache.memcached.weight', true); - $isConnected = $this->_memcached->addServer(...$array); - } - if (!$isConnected) { - throw new Exception('Cache Memcache Host 127.0.0.1 Connect Fail.'); - } - } - - - /** - * @param $key - * @param $val - * @return mixed|void - */ - public function set($key, $val) - { - // TODO: Implement set() method. - if (is_array($val) || is_object($val)) { - $val = serialize($val); - } - - $this->_memcached->set($key, $val); - } - - /** - * @param $key - * @return mixed|void - */ - public function get($key) - { - // TODO: Implement get() method. - } - - /** - * @param $key - * @param array $hashKeys - * @return mixed|void - */ - public function hMget($key, array $hashKeys) - { - // TODO: Implement hMget() method. - } - - /** - * @param $key - * @param array $val - * @return mixed|void - */ - public function hMset($key, array $val) - { - // TODO: Implement hMset() method. - } - - /** - * @param $key - * @param $hashKey - * @return mixed|void - */ - public function hget($key, $hashKey) - { - // TODO: Implement hget() method. - } - - /** - * @param $key - * @param $hashKey - * @param $hashValue - * @return mixed|void - */ - public function hset($key, $hashKey, $hashValue) - { - // TODO: Implement hset() method. - } - - /** - * @param $key - * @return bool|void - */ - public function exists($key) - { - // TODO: Implement exists() method. - } - - -} diff --git a/System/Cache/Redis.php b/System/Cache/Redis.php index 9bf81f60..ec361a64 100644 --- a/System/Cache/Redis.php +++ b/System/Cache/Redis.php @@ -46,7 +46,7 @@ class Redis extends Component * @return mixed * @throws */ - public function __call($name, $arguments) + public function __call($name, $arguments): mixed { if (method_exists($this, $name)) { $data = $this->{$name}(...$arguments); @@ -82,7 +82,7 @@ SCRIPT; * @return int * @throws Exception */ - public function unlock($key) + public function unlock($key): int { $redis = $this->proxy(); return $redis->del($key); @@ -113,7 +113,7 @@ SCRIPT; * @return \Redis * @throws Exception */ - public function proxy() + public function proxy(): \Redis { $connections = Snowflake::app()->pool->redis; diff --git a/System/Core/ArrayAccess.php b/System/Core/ArrayAccess.php index d631a298..8420679b 100644 --- a/System/Core/ArrayAccess.php +++ b/System/Core/ArrayAccess.php @@ -24,7 +24,7 @@ class ArrayAccess * @return array * @throws Exception */ - public static function toArray($data) + public static function toArray($data): array { if (!is_object($data) && !is_array($data)) { return $data; @@ -49,10 +49,10 @@ class ArrayAccess /** * @param $data - * @return array|mixed + * @return array * @throws Exception */ - public static function objToArray($data) + public static function objToArray($data): array { if (!is_object($data)) { return $data; @@ -77,7 +77,7 @@ class ArrayAccess * @param array $newArray * @return array */ - public static function merge(array $oldArray, array $newArray) + public static function merge(array $oldArray, array $newArray): array { if (empty($oldArray)) { return $newArray; diff --git a/System/Core/DateFormat.php b/System/Core/DateFormat.php index b6c72f58..fced4fca 100644 --- a/System/Core/DateFormat.php +++ b/System/Core/DateFormat.php @@ -9,6 +9,8 @@ declare(strict_types=1); namespace Snowflake\Core; +use JetBrains\PhpStorm\Pure; + /** * Class DateFormat * @package Snowflake\Snowflake\Core @@ -20,7 +22,7 @@ class DateFormat * @param $time * @return bool|false|int|string */ - private static function check($time) + private static function check($time): bool|int|string { if ($time === null) { $time = time(); @@ -46,7 +48,7 @@ class DateFormat * * 获取指定日期当周第一天的时间 */ - public static function getWeekCurrentDay($time = null) + public static function getWeekCurrentDay($time = null): bool|int { if (!($time = static::check($time))) { return false; @@ -64,7 +66,7 @@ class DateFormat * * 获取指定日期当月第一天的时间 */ - public static function getMonthCurrentDay($time = null) + public static function getMonthCurrentDay($time = null): bool|int { if (!($time = static::check($time))) { return false; @@ -75,10 +77,10 @@ class DateFormat /** * @param $time - * @return bool|false|int|string + * @return bool|int|string 指定的月份有几天 * 指定的月份有几天 */ - public static function getMonthTotalDay($time) + public static function getMonthTotalDay($time): bool|int|string { if (!($time = static::check($time))) { return false; @@ -94,7 +96,7 @@ class DateFormat * @param null $endTime * @return string */ - public static function mtime($startTime, $endTime = null) + #[Pure] public static function mtime($startTime, $endTime = null) { if ($endTime === null) { $endTime = microtime(true); diff --git a/System/Core/Dtl.php b/System/Core/Dtl.php index d58a725a..decdfb92 100644 --- a/System/Core/Dtl.php +++ b/System/Core/Dtl.php @@ -30,10 +30,10 @@ class Dtl extends Component /** - * @return mixed + * @return array * @throws Exception */ - public function toArray() + public function toArray(): array { if (!is_array($this->params)) { return ArrayAccess::toArray($this->params); @@ -44,10 +44,10 @@ class Dtl extends Component /** * @param $name - * @return mixed|null + * @return mixed * @throws Exception */ - public function get($name) + public function get($name): mixed { $array = $this->toArray(); if (!isset($array[$name])) { diff --git a/System/Core/Help.php b/System/Core/Help.php index 30290045..40ffde3e 100644 --- a/System/Core/Help.php +++ b/System/Core/Help.php @@ -5,6 +5,9 @@ declare(strict_types=1); namespace Snowflake\Core; +use Exception; +use JetBrains\PhpStorm\Pure; + /** * Class Help * @package Snowflake\Snowflake\Core @@ -16,7 +19,7 @@ class Help * @param array $data * @return string */ - public static function toXml(array $data) + #[Pure] public static function toXml(array $data) { $xml = ""; foreach ($data as $key => $val) { @@ -33,9 +36,9 @@ class Help /** * @param $xml - * @return array|mixed + * @return mixed */ - public static function toArray($xml) + public static function toArray($xml): mixed { if (empty($xml)) { return null; @@ -49,7 +52,11 @@ class Help } - public static function jsonToArray($xml) + /** + * @param $xml + * @return mixed + */ + public static function jsonToArray($xml): mixed { $_xml = json_decode($xml, true); if (is_null($_xml)) { @@ -62,7 +69,7 @@ class Help * @param $xml * @return mixed */ - public static function xmlToArray($xml) + public static function xmlToArray($xml): mixed { if (is_array($xml)) { return $xml; @@ -79,9 +86,9 @@ class Help /** * @param $parameter * @return array|false|string - * @throws \Exception + * @throws Exception */ - public static function toString($parameter) + public static function toString($parameter): bool|array|string { if (!is_string($parameter)) { $parameter = ArrayAccess::toArray($parameter); @@ -94,9 +101,9 @@ class Help /** * @param mixed $json - * @return false|mixed|string + * @return bool|string */ - public static function toJson($json) + public static function toJson(mixed $json): bool|string { if (is_object($json)) { $json = get_object_vars($json); @@ -122,7 +129,7 @@ class Help * * 随机字符串 */ - public static function random($length = 20) + public static function random($length = 20): string { $res = []; $str = 'abcdefghijklmnopqrstuvwxyz'; @@ -144,7 +151,7 @@ class Help * @param $type * @return string */ - public static function sign(array $array, $key, $type) + public static function sign(array $array, $key, $type): string { ksort($array, SORT_ASC); $string = []; diff --git a/System/Core/JSON.php b/System/Core/JSON.php index 5a62c45a..987144d9 100644 --- a/System/Core/JSON.php +++ b/System/Core/JSON.php @@ -24,7 +24,7 @@ class JSON * @return false|string * @throws Exception */ - public static function encode($data) + public static function encode($data): bool|string { if (empty($data)) { return $data; @@ -41,7 +41,7 @@ class JSON * @param bool $asArray * @return mixed */ - public static function decode($data, $asArray = true) + public static function decode($data, $asArray = true): mixed { if (is_array($data)) { return $data; @@ -58,7 +58,7 @@ class JSON * @return mixed * @throws */ - public static function to($code, $message = '', $data = [], $count = 0, $exPageInfo = []) + public static function to($code, $message = '', $data = [], $count = 0, $exPageInfo = []): mixed { $params['code'] = $code; if (!is_string($message)) { @@ -91,7 +91,7 @@ class JSON * @return false|int|string * @throws Exception */ - public static function output($state, $body) + public static function output($state, $body): bool|int|string { $params['state'] = $state; $params['body'] = ArrayAccess::toArray($body); diff --git a/System/Core/Reader.php b/System/Core/Reader.php index dd78f075..0210f4e0 100644 --- a/System/Core/Reader.php +++ b/System/Core/Reader.php @@ -18,7 +18,7 @@ class Reader * @param int $size * @return array and int */ - public static function readerServerLogPagination($filepath, $page = 1, $size = 20) + public static function readerServerLogPagination($filepath, $page = 1, $size = 20): array { $count = 0; $strings = []; @@ -56,7 +56,7 @@ class Reader * @param $lines * @return mixed */ - public static function read_backward_line($filename, $start, $lines) + public static function read_backward_line($filename, $start, $lines): mixed { $lines++; $offset = -1; @@ -100,7 +100,7 @@ class Reader * @param $filepath * @return int */ - private static function read_count_by_file($filepath) + private static function read_count_by_file($filepath): int { $count = 0; //只读方式打开文件 @@ -123,7 +123,7 @@ class Reader * @param int $size * @return array */ - public static function folderPagination($filepath, $page = 1, $size = 20) + public static function folderPagination($filepath, $page = 1, $size = 20): array { $count = 0; $strings = []; diff --git a/System/Core/Str.php b/System/Core/Str.php index a6da85c6..86a3df72 100644 --- a/System/Core/Str.php +++ b/System/Core/Str.php @@ -5,6 +5,7 @@ namespace Snowflake\Core; use Exception; +use JetBrains\PhpStorm\Pure; /** * Class Str @@ -23,7 +24,7 @@ class Str * @return string * 获取随机字符串 */ - public static function rand(int $length = 20) + #[Pure] public static function rand(int $length = 20): string { $string = ''; if ($length < 1) $length = 20; @@ -38,10 +39,10 @@ class Str /** * @param int $length * - * @return int + * @return int|string 获取随机数字 * 获取随机数字 */ - public static function random(int $length = 20) + #[Pure] public static function random(int $length = 20): int|string { $number = ''; $default = str_split(self::NUMBER); @@ -54,13 +55,13 @@ class Str /** * @param $string - * @param $sublen + * @param $sullen * @param bool $strip_tags * @param string $append * * @return string */ - public static function cut_str_utf8($string, $sublen, $strip_tags = true, $append = '...') + public static function cut_str_utf8($string, $sullen, $strip_tags = true, $append = '...'): string { if ($strip_tags) { $string = strip_tags($string); @@ -71,7 +72,7 @@ class Str for ($i = 0; $i < count($t_string[0]); $i++) { $str .= $t_string[0][$i]; //转为gbk,一个汉字长度为2 - if (strlen(@iconv('utf-8', 'gbk', $str)) >= $sublen) { + if (strlen(@iconv('utf-8', 'gbk', $str)) >= $sullen) { if ($i != count($t_string[0]) - 1) $str .= $append; break; } @@ -86,7 +87,7 @@ class Str * @return bool * 判断是否为json字符串 */ - public static function isJson($data, $callback = null) + public static function isJson($data, $callback = null): bool { $json = !is_null(json_decode($data)) && !is_numeric($data); if ($json && is_callable($callback, true)) { @@ -102,7 +103,7 @@ class Str * @return bool * 判断是否序列化字符串 */ - public static function isSerialize($data, $callBack = null) + public static function isSerialize($data, $callBack = null): bool { $false = !empty($data) && unserialize($data) !== false; if ($false && is_callable($callBack, true)) { @@ -118,7 +119,7 @@ class Str * @param string $append * @return string */ - public static function cut($string, int $length = 20, $append = '...') + #[Pure] public static function cut($string, int $length = 20, $append = '...'): string { if (empty($string)) { return ''; @@ -144,7 +145,7 @@ class Str * * @return string */ - public static function encrypt($str, $number = 10, $key = 'xshucai.com') + public static function encrypt($str, $number = 10, $key = 'xshucai.com'): string { $res = []; $add = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; @@ -166,7 +167,7 @@ class Str * @param $type * @return string */ - public static function filename($file, $type) + #[Pure] public static function filename($file, $type): string { switch ($type) { case 'image/png': @@ -187,7 +188,7 @@ class Str * @return array * 剩余天,带分秒 */ - public static function timeout($endTime, int $startTime = null) + public static function timeout($endTime, int $startTime = null): array { $endTime = $endTime - (!empty($startTime) ? $startTime : time()); @@ -206,7 +207,7 @@ class Str /** * @return false|int */ - public static function get_sy_time() + public static function get_sy_time(): bool|int { $time = strtotime('+1days', strtotime(date('Y-m-d'))); @@ -217,7 +218,7 @@ class Str * @param string $string * @return string */ - public static function encode(string $string) + #[Pure] public static function encode(string $string): string { return addslashes($string); } @@ -227,7 +228,7 @@ class Str * @return string|string[]|null * 清除标点符号 */ - public static function clear(string $string) + public static function clear(string $string): array|string|null { $char = '。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()'; return preg_replace(array("/[[:punct:]]/i", '/[' . $char . ']/u', '/[ ]{2,}/'), '', $string); @@ -237,12 +238,12 @@ class Str /** * @param int $user * @param array $param - * @param int $requestTime + * @param null $requestTime * * @return string * @throws Exception */ - public static function token($user, $param = [], $requestTime = NULL) + public static function token(int $user, $param = [], $requestTime = NULL): string { $str = ''; if (!$requestTime) { diff --git a/System/Core/Xml.php b/System/Core/Xml.php index 2cb5a420..a40beeb7 100644 --- a/System/Core/Xml.php +++ b/System/Core/Xml.php @@ -21,7 +21,7 @@ class Xml * @param bool $asArray * @return array|object */ - public static function toArray($data, $asArray = true) + public static function toArray($data, $asArray = true): object|array { $data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA); if ($asArray) { @@ -35,7 +35,7 @@ class Xml * @param $str * @return array|bool|object */ - public static function isXml($str) + public static function isXml($str): object|bool|array { $xml_parser = xml_parser_create(); if (!xml_parse($xml_parser, $str, true)) { diff --git a/System/Error/ErrorHandler.php b/System/Error/ErrorHandler.php index 96138a45..e2fd3eb6 100644 --- a/System/Error/ErrorHandler.php +++ b/System/Error/ErrorHandler.php @@ -88,7 +88,7 @@ class ErrorHandler extends Component implements ErrorInterface public function errorHandler() { $error = func_get_args(); - if (strpos($error[2], 'vendor/Reboot.php') !== FALSE) { + if (str_contains($error[2], 'vendor/Reboot.php')) { return; } @@ -116,7 +116,7 @@ class ErrorHandler extends Component implements ErrorInterface * @return false|string * @throws Exception */ - public function sendError($message, $file, $line, $code = 500) + public function sendError($message, $file, $line, $code = 500): bool|string { $path = ['file' => $file, 'line' => $line]; @@ -130,7 +130,7 @@ class ErrorHandler extends Component implements ErrorInterface /** * @return mixed */ - public function getErrorMessage() + public function getErrorMessage(): mixed { $message = $this->message; $this->message = NULL; @@ -140,7 +140,7 @@ class ErrorHandler extends Component implements ErrorInterface /** * @return bool */ - public function getAsError() + public function getAsError(): bool { return $this->message !== NULL; } diff --git a/System/Error/ErrorInterface.php b/System/Error/ErrorInterface.php index e1231f19..f596bdcb 100644 --- a/System/Error/ErrorInterface.php +++ b/System/Error/ErrorInterface.php @@ -23,6 +23,6 @@ interface ErrorInterface * @param int $code * @return mixed */ - public function sendError($message, $file, $line, $code = 500); + public function sendError($message, $file, $line, $code = 500): mixed; } diff --git a/System/Error/Logger.php b/System/Error/Logger.php index 83bbbd2e..335b0069 100644 --- a/System/Error/Logger.php +++ b/System/Error/Logger.php @@ -30,58 +30,58 @@ class Logger extends Component /** * @param $message - * @param string $category - * @param null $_ + * @param string $method + * @param null $file * @throws Exception */ - public function debug($message, $category = 'app', $_ = null) + public function debug(mixed $message, string $method = 'app', $file = null) { - $this->writer($message, $category); + $this->writer($message, $method); } /** * @param $message - * @param string $category + * @param string $method * @throws Exception */ - public function trance($message, $category = 'app') + public function trance($message, $method = 'app') { - $this->writer($message, $category); + $this->writer($message, $method); } /** * @param $message - * @param string $category - * @param null $_ + * @param string $method + * @param null $file * @throws Exception */ - public function error($message, $category = 'error', $_ = null) + public function error(mixed $message, $method = 'error', $file = null) { - $this->writer($message, $category); + $this->writer($message, $method); } /** * @param $message - * @param string $category - * @param null $_ + * @param string $method + * @param null $file * @throws Exception */ - public function success($message, $category = 'app', $_ = null) + public function success(mixed $message, $method = 'app', $file = null) { - $this->writer($message, $category); + $this->writer($message, $method); } /** * @param $message - * @param string $category + * @param string $method * @return string * @throws Exception */ - private function writer($message, $category = 'app') + private function writer($message, $method = 'app'): string { - $this->print_r($message, $category); + $this->print_r($message, $method); if ($message instanceof Throwable) { $message = $message->getMessage(); } else { @@ -96,7 +96,7 @@ class Logger extends Component if (!is_array($this->logs)) { $this->logs = []; } - $this->logs[] = [$category, $message]; + $this->logs[] = [$method, $message]; } return $message; } @@ -104,17 +104,17 @@ class Logger extends Component /** * @param $message - * @param $category + * @param $method * @throws Exception */ - public function print_r($message, $category = '') + public function print_r($message, $method = '') { $debug = Config::get('debug', false, ['enable' => false]); if ((bool)$debug['enable'] === true) { if (!is_callable($debug['callback'] ?? null, true)) { return; } - call_user_func($debug['callback'], $message, $category); + call_user_func($debug['callback'], $message, $method); } } @@ -123,33 +123,33 @@ class Logger extends Component * @param string $application * @return mixed */ - public function getLastError($application = 'app') + public function getLastError($application = 'app'): mixed { - $_tmp = []; + $filetype = []; foreach ($this->logs as $key => $val) { if ($val[0] != $application) { continue; } - $_tmp[] = $val[1]; + $filetype[] = $val[1]; } - if (empty($_tmp)) { + if (empty($filetype)) { return 'Unknown error.'; } - return end($_tmp); + return end($filetype); } /** * @param $messages - * @param string $category + * @param string $method * @throws */ - public function write(string $messages, $category = 'app') + public function write(string $messages, $method = 'app') { if (empty($messages)) { return; } $fileName = 'server-' . date('Y-m-d') . '.log'; - $dirName = 'log/' . (empty($category) ? 'app' : $category); + $dirName = 'log/' . (empty($method) ? 'app' : $method); $logFile = '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL; Snowflake::writeFile(storage($fileName, $dirName), $logFile, FILE_APPEND); @@ -167,9 +167,9 @@ class Logger extends Component /** * @param $logFile - * @return false|string + * @return string */ - private function getSource($logFile) + private function getSource($logFile): string { if (!file_exists($logFile)) { shell_exec('echo 3 > /proc/sys/vm/drop_caches'); @@ -191,8 +191,8 @@ class Logger extends Component return; } foreach ($this->logs as $log) { - [$category, $message] = $log; - $this->write($message, $category); + [$method, $message] = $log; + $this->write($message, $method); } $this->logs = []; } @@ -200,7 +200,7 @@ class Logger extends Component /** * @return array */ - public function clear() + public function clear(): array { return $this->logs = []; } @@ -209,7 +209,7 @@ class Logger extends Component * @param $data * @return string */ - private function arrayFormat($data) + private function arrayFormat($data): string { if (is_string($data)) { return $data; @@ -220,15 +220,15 @@ class Logger extends Component $data = get_object_vars($data); } - $_tmp = []; + $filetype = []; foreach ($data as $key => $val) { if (is_array($val)) { - $_tmp[] = $this->arrayFormat($val); + $filetype[] = $this->arrayFormat($val); } else { - $_tmp[] = (is_string($key) ? $key . ' : ' : '') . $val; + $filetype[] = (is_string($key) ? $key . ' : ' : '') . $val; } } - return implode(PHP_EOL, $_tmp); + return implode(PHP_EOL, $filetype); } @@ -269,12 +269,12 @@ class Logger extends Component * @param Throwable $exception * @return array */ - private function getException(Throwable $exception) + private function getException(Throwable $exception): array { - $_tmp = [$exception->getMessage()]; - $_tmp[] = $exception->getFile() . ' on line ' . $exception->getLine(); - $_tmp[] = $exception->getTrace(); - return $_tmp; + $filetype = [$exception->getMessage()]; + $filetype[] = $exception->getFile() . ' on line ' . $exception->getLine(); + $filetype[] = $exception->getTrace(); + return $filetype; } } diff --git a/System/Event.php b/System/Event.php index 81787b25..2992f503 100644 --- a/System/Event.php +++ b/System/Event.php @@ -87,7 +87,7 @@ class Event extends BaseObject * @param $name * @param $callback */ - public function of($name, $callback) + public function of($name, $callback): void { if (!isset($this->_events[$name])) { return; @@ -106,7 +106,7 @@ class Event extends BaseObject * @param $name * @return bool */ - public function offName($name) + public function offName($name): bool { if (!$this->exists($name)) { return true; @@ -121,7 +121,7 @@ class Event extends BaseObject * @param null $callback * @return bool */ - public function exists($name, $callback = null) + public function exists($name, $callback = null): bool { if (!isset($this->_events[$name])) { return false; @@ -142,9 +142,9 @@ class Event extends BaseObject /** * @param $name * @param $handler - * @return mixed|null + * @return mixed */ - public function get($name, $handler) + public function get($name, $handler): mixed { if (!$this->exists($name)) { return null; @@ -173,7 +173,7 @@ class Event extends BaseObject * @return bool|mixed * @throws Exception */ - public function trigger($name, $parameter = null, $handler = null, $is_remove = false) + public function trigger($name, $parameter = null, $handler = null, $is_remove = false): mixed { if (!$this->exists($name)) { return false; diff --git a/System/Exception/AuthException.php b/System/Exception/AuthException.php index 2d4c6c55..9302d9ee 100644 --- a/System/Exception/AuthException.php +++ b/System/Exception/AuthException.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Snowflake\Exception; +use JetBrains\PhpStorm\Pure; use Throwable; /** @@ -14,7 +15,13 @@ use Throwable; 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, 401, $previous); } diff --git a/System/Exception/ComponentException.php b/System/Exception/ComponentException.php index 99f36a1d..5c08c0bf 100644 --- a/System/Exception/ComponentException.php +++ b/System/Exception/ComponentException.php @@ -10,6 +10,7 @@ declare(strict_types=1); namespace Snowflake\Exception; +use JetBrains\PhpStorm\Pure; use Throwable; /** @@ -19,7 +20,14 @@ use Throwable; class ComponentException extends \Exception { - public function __construct(string $message = "", int $code = 0, Throwable $previous = NULL) + + /** + * ComponentException constructor. + * @param string $message + * @param int $code + * @param Throwable|null $previous + */ + #[Pure] public function __construct(string $message = "", int $code = 0, Throwable $previous = NULL) { parent::__construct($message, 5000, $previous); } diff --git a/System/Exception/ConfigException.php b/System/Exception/ConfigException.php index 47c5a2b8..1729da57 100644 --- a/System/Exception/ConfigException.php +++ b/System/Exception/ConfigException.php @@ -5,6 +5,10 @@ declare(strict_types=1); namespace Snowflake\Exception; +/** + * Class ConfigException + * @package Snowflake\Exception + */ class ConfigException extends \Exception { diff --git a/System/Exception/InitException.php b/System/Exception/InitException.php index 73ab3770..3a141893 100644 --- a/System/Exception/InitException.php +++ b/System/Exception/InitException.php @@ -4,7 +4,10 @@ declare(strict_types=1); namespace Snowflake\Exception; - +/** + * Class InitException + * @package Snowflake\Exception + */ class InitException extends \Exception { diff --git a/System/Exception/NotFindClassException.php b/System/Exception/NotFindClassException.php index 2899d8b9..6c7c6ae6 100644 --- a/System/Exception/NotFindClassException.php +++ b/System/Exception/NotFindClassException.php @@ -10,6 +10,7 @@ declare(strict_types=1); namespace Snowflake\Exception; +use JetBrains\PhpStorm\Pure; use Throwable; /** @@ -19,7 +20,13 @@ use Throwable; class NotFindClassException extends \Exception { - public function __construct(string $message = "", int $code = 0, Throwable $previous = null) + /** + * NotFindClassException constructor. + * @param string $message + * @param int $code + * @param Throwable|null $previous + */ + #[Pure] public function __construct(string $message = "", int $code = 0, Throwable $previous = null) { $message = "No class named `$message` was found, please check if the class name is correct"; parent::__construct($message, 404, $previous); diff --git a/System/Exception/RedisConnectException.php b/System/Exception/RedisConnectException.php index 66fdeebf..23519bcf 100644 --- a/System/Exception/RedisConnectException.php +++ b/System/Exception/RedisConnectException.php @@ -5,6 +5,10 @@ declare(strict_types=1); namespace Snowflake\Exception; +/** + * Class RedisConnectException + * @package Snowflake\Exception + */ class RedisConnectException extends \Exception { diff --git a/System/Jwt/Jwt.php b/System/Jwt/Jwt.php index dd97caaa..d31bc2e3 100644 --- a/System/Jwt/Jwt.php +++ b/System/Jwt/Jwt.php @@ -10,9 +10,15 @@ use Snowflake\Abstracts\Config; use Snowflake\Core\Str; use Snowflake\Exception\AuthException; use Snowflake\Abstracts\Component; +use Snowflake\Exception\ComponentException; use Snowflake\Exception\ConfigException; use Snowflake\Snowflake; + +/** + * Class Jwt + * @package Snowflake\Jwt + */ class Jwt extends Component { @@ -122,7 +128,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return array * @throws Exception */ - public function create(int $unionId, $headers = []) + public function create(int $unionId, $headers = []): array { $this->user = $unionId; $this->config['time'] = time(); @@ -149,7 +155,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @throws Exception * 对相关信息进行加密 */ - private function createEncrypt($unionId) + private function createEncrypt($unionId): array { $caches = $this->clear($unionId); $param = $this->assembly(array_merge($this->config, [ @@ -182,7 +188,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return array * @throws */ - private function assembly(array $param, $update = FALSE) + private function assembly(array $param, $update = FALSE): array { if (isset($param['sign'])) { unset($param['sign']); @@ -205,7 +211,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return array * @throws Exception */ - public function refresh($headers = []) + public function refresh($headers = []): array { $this->data = $headers; if (!openssl_public_decrypt(base64_decode($headers['refresh']), $data, $this->public)) { @@ -226,9 +232,9 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= /** * @param $param * - * @return mixed + * @return array */ - private function initialize(array $param) + private function initialize(array $param): array { $_param = [ 'version' => '1', @@ -270,7 +276,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return string * @throws Exception */ - private function authKey(string $_source, string $token) + private function authKey(string $_source, string $token): string { $source = $this->getSource(); if (!empty($_source)) $source = $_source; @@ -283,7 +289,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= /** * @return string */ - public function getSource() + public function getSource(): string { return $this->data['source'] ?? 'browser'; } @@ -295,7 +301,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * * @return string */ - private function token(int $user, $param = [], $requestTime = NULL) + private function token(int $user, $param = [], $requestTime = NULL): string { $str = ''; @@ -318,7 +324,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return mixed * 将字符串替换成指定格式 */ - private function preg(string $str) + private function preg(string $str): mixed { $preg = '/(\w{10})(\w{3})(\w{4})(\w{9})(\w{6})/'; return preg_replace($preg, '$1-$2-$3-$4-$5', $str); @@ -329,7 +335,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return string[] * @throws Exception */ - public function clear(int $user) + public function clear(int $user): array { $this->user = $user; $redis = $this->getRedis(); @@ -356,7 +362,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return bool * @throws AuthException */ - public function check(array $data, int $user) + public function check(array $data, int $user): bool { $this->data = $data; $this->user = $user; @@ -378,7 +384,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return mixed * @throws */ - public function getCurrentOnlineUser() + public function getCurrentOnlineUser(): mixed { $this->data = request()->headers->getHeaders(); $model = $this->getUserModel(); @@ -398,10 +404,12 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= /** * @param array $header - * @return false|mixed + * @return mixed + * @throws AuthException + * @throws ComponentException * @throws Exception */ - public static function checkAuth(array $header = []) + public static function checkAuth(array $header = []): mixed { $instance = Snowflake::app()->getJwt(); if (empty($header)) { @@ -435,7 +443,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @throws AuthException * @throws Exception */ - private function getUserModel() + private function getUserModel(): bool|array { if (!isset($this->data['token'])) { throw new AuthException('暂无访问权限!'); @@ -448,7 +456,7 @@ mlAZUEjsoaT9vjvjGTxl3uCm0TX5KTgtSJIt2kA1tYVjQef+/iZTHxY= * @return Redis * @throws Exception */ - private function getRedis() + private function getRedis(): Redis { return Snowflake::app()->getRedis(); } diff --git a/System/Pool/Connection.php b/System/Pool/Connection.php index 80302bb3..5da4fe13 100644 --- a/System/Pool/Connection.php +++ b/System/Pool/Connection.php @@ -105,7 +105,7 @@ class Connection extends Pool * * db is in transaction */ - public function inTransaction($cds) + public function inTransaction($cds): bool { $coroutineName = $this->name($cds, true); if (!Context::hasContext('begin_' . $coroutineName)) { @@ -162,7 +162,7 @@ class Connection extends Pool * @param false $isMaster * @return array */ - private function getIndex($name, $isMaster = false) + private function getIndex($name, $isMaster = false): array { return [Coroutine::getCid(), $this->name($name, $isMaster)]; } @@ -197,7 +197,7 @@ class Connection extends Pool * @return mixed * @throws Exception */ - public function getConnection(array $config, $isMaster = false) + public function getConnection(array $config, $isMaster = false): mixed { $coroutineName = $this->name($config['cds'], $isMaster); if (!isset($this->hasCreate[$coroutineName])) { @@ -222,7 +222,7 @@ class Connection extends Pool * @param $client * @return mixed */ - private function saveClient($coroutineName, $client) + private function saveClient($coroutineName, $client): mixed { return Context::setContext($coroutineName, $client); } @@ -234,7 +234,7 @@ class Connection extends Pool * @return PDO * @throws Exception */ - private function nowClient($coroutineName, $config) + private function nowClient($coroutineName, $config): PDO { $client = $this->createConnect($coroutineName, ...$this->parseConfig($config)); if ($number = Context::getContext('begin_' . $coroutineName, Coroutine::getCid())) { @@ -251,7 +251,7 @@ class Connection extends Pool * @param $config * @return array */ - private function parseConfig($config) + private function parseConfig($config): array { return [$config['cds'], $config['username'], $config['password'], $config['charset'] ?? 'utf8mb4']; } @@ -283,7 +283,7 @@ class Connection extends Pool * @param $coroutineName * @return bool */ - private function hasClient($coroutineName) + private function hasClient($coroutineName): bool { return Context::hasContext($coroutineName); } @@ -323,19 +323,19 @@ class Connection extends Pool /** * @param $name * @param $time - * @param $connect + * @param $client * @return bool */ - public function checkCanUse($name, $time, $connect) + public function checkCanUse($name, $time, $client): bool { try { if ($time + 60 * 10 > time()) { return $result = true; } - if (empty($connect) || !($connect instanceof PDO)) { + if (empty($client) || !($client instanceof PDO)) { return $result = false; } - if (!$connect->getAttribute(PDO::ATTR_SERVER_INFO)) { + if (!$client->getAttribute(PDO::ATTR_SERVER_INFO)) { return $result = false; } return $result = true; @@ -358,7 +358,7 @@ class Connection extends Pool * @return PDO * @throws Exception */ - public function createConnect($coroutineName, $cds, $username, $password, $charset = 'utf8mb4') + public function createConnect($coroutineName, $cds, $username, $password, $charset = 'utf8mb4'): PDO { try { $link = new PDO($cds, $username, $password, [ @@ -408,9 +408,9 @@ class Connection extends Pool } /** - * @param $coroutineName + * @param string $coroutineName */ - public function desc($coroutineName) + public function desc(string $coroutineName) { if (!isset($this->hasCreate[$coroutineName])) { $this->hasCreate[$coroutineName] = 0; diff --git a/System/Pool/Pool.php b/System/Pool/Pool.php index e510273a..62459b6c 100644 --- a/System/Pool/Pool.php +++ b/System/Pool/Pool.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace Snowflake\Pool; -use Snowflake\Cache\Memcached; +use JetBrains\PhpStorm\Pure; use Snowflake\Snowflake; /** @@ -21,7 +21,7 @@ class Pool extends \Snowflake\Abstracts\Pool /** * @return Redis */ - public function getRedis() + #[Pure] public function getRedis(): Redis { return Snowflake::app()->redis_connections; } @@ -29,18 +29,10 @@ class Pool extends \Snowflake\Abstracts\Pool /** * @return Connection */ - public function getDb() + #[Pure] public function getDb(): Connection { return Snowflake::app()->connections; } - /** - * @return Memcached - */ - public function getMemcached() - { - return Snowflake::app()->memcached; - } - } diff --git a/System/Pool/Redis.php b/System/Pool/Redis.php index 04dae36c..93b434f0 100644 --- a/System/Pool/Redis.php +++ b/System/Pool/Redis.php @@ -31,10 +31,11 @@ class Redis extends Pool /** * @param array $config * @param bool $isMaster - * @return mixed|null + * @return mixed + * @throws RedisConnectException * @throws Exception */ - public function getConnection(array $config, $isMaster = false) + public function getConnection(array $config, $isMaster = false): mixed { $name = $config['host'] . ':' . $config['prefix'] . ':' . $config['databases']; $coroutineName = $this->name('redis:' . $name, $isMaster); @@ -53,7 +54,7 @@ class Redis extends Pool * @return mixed * @throws Exception */ - public function getByChannel($coroutineName, $config) + public function getByChannel($coroutineName, $config): mixed { if (!$this->hasItem($coroutineName)) { return $this->saveClient($coroutineName, $this->createConnect($config, $coroutineName)); @@ -72,7 +73,7 @@ class Redis extends Pool * @return mixed * @throws Exception */ - private function saveClient($coroutineName, $client) + private function saveClient($coroutineName, $client): mixed { return Context::setContext($coroutineName, $client); } @@ -84,7 +85,7 @@ class Redis extends Pool * @return SRedis * @throws RedisConnectException */ - private function createConnect(array $config, string $coroutineName) + private function createConnect(array $config, string $coroutineName): SRedis { $redis = new SRedis(); if (!$redis->connect($config['host'], (int)$config['port'], $config['timeout'])) { @@ -139,7 +140,7 @@ class Redis extends Pool /** * @param $coroutineName */ - public function remove($coroutineName) + public function remove(string $coroutineName) { Context::deleteId($coroutineName); } @@ -148,10 +149,10 @@ class Redis extends Pool * @param $name * @param $time * @param $client - * @return bool|mixed + * @return bool * @throws Exception */ - public function checkCanUse($name, $time, $client) + public function checkCanUse(string $name, int $time, mixed $client): bool { try { if ($time + 60 * 10 < time()) { @@ -173,7 +174,7 @@ class Redis extends Pool } } - public function desc($name) + public function desc(string $name) { // TODO: Implement desc() method. } diff --git a/System/Process/ServerInotify.php b/System/Process/ServerInotify.php index df4762cb..5ab17dd5 100644 --- a/System/Process/ServerInotify.php +++ b/System/Process/ServerInotify.php @@ -23,7 +23,7 @@ use Swoole\Timer; */ class ServerInotify extends Process { - private $inotify; + private mixed $inotify; private bool $isReloading = false; private bool $isReloadingOut = false; private array $watchFiles = []; @@ -80,10 +80,10 @@ class ServerInotify extends Process /** * @param $path * @param bool $isReload - * @return void|mixed + * @return mixed * @throws Exception */ - private function loadByDir($path, $isReload = false) + private function loadByDir($path, $isReload = false): mixed { $path = rtrim($path, '/'); foreach (glob(realpath($path) . '/*') as $value) { @@ -105,7 +105,7 @@ class ServerInotify extends Process * @param $isReload * @return bool */ - private function checkFile($value, $isReload) + private function checkFile($value, $isReload): bool { $md5 = md5($value); $mTime = filectime($value); @@ -243,7 +243,7 @@ class ServerInotify extends Process * @return bool * @throws Exception */ - public function watch($dir) + public function watch($dir): bool { //目录不存在 if (!is_dir($dir)) { diff --git a/System/Snowflake.php b/System/Snowflake.php index 3d1f72a0..53347ce8 100644 --- a/System/Snowflake.php +++ b/System/Snowflake.php @@ -25,6 +25,11 @@ defined('PARAMS_IS_NULL') or define('PARAMS_IS_NULL', 'Required items cannot be defined('CONTROLLER_PATH') or define('CONTROLLER_PATH', APP_PATH . 'app/Http/Controllers/'); defined('SOCKET_PATH') or define('SOCKET_PATH', APP_PATH . 'app/Websocket/'); + +/** + * Class Snowflake + * @package Snowflake + */ class Snowflake { @@ -135,7 +140,7 @@ class Snowflake /** * @param $workerId - * @return false|int|mixed + * @return mixed * @throws Exception */ public static function setProcessId($workerId): mixed @@ -146,7 +151,7 @@ class Snowflake /** * @param $workerId - * @return false|int|mixed + * @return mixed * @throws Exception */ public static function setWorkerId($workerId): mixed @@ -314,7 +319,7 @@ class Snowflake /** * @return bool */ - public static function isMac() + #[Pure] public static function isMac(): bool { $output = strtolower(PHP_OS | PHP_OS_FAMILY); if (str_contains('mac', $output)) { @@ -329,7 +334,7 @@ class Snowflake /** * @return bool */ - public static function isLinux(): bool + #[Pure] public static function isLinux(): bool { if (!static::isMac()) { return true; diff --git a/Validator/ArrayValidator.php b/Validator/ArrayValidator.php index 711e3849..232e1fe2 100644 --- a/Validator/ArrayValidator.php +++ b/Validator/ArrayValidator.php @@ -10,15 +10,19 @@ declare(strict_types=1); namespace validator; +/** + * Class ArrayValidator + * @package validator + */ class ArrayValidator extends BaseValidator { - + /** - * @return array|bool + * @return bool * * 检查 */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !is_array($param)) { @@ -30,16 +34,16 @@ class ArrayValidator extends BaseValidator if (!is_array($param[$this->field])) { return $this->addError("The param :attribute must a array"); } - return $this->toArray($param[$this->field]); + return true; } - + /** * @param $data * @return array * * 转成数组 */ - private function toArray($data) + private function toArray($data): array { if (is_numeric($data)) { return []; @@ -48,7 +52,7 @@ class ArrayValidator extends BaseValidator } elseif (is_object($data)) { $data = get_object_vars($data); } - + $_tmp = []; foreach ($data as $key => $val) { if (is_object($val)) { @@ -59,8 +63,8 @@ class ArrayValidator extends BaseValidator $_tmp[$key] = $val; } } - + return $_tmp; } - + } diff --git a/Validator/BaseValidator.php b/Validator/BaseValidator.php index af49b13a..1f5b908d 100644 --- a/Validator/BaseValidator.php +++ b/Validator/BaseValidator.php @@ -5,6 +5,7 @@ namespace validator; use Database\ActiveRecord; +use Exception; abstract class BaseValidator { @@ -24,6 +25,10 @@ abstract class BaseValidator /** @var ActiveRecord */ protected ActiveRecord $model; + + /** + * @param $model + */ public function setModel($model) { $this->model = $model; @@ -32,16 +37,25 @@ abstract class BaseValidator /** * @return ActiveRecord */ - public function getModel() + public function getModel(): ActiveRecord { return $this->model; } + + /** + * BaseValidator constructor. + * @param array $config + */ public function __construct($config = []) { $this->regConfig($config); } + + /** + * @param $config + */ private function regConfig($config) { if (empty($config) || !is_array($config)) { @@ -53,27 +67,27 @@ abstract class BaseValidator } /** - * @throws \Exception + * @throws Exception * @return bool */ - public function trigger() + public function trigger(): bool { - throw new \Exception('Child Class must define method of trigger'); + throw new Exception('Child Class must define method of trigger'); } /** - * @return mixed + * @return array */ - protected function getParams() + protected function getParams(): array { return $this->params; } /** - * @param $data + * @param array $data * @return $this */ - public function setParams($data) + public function setParams(array $data): static { $this->params = $data; return $this; @@ -83,7 +97,7 @@ abstract class BaseValidator * @param $message * @return bool */ - public function addError($message) + public function addError($message): bool { $this->isFail = FALSE; @@ -97,7 +111,7 @@ abstract class BaseValidator /** * @return string */ - public function getError() + public function getError(): string { return $this->message; } @@ -105,7 +119,7 @@ abstract class BaseValidator /** * @param $name * @param $value - * @throws \Exception + * @throws Exception */ public function __set($name, $value) { @@ -115,7 +129,7 @@ abstract class BaseValidator } else if (property_exists($this, $name)) { $this->$name = $value; } else { - throw new \Exception('unknown property ' . $name . ' in class ' . get_called_class()); + throw new Exception('unknown property ' . $name . ' in class ' . get_called_class()); } } } diff --git a/Validator/DateTimeValidator.php b/Validator/DateTimeValidator.php index 9c5e96a4..6fe093fa 100644 --- a/Validator/DateTimeValidator.php +++ b/Validator/DateTimeValidator.php @@ -23,7 +23,7 @@ class DateTimeValidator extends BaseValidator /** * @return bool */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !is_array($param)) { @@ -53,7 +53,7 @@ class DateTimeValidator extends BaseValidator * * 效验分秒 格式如 01:02 or 01-02 */ - public function validatorTime($value) + public function validatorTime($value): bool { if (empty($value) || !is_string($value)) { return $this->addError('The param :attribute not is a date value'); @@ -73,7 +73,7 @@ class DateTimeValidator extends BaseValidator * * 效验分秒 格式如 2017-12-22 01:02 */ - public function validateDatetime($value) + public function validateDatetime($value): bool { if (empty($value) || !is_string($value)) { return $this->addError('The param :attribute not is a date value'); @@ -93,7 +93,7 @@ class DateTimeValidator extends BaseValidator * * 效验分秒 格式如 2017-12-22 */ - public function validatorDate($value) + public function validatorDate($value): bool { if (empty($value) || !is_string($value)) { return $this->addError('The param :attribute not is a date value'); @@ -112,7 +112,7 @@ class DateTimeValidator extends BaseValidator * * 效验时间戳 格式如 1521452254 */ - public function validatorTimestamp($value) + public function validatorTimestamp($value): bool { if (empty($value) || !is_numeric($value)) { return $this->addError('The param :attribute not is a timestamp value'); diff --git a/Validator/EmailValidator.php b/Validator/EmailValidator.php index 0b7d7d41..6ec3df78 100644 --- a/Validator/EmailValidator.php +++ b/Validator/EmailValidator.php @@ -17,7 +17,7 @@ class EmailValidator extends BaseValidator * @return bool * 检查是否存在 */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !isset($param[$this->field])) { diff --git a/Validator/EmptyValidator.php b/Validator/EmptyValidator.php index 69e885a6..de861da4 100644 --- a/Validator/EmptyValidator.php +++ b/Validator/EmptyValidator.php @@ -28,7 +28,7 @@ class EmptyValidator extends BaseValidator * * 检查参数是否为NULL */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !isset($param[$this->field])) { diff --git a/Validator/EnumValidator.php b/Validator/EnumValidator.php index f5524ef6..dde2338e 100644 --- a/Validator/EnumValidator.php +++ b/Validator/EnumValidator.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace validator; +use JetBrains\PhpStorm\Pure; + /** * Class EnumValidator * @package validator @@ -16,7 +18,7 @@ class EnumValidator extends BaseValidator /** * @return bool */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !isset($param[$this->field])) { @@ -40,7 +42,7 @@ class EnumValidator extends BaseValidator /** * @return string */ - private function i() + #[Pure] private function i(): string { return 'The param :attribute value only in ' . implode(',', $this->value); } diff --git a/Validator/IntegerValidator.php b/Validator/IntegerValidator.php index 7ad60709..4afc8af5 100644 --- a/Validator/IntegerValidator.php +++ b/Validator/IntegerValidator.php @@ -22,7 +22,7 @@ class IntegerValidator extends BaseValidator /** * @return bool */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !isset($param[$this->field])) { diff --git a/Validator/LengthValidator.php b/Validator/LengthValidator.php index d4cfade7..72ec3121 100644 --- a/Validator/LengthValidator.php +++ b/Validator/LengthValidator.php @@ -23,7 +23,7 @@ class LengthValidator extends BaseValidator /** * @return bool */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !isset($param[$this->field])) { @@ -53,7 +53,7 @@ class LengthValidator extends BaseValidator * * 效验长度是否大于最大长度 */ - private function maxLength($value) + private function maxLength($value): bool { if (is_array($value)) { if (count($value) > $value) { @@ -76,7 +76,7 @@ class LengthValidator extends BaseValidator * * 效验长度是否小于最小长度 */ - private function minLength($value) + private function minLength($value): bool { if (is_array($value)) { if (count($value) < $value) { @@ -99,7 +99,7 @@ class LengthValidator extends BaseValidator * * 效验长度是否小于最小长度 */ - private function defaultLength($value) + private function defaultLength($value): bool { if (is_array($value)) { if (count($value) !== $value) { diff --git a/Validator/RequiredValidator.php b/Validator/RequiredValidator.php index 782bee55..decf5ced 100644 --- a/Validator/RequiredValidator.php +++ b/Validator/RequiredValidator.php @@ -17,7 +17,7 @@ class RequiredValidator extends BaseValidator * @return bool * 检查是否存在 */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (is_numeric($param)) { diff --git a/Validator/TypesOfValidator.php b/Validator/TypesOfValidator.php index ee277e45..32e84af6 100644 --- a/Validator/TypesOfValidator.php +++ b/Validator/TypesOfValidator.php @@ -41,7 +41,7 @@ class TypesOfValidator extends BaseValidator /** * @return bool */ - public function trigger() + public function trigger(): bool { if (!in_array($this->method, $this->types)) { return true; @@ -67,7 +67,7 @@ class TypesOfValidator extends BaseValidator * @param $value * @return bool */ - public function jsonFormat($value) + public function jsonFormat($value): bool { if (!is_string($value) || is_numeric($value)) { return $this->addError('The ' . $this->field . ' not is JSON data.'); @@ -82,7 +82,7 @@ class TypesOfValidator extends BaseValidator * @param $value * @return bool */ - public function serializeFormat($value) + public function serializeFormat($value): bool { if (!is_string($value) || is_numeric($value)) { return $this->addError('The ' . $this->field . ' not is serialize data.'); @@ -97,7 +97,7 @@ class TypesOfValidator extends BaseValidator * @param $value * @return bool */ - public function arrayFormat($value) + public function arrayFormat($value): bool { if (!is_array($value)) { return $this->addError('The ' . $this->field . ' not is array data.'); @@ -109,7 +109,7 @@ class TypesOfValidator extends BaseValidator * @param $value * @return bool */ - public function stringFormat($value) + public function stringFormat($value): bool { if (is_array($value) || is_object($value) || is_bool($value)) { return $this->addError('The ' . $this->field . ' not is string data.'); @@ -121,7 +121,7 @@ class TypesOfValidator extends BaseValidator * @param $value * @return bool */ - public function integerFormat($value) + public function integerFormat($value): bool { if (!is_numeric($value)) { return $this->addError('The ' . $this->field . ' not is number data.'); @@ -137,7 +137,7 @@ class TypesOfValidator extends BaseValidator * @param $value * @return bool */ - public function floatFormat($value) + public function floatFormat($value): bool { $trim = floatval((string)$value); if ($trim != $value || !is_float($trim)) { diff --git a/Validator/UniqueValidator.php b/Validator/UniqueValidator.php index 83f30390..2e423a35 100644 --- a/Validator/UniqueValidator.php +++ b/Validator/UniqueValidator.php @@ -18,7 +18,7 @@ class UniqueValidator extends BaseValidator * @throws * 检查是否存在 */ - public function trigger() + public function trigger(): bool { $param = $this->getParams(); if (empty($param) || !isset($param[$this->field])) { diff --git a/Validator/Validator.php b/Validator/Validator.php index 38f140c8..88755af6 100644 --- a/Validator/Validator.php +++ b/Validator/Validator.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace validator; +use Closure; use Exception; use Snowflake\Snowflake; @@ -104,9 +105,9 @@ class Validator extends BaseValidator ]; /** - * @return Validator + * @return Validator|null */ - public static function getInstance() + public static function getInstance(): ?Validator { if (static::$instance == null) { static::$instance = new Validator(); @@ -120,7 +121,7 @@ class Validator extends BaseValidator * @return $this * @throws Exception */ - public function make($field, $rules) + public function make($field, $rules): static { if (!is_array($field)) { $field = [$field]; @@ -176,7 +177,7 @@ class Validator extends BaseValidator * @return bool * @throws Exception */ - public function validation() + public function validation(): bool { if (count($this->validators) < 1) { return true; @@ -197,11 +198,11 @@ class Validator extends BaseValidator } /** - * @param BaseValidator $val + * @param BaseValidator|array|Closure $val * @return mixed - * @throws + * @throws Exception */ - private function check($val) + private function check(BaseValidator|array|Closure $val): mixed { if (is_callable($val, true)) { return call_user_func($val, $this); diff --git a/composer.json b/composer.json index 557ea1f6..4e2512c0 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,6 @@ "ext-iconv": "*", "ext-mbstring": "*", "ext-xml": "*", - "ext-memcached": "*", "ext-inotify": "*", "ext-curl": "*", "ext-openssl": "*",