This commit is contained in:
2020-12-17 14:09:14 +08:00
parent 672a719dbd
commit 36c1d0502a
151 changed files with 1937 additions and 2848 deletions
+2 -1
View File
@@ -7,6 +7,7 @@ namespace Annotation;
use ReflectionAttribute;
use 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;
+28 -35
View File
@@ -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();
}
+36 -34
View File
@@ -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;
+4 -2
View File
@@ -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
+18 -15
View File
@@ -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);
}
+18 -17
View File
@@ -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;
}
+38 -38
View File
@@ -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 驱动错误.';
}
+6 -5
View File
@@ -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);
}
+1 -1
View File
@@ -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];
}
+1 -1
View File
@@ -14,7 +14,7 @@ class ChildCondition extends Condition
/**
* @return string
*/
public function builder()
public function builder(): string
{
return $this->column . ' ' . $this->opera . ' (' . $this->value . ')';
}
+6 -5
View File
@@ -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) {
+1 -1
View File
@@ -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);
}
+1 -1
View File
@@ -12,7 +12,7 @@ class HashCondition extends Condition
/**
* @return string
*/
public function builder()
public function builder(): string
{
$array = [];
if (empty($this->value)) {
+3 -2
View File
@@ -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);
+1 -1
View File
@@ -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);
+1 -1
View File
@@ -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);
+7 -7
View File
@@ -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;
}
+1 -1
View File
@@ -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];
}
+1 -1
View File
@@ -14,7 +14,7 @@ class NotInCondition extends Condition
/**
* @return string
*/
public function builder()
public function builder(): string
{
$format = array_filter($this->format($this->value));
+1 -1
View File
@@ -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);
+1 -1
View File
@@ -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);
}
+1 -1
View File
@@ -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);
+21 -17
View File
@@ -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();
}
+3 -3
View File
@@ -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);
}
+22 -22
View File
@@ -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;
+3 -6
View File
@@ -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;
+2 -2
View File
@@ -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);
}
+3 -3
View File
@@ -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);
}
+2 -2
View File
@@ -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);
}
+4 -4
View File
@@ -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);
+37 -37
View File
@@ -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)) {
+6 -6
View File
@@ -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]);
+13 -12
View File
@@ -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;
}
+20 -15
View File
@@ -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;
+7 -6
View File
@@ -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;
}
+10 -10
View File
@@ -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;
+13 -14
View File
@@ -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);
+3 -2
View File
@@ -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);
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -27,7 +27,7 @@ class Command extends \Console\Command
* @return array
* @throws Exception
*/
public function onHandler(Input $dtl)
public function onHandler(Input $dtl): array
{
/** @var Gii $gii */
$gii = Snowflake::app()->get('gii');
+18 -20
View File
@@ -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';
}
}
+24 -22
View File
@@ -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;
}
+26 -16
View File
@@ -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 = '';
+2 -5
View File
@@ -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);
+2 -5
View File
@@ -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);
+2 -7
View File
@@ -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);
+30 -24
View File
@@ -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'] ?? '';
+1 -7
View File
@@ -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);
+1 -1
View File
@@ -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
+1 -1
View File
@@ -25,7 +25,7 @@ abstract class ServerBase extends Application
/**
* @return Server
*/
public function getServer()
public function getServer(): Server
{
return $this->server;
}
+4 -3
View File
@@ -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;
+8 -8
View File
@@ -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);
}
+11 -11
View File
@@ -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();
+95 -104
View File
@@ -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,
+15 -14
View File
@@ -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) {
+9 -9
View File
@@ -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);
+2 -1
View File
@@ -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;
}
+2 -2
View File
@@ -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;
+14 -13
View File
@@ -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;
}
+3 -3
View File
@@ -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();
}
}
+6 -10
View File
@@ -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);
}
-5
View File
@@ -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;
/**
+4
View File
@@ -8,6 +8,10 @@ use Exception;
use HttpServer\Abstracts\Callback;
use Swoole\Server;
/**
* Class OnFinish
* @package HttpServer\Events
*/
class OnFinish extends Callback
{
/**
+4 -5
View File
@@ -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);
+2 -3
View File
@@ -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)
{
+2 -1
View File
@@ -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)
{
+1 -2
View File
@@ -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);
+1 -1
View File
@@ -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);
-4
View File
@@ -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;
-8
View File
@@ -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
+2 -3
View File
@@ -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)
{
-5
View File
@@ -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;
/**
+2 -1
View File
@@ -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)
{
+2 -2
View File
@@ -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)) {
+10 -2
View File
@@ -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);
}
+2 -1
View File
@@ -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);
}
+3 -3
View File
@@ -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;
+2 -1
View File
@@ -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
{
+2 -2
View File
@@ -49,9 +49,9 @@ class XmlFormatter extends Application implements IFormatter
}
/**
* @return mixed
* @return string|null
*/
public function getData(): mixed
public function getData(): ?string
{
$data = $this->data;
$this->clear();
+38 -35
View File
@@ -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;
-257
View File
@@ -1,257 +0,0 @@
<?php
declare(strict_types=1);
namespace HttpServer\Route\Annotation;
use HttpServer\IInterface\After;
use HttpServer\IInterface\Interceptor;
use HttpServer\IInterface\Limits;
use HttpServer\Route\Node;
use ReflectionClass;
use ReflectionException;
use Snowflake\Annotation\Annotation;
use Snowflake\Snowflake;
/**
* Class Annotation
*/
class Http extends Annotation
{
const HTTP_EVENT = 'http:event:';
const CLOSE = 'Close';
/**
* @var string
* @Interceptor(LoginInterceptor)
*/
private string $Interceptor = 'required|not empty';
/**
* @var string
*/
private string $Limits = 'required|not empty';
private string $Method = 'post';
private string $Middleware = '';
private string $After = '';
protected array $_annotations = [];
/**
* @param Node $node
* @param ReflectionClass $reflect
* @param $method
* @param $annotations
* @throws ReflectionException
*/
public function read(Node $node, ReflectionClass $reflect, $method, $annotations)
{
$method = $reflect->getMethod($method);
$_annotations = $this->getDocCommentAnnotation($annotations, $method->getDocComment());
foreach ($_annotations as $keyName => $annotation) {
if (!in_array($keyName, $annotations)) {
continue;
}
$this->bind($keyName, $node, $annotation);
}
}
/**
* @param $keyName
* @param $node
* @param $annotation
*/
private function bind($keyName, $node, $annotation)
{
switch ($keyName) {
case 'Method':
$this->bindMethod($node, $annotation);
break;
case'Interceptor':
$this->bindInterceptors($node, $annotation);
break;
case 'Middleware':
$this->bindMiddleware($node, $annotation);
break;
case 'Limits':
$this->bindLimits($node, $annotation);
break;
case 'After':
$this->bindAfter($node, $annotation);
break;
}
}
/**
* @param $node
* @param $annotation
*/
private function bindMethod($node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
if (in_array('any', $explode)) {
$explode = ['*'];
}
$node->method = $explode;
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindMiddleware(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\Middleware\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$node->addMiddleware($middleware);
}
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindInterceptors(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\Interceptor\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$middleware = Snowflake::createObject($middleware);
if (!($middleware instanceof Interceptor)) {
continue;
}
$node->addInterceptor([$middleware, 'Interceptor']);
}
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindAfter(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\After\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$middleware = Snowflake::createObject($middleware);
if (!($middleware instanceof After)) {
continue;
}
$node->addAfter([$middleware, 'onHandler']);
}
}
/**
* @param Node $node
* @param $annotation
* @throws
*/
private function bindLimits(Node $node, $annotation)
{
if (!isset($annotation[1][2])) {
return;
}
$explode = explode(',', $annotation[1][2]);
foreach ($explode as $middleware) {
if (strpos($middleware, '\\') !== 0) {
$middleware = 'App\Http\Limits\\' . $middleware;
}
if (!class_exists($middleware)) {
continue;
}
$middleware = Snowflake::createObject($middleware);
if (!($middleware instanceof Limits)) {
continue;
}
$node->addLimits([$middleware, 'next']);
}
}
/**
* @param $controller
* @param $methodName
* @param $events
* @return array|void
* @throws
*/
public function createHandler($controller, $methodName, $events)
{
return Snowflake::createObject($events[2]);
}
/**
* @param $events
* @return bool
*/
public function isLegitimate($events)
{
return isset($events[2]) && !empty($events[2]);
}
/**
* @param $name
* @param $comment
* @return false|string
*/
public function getName($name, $comment = [])
{
$prefix = self::HTTP_EVENT . ltrim($name, ':');
if (isset($comment[2]) && !empty($comment[2])) {
return $prefix . ':' . $comment[2];
}
return $prefix;
}
}
-62
View File
@@ -1,62 +0,0 @@
<?php
declare(strict_types=1);
namespace HttpServer\Route\Annotation;
use Snowflake\Annotation\Annotation;
/**
* Class Tcp
* @package HttpServer\Route\Annotation
*/
class Tcp extends Annotation
{
const CONNECT = 'Connect';
const PACKET = 'Packet';
const RECEIVE = 'Receive';
const CLOSE = 'Close';
private string $Message = 'required|not empty';
/**
* @param $controller
* @param $methodName
* @param $events
* @return array
*/
public function createHandler($controller, $methodName, $events)
{
return [$controller, $methodName];
}
/**
* @param $events
* @return bool|void
*/
public function isLegitimate($events)
{
return true;
}
/**
* @param $events
* @param $comment
* @return false|string
*/
public function getName($events, $comment = [])
{
$prefix = 'TCP:ANNOTATION:' . ltrim($events, ':');
if (isset($comment[2]) && !empty($comment[2])) {
return $prefix . ':' . $comment[2];
}
return $prefix;
}
}
-65
View File
@@ -1,65 +0,0 @@
<?php
declare(strict_types=1);
namespace HttpServer\Route\Annotation;
use Snowflake\Annotation\Annotation;
/**
* Class Websocket
* @package Snowflake\Annotation
*/
class Websocket extends Annotation
{
const MESSAGE = 'Message';
const HANDSHAKE = 'Handshake';
const CLOSE = 'Close';
private string $Message = 'required|not empty';
private string $Handshake;
private string $Close;
/**
* @param $controller
* @param $methodName
* @param $events
* @return array
*/
public function createHandler($controller, $methodName, $events)
{
return [$controller, $methodName];
}
/**
* @param $events
* @return bool|void
*/
public function isLegitimate($events)
{
return true;
}
/**
* @param $events
* @param $comment
* @return false|string
*/
public function getName($events, $comment = [])
{
$prefix = 'WEBSOCKET:ANNOTATION:' . ltrim($events, ':');
if (isset($comment[2]) && !empty($comment[2])) {
return $prefix . ':' . $comment[2];
}
return $prefix;
}
}
+2 -2
View File
@@ -12,7 +12,7 @@ namespace HttpServer\Route;
class Any
{
private $nodes = [];
private array $nodes = [];
/**
* Any constructor.
@@ -29,7 +29,7 @@ class Any
* @param $arguments
* @return $this
*/
public function __call($name, $arguments)
public function __call($name, $arguments): static
{
foreach ($this->nodes as $node) {
$node->{$name}(...$arguments);
+7 -7
View File
@@ -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;
+1 -1
View File
@@ -18,7 +18,7 @@ class BodyFilter extends Filter
* @return bool
* @throws Exception
*/
public function check()
public function check(): bool
{
return $this->validator();
}
+1 -1
View File
@@ -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);
+9 -1
View File
@@ -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);
}
+1 -1
View File
@@ -18,7 +18,7 @@ class HeaderFilter extends Filter
* @return bool
* @throws Exception
*/
public function check()
public function check(): bool
{
return $this->validator();
}
+1 -1
View File
@@ -18,7 +18,7 @@ class QueryFilter extends Filter
* @return bool
* @throws Exception
*/
public function check()
public function check(): bool
{
return $this->validator();
}
+4 -2
View File
@@ -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');
}
-1
View File
@@ -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;
/**
+26 -34
View File
@@ -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;
}
+4 -7
View File
@@ -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();
}
+3 -3
View File
@@ -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)) {
+1 -1
View File
@@ -16,7 +16,7 @@ interface ConsumerInterface
* @param Struct $struct
* @return mixed
*/
public function onHandler(Struct $struct);
public function onHandler(Struct $struct): mixed;
}
+1 -1
View File
@@ -144,7 +144,7 @@ class Kafka extends \Snowflake\Process\Process
* @param $kafka
* @return array
*/
private function kafkaConfig($kafka)
private function kafkaConfig($kafka): array
{
$conf = new Conf();
$conf->setRebalanceCb([$this, 'rebalanced_cb']);
+15 -10
View File
@@ -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);
+2 -2
View File
@@ -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;
-157
View File
@@ -1,157 +0,0 @@
<?php
declare(strict_types=1);
namespace Snowflake\Abstracts;
use Exception;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
/**
* Class BaseAnnotation
* @package Snowflake\Snowflake\Annotation\Base
*/
abstract class BaseAnnotation extends Component
{
/**
* @param ReflectionClass $reflect
* @param string $method
* @param array $annotations
* @return array
* @throws ReflectionException
* @throws Exception
*/
public function instance(ReflectionClass $reflect, $method = '', $annotations = [])
{
$classMethods = $reflect->getMethods(ReflectionMethod::IS_PUBLIC);
if (!$reflect->isInstantiable()) {
throw new Exception('Class ' . $reflect->getName() . ' cannot be instantiated.');
}
$array = [];
$object = $reflect->newInstance();
if (!empty($method)) {
$array = $this->resolveDocComment($reflect->getMethod($method), $object, $annotations, $array);
} else {
foreach ($classMethods as $classMethod) {
$array = $this->resolveDocComment($classMethod, $object, $annotations, $array);
}
}
return $array;
}
/**
* @param ReflectionMethod $function
* @param $object
* @param $annotations
* @param $array
* @return array
* @throws
*/
protected function resolveDocComment(ReflectionMethod $function, $object, $annotations, $array)
{
$comment = $function->getDocComment();
$array = $this->getDocCommentAnnotation($annotations, $comment);
foreach ($array as $name => $annotation) {
foreach ($annotation as $index => $events) {
if (!isset($events[1])) {
continue;
}
if (!($_key = $this->getName($name, $events))) {
continue;
}
if (isset($item[2])) {
$handler = Snowflake::createObject($events[2]);
} else {
$handler = [$object, $events[1]];
}
if (!isset($array[$annotation])) {
$array[$annotation] = [];
}
$array[$name][] = [$_key, $handler];
}
}
return $array;
}
/**
* @param $object
* @param $events
* @throws NotFindClassException
* @throws ReflectionException
*/
protected function getOrCreate($object, $events)
{
if (isset($item[2])) {
$handler = Snowflake::createObject($events[2]);
} else {
$handler = [$object, $events[1]];
}
}
/**
* @param $annotations
* @param $comment
* @return array
*/
protected function getDocCommentAnnotation($annotations, $comment)
{
$array = [];
foreach ($annotations as $annotation) {
if (!$comment) {
continue;
}
preg_match('/@(' . $annotation . ')\((.*?)\)/', $comment, $events);
if (!isset($events[1])) {
continue;
}
if (!isset($array[$annotation])) {
$array[$annotation] = [];
}
$array[$annotation] = [$annotation, $events];
}
return $array;
}
/**
* @param $rule
* @param $content
* @param $rules
* @return bool
* @throws ReflectionException
* @throws NotFindClassException
* @throws Exception
*/
public function check($rule, $content, $rules)
{
if (empty($rule)) {
return true;
}
$explode = explode('|', $rule);
foreach ($explode as $value) {
$reflect = array_merge($rules[$value], [
'value' => $content
]);
$validator = Snowflake::createObject($reflect);
if (!$validator->check()) {
throw new Exception($validator->getMessage());
}
}
return false;
}
abstract public function runWith($path);
}

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