初始化本地仓库

This commit is contained in:
2026-08-31 11:33:59 +08:00
commit 663f74b633
2390 changed files with 402918 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
<?php
/**
*+------------------
* madong
*+------------------
* Copyright (c) https://gitee.com/motion-code All rights reserved.
*+------------------
* Author: Mr. April (405784684@qq.com)
*+------------------
* Official Website: http://www.madong.tech
*/
namespace core\base;
abstract class BaseController
{
/**
* @var \core\base\BaseService|null
*/
protected BaseService|null $service = null;
/**
* @var \core\base\BaseValidate|null
*/
protected BaseValidate|null $validate=null;
/**
* 构造方法
*
* @access public
*/
public function __construct()
{
$this->initialize();
}
/**
* @return void
*/
abstract protected function initialize(): void;
}
File diff suppressed because it is too large Load Diff
+293
View File
@@ -0,0 +1,293 @@
<?php
/**
*+------------------
* madong
*+------------------
* Copyright (c) https://gitee.com/motion-code All rights reserved.
*+------------------
* Author: Mr. April (405784684@qq.com)
*+------------------
* Official Website: http://www.madong.tech
*/
namespace core\base;
use app\adminapi\CurrentUser;
use app\model\system\RecycleBin;
use app\scope\global\AccessPermissionScope;
use app\service\admin\system\RecycleBinService;
use Carbon\Carbon;
use core\exception\handler\AdminException;
use core\uuid\Snowflake;
use Illuminate\Database\Eloquent\SoftDeletes;
use support\Container;
use support\Model;
class BaseModel extends Model
{
/**
* 指明模型的ID是否自动递增。
* false = 雪花ID(默认);true = 数据库自增ID
* 子类如需自增ID,覆盖为: public $incrementing = true;
*
* @var bool
*/
public $incrementing = false;
/**
* 主键类型
* 雪花ID默认为 'string',自增ID子类应覆盖为: protected $keyType = 'int';
*
* @var string
*/
protected $keyType = 'string';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
const DELETED_AT = 'deleted_at';
protected $appends = [];
/**
* 隐藏属性
*
* @var array
*/
protected $hidden = [];
/**
* 模型日期字段的存储格式。
*
* @var string
*/
protected $dateFormat = 'U';
/**
* 指示模型是否主动维护时间戳。
*
* @var bool
*/
public $timestamps = true;
public function __construct(array $data = [])
{
parent::__construct($data);
}
protected static function booted(): void
{
// 添加全局数据权限作用域-这里主要添加数据权限子类重写开启默认关闭
// static::addGlobalScope(new AccessPermissionScope);
}
protected static function boot()
{
parent::boot();
//注册创建事件
static::creating(function ($model) {
// 仅非自增主键时自动生成雪花ID
if (!$model->getIncrementing() && !isset($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = (string)Snowflake::generate();
}
self::setCreatedBy($model);
});
// 注册更新事件
static::updating(function ($model) {
self::setUpdatedBy($model);
});
// 注册删除事件
static::deleted(function ($model) {
self::onAfterDelete($model);
});
}
/**
* 是否开启软删
*
* @return bool
*/
public static function isSoftDeleteEnabled(): bool
{
return in_array(SoftDeletes::class, class_uses(static::class));
}
/**
* 获取主键名称
*
* @return string
*/
public function getPk(): string
{
return $this->getKeyName();
}
/**
* 获取模型字段数据
*
* @param string $field
*
* @return mixed
*/
public function getData(string $field): mixed
{
return $this->attributes[$field] ?? null;
}
/**
* 写入模型字段数据
*
* @param string $name
* @param mixed $value
*/
public function set(string $name, mixed $value): void
{
$this->attributes[$name] = $value;
}
/**
* 获取模型的字段列表
*
* @return array
*/
public function getFields(): array
{
try {
$tableName = $this->getTable();
$connection = $this->getConnection();
$prefix = $connection->getTablePrefix();
$fullTableName = $prefix . $tableName;
$fields = $connection->select("SHOW COLUMNS FROM `{$fullTableName}`");
return array_map(function ($column) {
return $column->Field;
}, $fields);
} catch (\Exception $e) {
return [];
}
}
/**
* 追加创建时间
*
* @return string|null
*/
public function getCreatedDateAttribute(): ?string
{
if ($this->getAttribute($this->getCreatedAtColumn())) {
try {
$timestamp = $this->getRawOriginal($this->getCreatedAtColumn());
if (empty($timestamp)) {
return null;
}
$carbonInstance = Carbon::createFromTimestamp($timestamp);
return $carbonInstance->setTimezone(config('app.default_timezone'))->format('Y-m-d H:i:s');
} catch (\Exception $e) {
return null;
}
}
return null;
}
/**
* 追加更新时间
*
* @return string|null
*/
public function getUpdatedDateAttribute(): ?string
{
if ($this->getAttribute($this->getUpdatedAtColumn())) {
try {
$timestamp = $this->getRawOriginal($this->getUpdatedAtColumn());
if (empty($timestamp)) {
return null;
}
$carbonInstance = Carbon::createFromTimestamp($timestamp);
return $carbonInstance->setTimezone(config('app.default_timezone'))->format('Y-m-d H:i:s');
} catch (\Exception $e) {
return null;
}
}
return null;
}
/**
* 删除事件
*
* @param \support\Model $model
*
* @throws \core\exception\handler\AdminException
*/
public static function onAfterDelete(Model $model)
{
try {
$table = $model->getTable();
/** @var RecycleBinService $recycleService */
$service = Container::make(RecycleBinService::class);
$config = $service->getTableConfig($table);
// 检查是否启用回收站
if (!$config['enabled'] || $model->isSoftDeleteEnabled() || $config['strategy'] === 'logical') {
return;
}
$prefix = $model->getConnection()->getTablePrefix();
// 准备数据(排除敏感字段)
$tableData = array_except($model->getAttributes(), $config['exclude_fields'] ?? []);
$tableData['original_id'] = $model->getAttribute($model->getPk());
$data = self::prepareRecycleBinData($tableData, $table, $prefix);
// 动态选择存储方式
$handler = fn() => RecycleBin::centralConnection();
$handler()->create($data);
} catch (\Exception $e) {
throw new AdminException($e->getMessage());
}
}
/**
* 设置创建人
*
* @param Model $model
*
* @return void
*/
private static function setCreatedBy(Model $model): void
{
$uid = Container::make(CurrentUser::class)->id();
if ($uid && $model->isFillable('created_by')) {
$model->setAttribute('created_by', $uid);
}
}
/**
* 设置更新人
*
* @param Model $model
*
* @return void
*/
private static function setUpdatedBy(Model $model): void
{
$uid = Container::make(CurrentUser::class)->id();
if ($uid && $model->isFillable('updated_by')) {
$model->setAttribute('updated_by', $uid);
}
}
private static function prepareRecycleBinData($tableData, $table, $prefix): array
{
return [
'data' => $tableData,
'original_id' => $tableData['id'] ?? '',
'table_name' => $table,
'table_prefix' => $prefix,
'enabled' => 0,
'ip' => request()->getRealIp(),
'operate_id' => Container::make(CurrentUser::class)->id(),
];
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
/**
*+------------------
* madong
*+------------------
* Copyright (c) https://gitee.com/motion-code All rights reserved.
*+------------------
* Author: Mr. April (405784684@qq.com)
*+------------------
* Official Website: http://www.madong.tech
*/
namespace core\base;
use Illuminate\Database\Eloquent\Relations\Pivot;
class BasePivot extends Pivot
{
}
+108
View File
@@ -0,0 +1,108 @@
<?php
/**
*+------------------
* madong
*+------------------
* Copyright (c) https://gitee.com/motion-code All rights reserved.
*+------------------
* Author: Mr. April (405784684@qq.com)
*+------------------
* Official Website: http://www.madong.tech
*/
namespace core\base;
use core\cache\CacheService;
use core\trait\ServiceTrait;
use support\Db as LaravelDb;
/**
* @method getModel()
*/
abstract class BaseService
{
use ServiceTrait;
/**
* 模型注入
*/
protected ?BaseDao $dao;
/**
* 缓存管理
*
* @return \core\cache\CacheService
*/
public function cacheDriver(): CacheService
{
return new CacheService();
}
/**
* 获取分页配置
*
* @param bool $isPage
* @param bool $isRelieve
*
* @return int[]
*/
public function getPageValue(bool $isPage = true, bool $isRelieve = true): array
{
// 获取请求实例
$request = request();
$page = $limit = 0;
if ($isPage) {
$page = $request->input(Config('database.page.pageKey', 'page') . '/d', 0);
$limit = $request->input(Config('database.page.limitKey', 'limit') . '/d', 0);
}
$limitMax = Config('database.page.limitMax');
$defaultLimit = Config('database.page.defaultLimit', 10);
if ($limit > $limitMax && $isRelieve) {
$limit = $limitMax;
}
return [(int)$page, (int)$limit, (int)$defaultLimit, (int)$limitMax];
}
/**
* 执行指定框架的事务
*
* @param callable $closure
* @param bool $isTran 是否启用事务
* @param string|null $connectionName
*
* @return mixed
* @throws \Throwable
*/
public function transaction(callable $closure, bool $isTran = true, ?string $connectionName = null): mixed
{
$connectionName = !empty($connectionName) ? $connectionName : (!empty(request()->dataSource) ? request()->dataSource : config('database.default', 'default'));
return $isTran ? LaravelDb::connection($connectionName)->transaction($closure) : $closure();
}
/**
* 密码hash加密
*
* @param string $password
*
* @return string
*/
public function passwordHash(string $password): string
{
return password_hash($password, PASSWORD_BCRYPT);
}
/**
* @param $name
* @param $arguments
*
* @return mixed
*/
public function __call($name, $arguments)
{
return call_user_func_array([$this->dao, $name], $arguments);
}
}
+316
View File
@@ -0,0 +1,316 @@
<?php
namespace core\base;
use core\exception\handler\ValidationException;
use Illuminate\Validation\Validator;
use think\helper\Str;
use Webman\Http\Request;
abstract class BaseValidate
{
/** @var bool 是否实例化时自动验证 */
public bool $authValidate = false;
/** @var array 验证规则 */
protected array $rules = [];
/** @var array 错误消息 */
protected array $message = [];
/** @var array 验证场景(场景名 => 需要验证的字段) */
protected array $scene = [];
/** @var array 当前场景需验证的字段 */
protected array $only = [];
/** @var array 验证通过的有效数据 */
protected array $data = [];
/** @var string|null 当前场景名 */
protected string|null $currentScene;
/** @var string|null 验证失败错误信息 */
protected ?string $error = null;
/** @var bool 是否抛出验证异常(默认是) */
protected bool $failException = true;
/** @var int 业务错误码 */
protected int $code = -1;
/** @var int HTTP响应状态码 */
protected int $statusCode = 200;
/**
* 构造函数:初始化场景与自动验证
*
* @param string|null $scene 验证场景名
*
* @throws ValidationException
*/
public function __construct(?string $scene = null)
{
// 设置场景
if ($scene) {
$this->scene($scene);
}
// 自动验证(若开启)
if ($this->authValidate) {
$this->check();
}
}
/**
* 魔术方法:代理Webman请求对象的方法(如input、method)
*
* @param string $name 方法名
* @param array $arguments 参数
*
* @return mixed
* @throws ValidationException
*/
public function __call(string $name, array $arguments)
{
$request = $this->request();
if (method_exists($request, $name)) {
return $request->{$name}(...$arguments);
}
throw new ValidationException(__('方法名不能为空', ['class' => get_class($request), 'method' => $name]));
}
/**
* 合并自定义错误消息
*
* @param array $message 自定义消息
*
* @return $this
*/
public function setMessage(array $message): self
{
$this->message = array_merge($this->message, $message);
return $this;
}
/**
* 核心验证方法:执行规则校验(保持原功能,优化内部逻辑)
*
* @param array $data 待验证数据(为空则从请求取)
* @param array $rules 自定义规则(为空则用类内规则)
*
* @return bool 验证通过返回true
* @throws ValidationException
* @throws \Exception
*/
public function check(array $data = [], array $rules = []): bool
{
// 1. 初始化场景(若有)
if ($this->currentScene) {
$this->loadSceneRules($this->currentScene);
}
// 2. 获取最终验证规则(支持方法和属性两种方式,属性优先)
if (empty($rules)) {
// 优先使用属性定义(如果属性不为空)
if (!empty($this->rules)) {
$finalRules = $this->rules;
}
// 其次使用方法定义(如果方法返回非空数组)
elseif (method_exists($this, 'rules')) {
$methodRules = $this->rules();
if (!empty($methodRules)) {
$finalRules = $methodRules;
} else {
$finalRules = [];
}
} else {
$finalRules = [];
}
} else {
$finalRules = $rules;
}
// 3. 获取错误消息(优先类内message方法)
if (empty($this->message) && method_exists($this, 'message')) {
$this->message = $this->message();
}
// 4. 处理场景字段过滤(only)
if (!empty($this->only)) {
$sceneRules = [];
$method = strtolower($this->request()->method());
$method = $method === 'post' ? 'post' : 'get';
foreach ($this->only as $field) {
if (isset($finalRules[$field])) {
$sceneRules[$field] = $finalRules[$field];
// 若数据为空,从请求中获取对应字段值
if (empty($data)) {
$data[$field] = $this->request()->{$method}($field);
}
}
}
$finalRules = $sceneRules;
} else {
// 若未指定only,从请求中获取全部数据(若数据为空)
if (empty($data)) {
$data = $this->request()->all();
}
}
// 5. 执行验证
$validator = validator($data, $finalRules, $this->message);
// 6. 处理验证结果
$this->currentScene = null;
if ($validator->fails()) {
return $this->handleValidationFailure($validator);
}
// 验证通过:保存有效数据
$this->data = $validator->validated();
return true;
}
/**
* 加载场景规则
*
* @param string $scene 场景名
*/
protected function loadSceneRules(string $scene): void
{
$this->only = [];
$sceneAction = Str::studly($scene);
// 优先调用sceneXxx方法(如sceneAdd)
if (method_exists($this, $sceneAction)) {
call_user_func([$this, $sceneAction]);
} // 其次读取scene数组配置
elseif (isset($this->scene[$scene])) {
$this->only = $this->scene[$scene];
}
}
/**
* 处理验证失败:修正异常抛出逻辑
*
* @param Validator $validator 验证器实例
*
* @return bool
* @throws \Exception
*/
protected function handleValidationFailure(Validator $validator): bool
{
$errorMsg = $validator->errors()->first();
if ($this->failException) {
// 抛出正确的ValidationException(传递状态码)
throw new ValidationException($errorMsg, [
'statusCode' => $this->statusCode,
'errorCode' => $this->code,
'headers' => [],
]
);
}
// 不抛异常:保存错误信息
$this->error = $errorMsg;
return false;
}
/**
* 执行验证并返回验证通过的数据
*
* @param array $data 待验证数据(为空则从请求取)
* @param array $rules 自定义规则(为空则用类内规则)
* @param array $message 自定义错误消息(为空则用类内消息)
* @param bool $returnAllData 是否返回全部数据(包括未验证字段)
*
* @return array 验证通过的数据
* @throws \Exception
*/
public function validate(array $data = [], array $rules = [], array $message = [], bool $returnAllData = false): array
{
// 保存原始消息以便验证后恢复
$originalMessage = $this->message;
try {
if (!empty($message)) {
$this->setMessage($message);
}
// 执行验证
$this->check($data, $rules);
// 根据参数决定返回验证数据还是全部数据
if ($returnAllData && !empty($data)) {
return array_merge($data, $this->data);
}
return $this->data;
} finally {
$this->message = $originalMessage;
}
}
/**
* 获取验证通过的有效数据
*
* @return array
*/
public function getData(): array
{
return $this->data;
}
/**
* 获取验证失败错误信息
*
* @return string|null
*/
public function getError(): ?string
{
return $this->error;
}
/**
* 设置当前验证场景
*
* @param string $scene 场景名
*
* @return $this
*/
public function scene(string $scene): self
{
$this->currentScene = $scene;
return $this;
}
/**
* 设置是否抛出验证异常
*
* @param bool $flag 是否抛出
*
* @return $this
*/
public function failException(bool $flag): self
{
$this->failException = $flag;
return $this;
}
/**
* 获取Webman请求对象
*
* @return Request
*/
protected function request(): Request
{
return request();
}
/**
* 定义验证规则(子类重写)
*
* @return array
*/
protected function rules(): array
{
return [];
}
}