PHP code example of jeckleee / tools
1. Go to this page and download the library: Download jeckleee/tools library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jeckleee / tools example snippets
// 配置文件: config/plugin/jeckleee/tools/app.php
return [
'enable' => true,
// 定义验证失败以后抛出的异常, webman 框架建议使用 BusinessException::class
'exception' => Exception::class,
// 定义验证失败的错误码
'exception_code' => 500,
// 验证失败错误如何返回(immediate,collective)
// immediate: 立即返回, 只要验证出现错误, 立即抛出当前错误字段的异常信息, 不再验证剩余的字段
// collective: 集中返回, 验证全部字段, 收集所有异常, 验证结束后在异常 $e->getMessage() 中返回错误字段的列表, json 字符串形式
'error_return_mode' => 'immediate', // 只支持 immediate 和 collective,其他值会抛异常
];
use Jeckleee\Tools\Validator as V;
$post = [
'name' => 'jeckleee',
'password' => '123456',
'password_confirm' => '123456',
'email' => '[email protected] ',
'age' => 18,
'avatar' => $_FILES['avatar'] ?? null
];
// 验证一组数据
$data = V::array($post, [
// 基础验证
V::field('name')->受 int 类型)
V::field('age')->ield('email_code')->
// 验证一个字段
$age = V::one(
$post,
V::field('age')->时只验证第一条规则
$age = V::one($post, [
V::field('age')->
// 验证变量是否正确, 返回 (bool) TRUE or FALSE
$phone = '123456789';
if (V::var($phone)->isMobile()->check()) {
echo '手机号码正确';
} else {
echo '手机号码不正确';
}
// 自定义验证方法, 只有回调方法返回 (bool) true 时, 才验证通过
$data = V::one(
$post,
V::field('age')->fun(function ($value) {
return $value >= 18;
})->verify('年龄不能小于18岁')
);
$data = V::array($input, [
// 当邮箱存在时,验证码必填
V::field('email')->�填'),
// 当邮箱不存在时,手机号必填
V::field('phone')->
$data = V::array($input, [
// 密码确认
V::field('password')->不一致'),
// 新旧密码不能相同
V::field('new_password')->
// 兼容多种文件上传格式
$data = V::array($request->all(), [
// 原始 $_FILES 格式
V::field('avatar')->isFile($_FILES, ['jpg', 'png', 'gif'], 2*1024)->verify('头像格式或大小不正确'),
// Laravel 框架
V::field('document')->isFile($request->file(), ['pdf', 'doc', 'docx'], 10*1024)->verify('文档格式或大小不正确'),
// Webman 框架
V::field('image')->isFile($request->file(), ['jpg', 'png'], 1024)->verify('图片格式或大小不正确'),
]);
// Laravel 使用示例
public function upload(Request $request)
{
$data = V::array($request->all(), [
V::field('avatar')->isFile($request->file(), ['jpg', 'png'], 2*1024)->verify('头像格式或大小不正确'),
V::field('document')->isFile($request->file(), ['pdf'], 5*1024)->verify('文档格式或大小不正确'),
]);
// ....处理文件上传
}
// Webman 使用示例
public function upload(Request $request)
{
V::array($request->all(), [
V::field('avatar')->isFile($request->file(), ['jpg', 'png'], 2*1024)->verify('头像格式或大小不正确'),
V::field('document')->isFile($request->file(), ['pdf'], 5*1024)->verify('文档格式或大小不正确'),
]);
// ...自己处理文件上传
}
// 校验并转为数组
$data = V::array($post, [
V::field('data')->isJson(true)->verify('数据格式错误');
]);
// 校验Base64编码字符串
$data = V::array($post, [
V::field('image_data')->isBase64()->verify('图片数据格式错误');
]);
// 校验并限制 2 位小数
$data = V::array($post, [
V::field('price')->isFloat(2)->verify('价格格式错误');
]);
$data = V::array($post, [
V::field('age')->cmpNumber('>', 18)->verify('年龄必须大于18岁');
]);
$data = V::array($post, [
V::field('a')->isInt()->verify(); // 接受 int 或整数字符串(如 "123")
V::field('b')->isNumber()->verify(); // 接受 int/float/字符串数字
V::field('c')->isFloat(2)->verify(); // 浮点数且最多2位小数
]);
// isFile对文件校验时,没有返回值
V::array($post, [
// 校验通过无返回,失败则抛出异常
V::field('avatar')->isFile($_FILES, ['jpg'], 1024)->verify();
]);
// ...自己处理文件上传
$avatar=$request->file('avatar')->store('uploads/avatar/avatar');
$data = V::array($post, [
V::field('score')->fun(function($val){ return $val > 60; })->verify('分数必须大于60');
]);
$data = V::array($post, [
// 转小写
V::field('username')->strLowercase()->verify('用户名转小写失败');
// 转大写
V::field('code')->strUppercase()->verify('验证码转大写失败');
]);
// 1. 使用配置文件中定义异常和错误码
$data = V::array($post, [
V::field('name')-> [
V::field('name')->post, [
V::field('name')->
// immediate 模式:立即返回第一个错误
$data = V::array($post, $rules, null, null, 'immediate');
// collective 模式:收集所有错误后返回
$data = V::array($post, $rules, null, null, 'collective');
use Jeckleee\Tools\Validator as V;
use support\Request;
class UserController extends BaseController
{
public function register(Request $request): \support\Response
{
try {
$input = V::array($request->all(), [
// 基础信息验证
V::field('username')->fy('密码长度6-20位'),
V::field('password_confirm')->same('password')->verify('两次密码不一致'),
// 个人信息验证
V::field('age')->ifExisted()->isInt()->betweenNumber(1, 120)->verify('年龄格式错误'),
V::field('avatar')->ifExisted()->isFile($request->file(), ['jpg', 'png'], 1024)->verify('头像格式或大小错误'),
// 自定义验证
V::field('invite_code')->fun(function($val) {
return strlen($val) === 6 && ctype_alnum($val);
})->verify('邀请码格式错误'),
]);
//需要自己处理处理头像的上传...todo
$avatar = $request->file('avatar')->store('uploads/avatar/avatar');
//将头像地址增加到$input数据中
$input['avatar']=$avatar;
// 创建用户
$user = User::create($input);
return json(['code' => 200, 'msg' => '注册成功', 'data' => $user]);
} catch (BusinessException $exception) {
return json([
'code' => $exception->getCode() ?: 300,
'msg' => $exception->getMessage(),
'status' => 'error'
]);
}
}
}
use Jeckleee\Tools\Tool;
// 二维数组根据字段绑定到唯一键
$users = Tool::arrayBindKey($userList, 'id');
// $users = [1=>['id'=>1,'name'=>'A'], 2=>['id'=>2,'name'=>'B']]
// 二维数组根据字段排序
$sortedUsers = Tool::arraySequence($userList, 'age', 'SORT_DESC');
// $sortedUsers = [['id'=>2,'age'=>30], ['id'=>1,'age'=>20]]
// 生成树形结构
$tree = Tool::generateTree($list, 'id', 'parent_id', 'children');
// 生成随机字符串
$randomStr = Tool::getRandomString(16);
// 计算日期差
$days = Tool::diffDateDays('2024-01-01', '2024-01-10');
// 字符串脱敏
$masked = Tool::maskSecret('13812345678', 3, 4);
// 生成 UUID
$uuid = Tool::generateUUID();
// 安全 UUID v4 / 时间有序 UUID v7
$uuid4 = Tool::uuidV4();
$uuid7 = Tool::uuidV7();
// 安全随机数
$ri = Tool::randomInt(1, 100);
$rf = Tool::randomFloat(0.1, 9.9);
// 人性化时间差与字节显示
$diff = Tool::humanizeDiff('2025-01-01 12:00:00'); // 如:"3天前"
$size = Tool::humanBytes(1234567); // 1.18 MB
// 稳定排序构建查询串(RFC3986)
$query = Tool::buildQuery(['b'=>2, 'a'=>['y'=>2, 'x'=>1]]); // a%5Bx%5D=1&a%5By%5D=2&b=2
// 分组、去重、分块、二分
$groups = Tool::arrayGroupBy([
['id'=>1,'cat'=>'A'],
['id'=>2,'cat'=>'B'],
['id'=>3,'cat'=>'A'],
], 'cat');
// [ 'A' => [...], 'B' => [...] ]
$uniq = Tool::arrayUniqueBy([
['id'=>1,'name'=>'x'],
['id'=>1,'name'=>'x2'],
['id'=>2,'name'=>'y'],
], 'id'); // 稳定去重,保留首次出现
$chunks = Tool::arrayChunkFixed([1,2,3,4,5], 2); // [[1,2],[3,4],[5]]
[$evens, $odds] = Tool::arrayPartition([1,2,3,4], fn($n)=> $n%2===0);
// 树相关:扁平化、查找、路径
$flat = Tool::flattenTree($tree, 'children');
$found = Tool::findInTree($tree, fn($node)=> ($node['id']??null) === 5);
$pathInTree = Tool::pathInTree($tree, 5, 'id', 'children'); // 从根到目标的路径数组
// 从扁平数组追溯路径
$flatNodes = [
['id'=>1,'parent_id'=>null],
['id'=>2,'parent_id'=>1],
['id'=>5,'parent_id'=>2],
];
$path = Tool::pathInFlat($flatNodes, 5, 'id', 'parent_id');
// 重试工具
$result = Tool::retry(function(int $attempt){
if ($attempt < 3) throw new Exception('try again');
return 'ok';
}, times: 5, sleepMs: 100);
$arr = [['id'=>1,'name'=>'A'], ['id'=>2,'name'=>'B']];
$res = Tool::arrayBindKey($arr, 'id');
// [1=>['id'=>1,'name'=>'A'], 2=>['id'=>2,'name'=>'B']]
$arr = [['id'=>1,'age'=>20], ['id'=>2,'age'=>18]];
$res = Tool::arraySequence($arr, 'age', 'SORT_ASC');
// [['id'=>2,'age'=>18], ['id'=>1,'age'=>20]]