优化代码

main
gzydong 2021-08-28 23:41:01 +08:00
parent 0460093e13
commit 08e04141e1
11 changed files with 283 additions and 127 deletions

View File

@ -37,11 +37,8 @@ class TestCommand extends HyperfCommand
{ {
$repository = di()->get(ExampleRepository::class); $repository = di()->get(ExampleRepository::class);
$repository->get_case(); $repository->case5();
// 3500
//$api = config('juhe_api.ip'); //$api = config('juhe_api.ip');
//$options = []; //$options = [];
//$client = di()->get(ClientFactory::class)->create($options); //$client = di()->get(ClientFactory::class)->create($options);

View File

@ -17,7 +17,7 @@ use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\JWTAuthMiddleware; use App\Middleware\JWTAuthMiddleware;
use App\Model\User; use App\Model\User;
use App\Support\SendEmailCode; use App\Support\SendEmailCode;
use App\Helper\Hash; use App\Helper\HashHelper;
use App\Service\UserService; use App\Service\UserService;
use App\Service\SmsCodeService; use App\Service\SmsCodeService;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@ -163,7 +163,7 @@ class UsersController extends CController
$userInfo = $this->userService->findById($this->uid(), ['id', 'password', 'mobile']); $userInfo = $this->userService->findById($this->uid(), ['id', 'password', 'mobile']);
// 验证密码是否正确 // 验证密码是否正确
if (!Hash::check($this->request->post('old_password'), $userInfo->password)) { if (!HashHelper::check($this->request->post('old_password'), $userInfo->password)) {
return $this->response->fail('旧密码验证失败!'); return $this->response->fail('旧密码验证失败!');
} }
@ -194,7 +194,7 @@ class UsersController extends CController
} }
$user_id = $this->uid(); $user_id = $this->uid();
if (!Hash::check($params['password'], User::where('id', $user_id)->value('password'))) { if (!HashHelper::check($params['password'], User::where('id', $user_id)->value('password'))) {
return $this->response->fail('账号密码验证失败!'); return $this->response->fail('账号密码验证失败!');
} }
@ -231,7 +231,7 @@ class UsersController extends CController
$uid = $this->uid(); $uid = $this->uid();
$user_password = User::where('id', $uid)->value('password'); $user_password = User::where('id', $uid)->value('password');
if (!Hash::check($params['password'], $user_password)) { if (!HashHelper::check($params['password'], $user_password)) {
return $this->response->fail('账号密码验证失败!'); return $this->response->fail('账号密码验证失败!');
} }

View File

@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1);
/** /**
* This is my open source code, please do not use it for commercial applications. * This is my open source code, please do not use it for commercial applications.
* For the full copyright and license information, * For the full copyright and license information,
@ -15,7 +16,7 @@ namespace App\Helper;
* *
* @package App\Helper * @package App\Helper
*/ */
class Hash class HashHelper
{ {
/** /**
* Hash the given value. * Hash the given value.
@ -23,7 +24,7 @@ class Hash
* @param string $value * @param string $value
* @return string * @return string
*/ */
public static function make(string $value) public static function make(string $value): string
{ {
return password_hash($value, PASSWORD_DEFAULT); return password_hash($value, PASSWORD_DEFAULT);
} }
@ -35,7 +36,7 @@ class Hash
* @param string $hashedValue * @param string $hashedValue
* @return bool * @return bool
*/ */
public static function check(string $value, string $hashedValue) public static function check(string $value, string $hashedValue): bool
{ {
return password_verify($value, $hashedValue); return password_verify($value, $hashedValue);
} }

View File

@ -35,10 +35,10 @@ use Exception;
* @method int increment(array $where, string $field, $amount = 1, array $extra = []) 按查询条件指定字段递增指定值(默认递增1) * @method int increment(array $where, string $field, $amount = 1, array $extra = []) 按查询条件指定字段递增指定值(默认递增1)
* @method int decrement(array $where, string $field, $amount = 1, array $extra = []) 按查询条件指定字段递减指定值(默认递减1) * @method int decrement(array $where, string $field, $amount = 1, array $extra = []) 按查询条件指定字段递减指定值(默认递减1)
* *
* @method string|int|null value(array $where, string $field) * @method string|int|null value(array $where, string $field) 按查询条件获取一行指定字段的数据
* @method Collection pluck(array $where, string $field) * @method Collection pluck(array $where, string $field) 按查询条件获取多行指定字段
* @method bool exists(array $where) 判断是否存在相关数据 * @method bool exists(array $where) 判断是否存在相关数据
* @method bool doesntExist() 判断是否不存在相关数据 * @method bool doesntExist(array $where) 判断是否不存在相关数据
* *
* @todo 待完善,请勿使用 * @todo 待完善,请勿使用
* *
@ -190,7 +190,7 @@ abstract class BaseRepository
* @param array $where * @param array $where
* @return Builder * @return Builder
*/ */
public function buildWhere(array $where = []): Builder final public function buildWhere(array $where = []): Builder
{ {
$model = $this->getNewModel(); $model = $this->getNewModel();
@ -223,7 +223,7 @@ abstract class BaseRepository
* @param bool $or * @param bool $or
* @throws Exception * @throws Exception
*/ */
private function bindWhere(Builder $model, array $where, $or = false) final private function bindWhere(Builder $model, array $where, $or = false)
{ {
foreach ($where as $field => $item) { foreach ($where as $field => $item) {
if ($field === 'or' || $field === 'and') { if ($field === 'or' || $field === 'and') {
@ -255,7 +255,7 @@ abstract class BaseRepository
* @param string $field * @param string $field
* @throws Exception * @throws Exception
*/ */
private function addNewWhere(Builder $model, array $where, $or = false, $field = '') final private function addNewWhere(Builder $model, array $where, $or = false, $field = '')
{ {
$method = $or ? 'orWhere' : 'where'; $method = $or ? 'orWhere' : 'where';
@ -271,7 +271,7 @@ abstract class BaseRepository
* @param array $values * @param array $values
* @return int * @return int
*/ */
public function update(array $where, array $values): int final public function update(array $where, array $values): int
{ {
return $this->buildWhere($where)->update($values); return $this->buildWhere($where)->update($values);
} }
@ -281,13 +281,20 @@ abstract class BaseRepository
* *
* @param array $where 查询条件 * @param array $where 查询条件
* @param string[] $fields 查询字段 * @param string[] $fields 查询字段
* @return Builder|Model|object|null * @param bool $is_array 是否返回数组格式
* @return Builder|Model|object|array|null
*/ */
public function first(array $where = [], array $fields = ['*']) public function first(array $where = [], array $fields = ['*'], bool $is_array = false)
{ {
$this->handleFindField($fields); $this->handleFindField($fields);
return $this->buildWhere($where)->first($fields); $data = $this->buildWhere($where)->first($fields);
if ($is_array) {
return $data ? $data->toArray() : [];
}
return $data;
} }
/** /**
@ -295,13 +302,18 @@ abstract class BaseRepository
* *
* @param array $where 查询条件 * @param array $where 查询条件
* @param string[] $fields 查询字段 * @param string[] $fields 查询字段
* @return array * @param bool $is_array 是否返回数组格式
* @return Collection|array
*/ */
public function get(array $where = [], array $fields = ['*']): array public function get(array $where = [], array $fields = ['*'], bool $is_array = false)
{ {
$this->handleFindField($fields); $this->handleFindField($fields);
return $this->buildWhere($where)->get($fields); $data = $this->buildWhere($where)->get($fields);
$is_array && $data = $data->toArray();
return $data;
} }
/** /**
@ -311,21 +323,23 @@ abstract class BaseRepository
* @param array $fields 查询字段 * @param array $fields 查询字段
* @param int $page 当前页 * @param int $page 当前页
* @param int $size 每页条数 * @param int $size 每页条数
* @return array|null * @return array
*/ */
public function paginate(array $where, $fields = ['*'], $page = 1, $size = 10): ?array public function paginate(array $where, $fields = ['*'], $page = 1, $size = 10): array
{ {
$this->handleFindField($fields); $this->handleFindField($fields);
$result = $this->buildWhere($where)->paginate($size, $fields, 'page', $page); $result = $this->buildWhere($where)->paginate($size, $fields, 'page', $page);
if (empty($result)) return null; if (empty($result)) {
return $this->getPagingRows([], 0, $page, $size);
}
return $this->getPagingRows(collect($result->items())->toArray(), $result->total(), $page, $size); return $this->getPagingRows(collect($result->items())->toArray(), $result->total(), $page, $size);
} }
/** /**
* 根据 where 条件打印 sql * 打印查询 sql
* *
* @param array $where * @param array $where
* @return string * @return string
@ -335,7 +349,6 @@ abstract class BaseRepository
return $this->buildWhere($where)->toSql(); return $this->buildWhere($where)->toSql();
} }
/** /**
* 添加排序信息 * 添加排序信息
* *
@ -456,11 +469,11 @@ abstract class BaseRepository
* 判断字符串是否被反引号包含 * 判断字符串是否被反引号包含
* *
* @param string $string * @param string $string
* @return false|int * @return bool
*/ */
private function isBackQuote(string $string) private function isBackQuote(string $string): bool
{ {
return preg_match("/^`.*?`$/", $string); return (bool)preg_match("/^`.*?`$/", $string);
} }
/** /**

View File

@ -3,8 +3,15 @@ declare(strict_types=1);
namespace App\Repository; namespace App\Repository;
use App\Helper\HashHelper;
use App\Model\User; use App\Model\User;
use Hyperf\Utils\Str;
/**
* Repository 使用案例
*
* @package App\Repository
*/
class ExampleRepository extends BaseRepository class ExampleRepository extends BaseRepository
{ {
public function __construct(User $model) public function __construct(User $model)
@ -12,32 +19,171 @@ class ExampleRepository extends BaseRepository
parent::__construct($model); parent::__construct($model);
} }
public function insert() // 自增自减案例 increment decrement
{
}
public function case1() public function case1()
{ {
$this->increment(['id' => 1017], 'is_robot', 4, [ // $this->increment(['id' => 1017], 'is_robot', 4, [
'updated_at' => date('Y-m-d H:i:s') // 'updated_at' => date('Y-m-d H:i:s')
]); // ]);
$this->decrement(['id:gt' => 1017], 'is_robot', 1, [ // $this->decrement(['id:gt' => 1017], 'is_robot', 1, [
'updated_at' => date('Y-m-d H:i:s') // 'updated_at' => date('Y-m-d H:i:s')
]); // ]);
} }
// 聚合查询相关案例 count, max, min, avg, sum
public function case2() public function case2()
{ {
$res = $this->pluck(['id:gt' => 1017, 'id:lt' => 1040], 'id'); // $this->count([
// 'id:gt' => 3000
// ]);
// $this->max([
// 'id:gt' => 3000
// ], 'id');
var_dump($this->doesntExist([ // $this->min([
'id' => 2054 // 'id:gt' => 3000
])); // ], 'id');
// $this->avg([
// 'id:gt' => 3000
// ], 'id');
// $this->sum([
// 'id:gt' => 3000
// ], 'id');
} }
// model value pluck exists doesntExist
public function case3()
{
// $this->value(['id' => 20540000], 'id');
// $this->pluck(['id:gt' => 1017, 'id:lt' => 1040], 'mobile');
// $this->exists(['id' => 2054]);
// $this->doesntExist(['id' => 2054]);
}
// model 原生方法
public function case4()
{
// 创建一条数据
// $this->create([
// 'mobile' => '135' . mt_rand(1000, 9999) . mt_rand(1000, 9999),
// 'nickname' => Str::random(10),
// 'password' => HashHelper::make('aa123456'),
// 'created_at' => date('Y-m-d H:i:s'),
// 'updated_at' => date('Y-m-d H:i:s'),
// ]);
// 批量创建数据
// $this->insert([
// [
// 'mobile' => '135' . mt_rand(1000, 9999) . mt_rand(1000, 9999),
// 'nickname' => Str::random(10),
// 'password' => HashHelper::make('aa123456'),
// 'created_at' => date('Y-m-d H:i:s'),
// 'updated_at' => date('Y-m-d H:i:s'),
// ],
// [
// 'mobile' => '135' . mt_rand(1000, 9999) . mt_rand(1000, 9999),
// 'nickname' => Str::random(10),
// 'password' => HashHelper::make('aa123456'),
// 'created_at' => date('Y-m-d H:i:s'),
// 'updated_at' => date('Y-m-d H:i:s'),
// ],
// ]);
// 创建一条数据并返回主键ID
// $user_id = $this->insertGetId([
// 'mobile' => '135' . mt_rand(1000, 9999) . mt_rand(1000, 9999),
// 'nickname' => Str::random(10),
// 'password' => HashHelper::make('aa123456'),
// 'created_at' => date('Y-m-d H:i:s'),
// 'updated_at' => date('Y-m-d H:i:s'),
// ]);
// 查询一条数据不存在即新增一条数据
// $user = $this->firstOrCreate([
// 'mobile' => 18698272054,
// ], [
// 'mobile' => 18698272054,
// 'nickname' => Str::random(10),
// 'password' => HashHelper::make('aa123456'),
// 'created_at' => date('Y-m-d H:i:s'),
// 'updated_at' => date('Y-m-d H:i:s'),
// ]);
// 更新一条数据不存在就创建
// $this->updateOrCreate([
// 'mobile' => 18698272054,
// ], [
// 'mobile' => 18698272054,
// 'nickname' => Str::random(10),
// 'password' => HashHelper::make('aa123456'),
// 'created_at' => date('Y-m-d H:i:s'),
// 'updated_at' => date('Y-m-d H:i:s'),
// ]);
// 根据主键ID查询数据
// $this->find(2054, ['id', 'mobile']);
// 主键查询没有就抛出错误
// $this->findOrFail(20540000, ['id', 'mobile']);
// 根据条件更新数据
// $this->update([
// 'id' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
// ], [
// 'gender' => 2,
// 'updated_at' => date('Y-m-d H:i:s'),
// ]);
}
public function case5()
{
// 根据条件获取满足条件的第一条数据
// $result = $this->first([
// 'id' => 2054,
// ], ['*'], true);
// 根据条件获取所有满足条件的数据
// $this->get([
// 'id' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
// 'gender' => 2
// ], ['id', 'mobile'],true);
// 分页获取数据
// $this->paginate([
// 'id:gt' => 20540000,
// 'gender' => 2
// ], ['*'], 1, 15);
// 打印查询 sql 语句
// $this->toSql([
// 'id' => 2054,
// 'or' => [
// 'gender' => [1, 2, 3],
// [
// 'id:lt' => 2011,
// 'mobile' => 2066,
// ],
// [
// 'id:gt' => 1344,
// 'mobile' => 1233,
// 'or' => [
// 'nickname' => "1111",
// 'email' => '22222'
// ]
// ],
// ]
// ]);
}
// where 条件查询案例
public function where_case() public function where_case()
{ {
$where = [ $where = [
@ -67,52 +213,4 @@ class ExampleRepository extends BaseRepository
] ]
]; ];
} }
// 聚合查询相关案例 count, max, min, avg, sum
public function aggregation_case()
{
var_dump('count : ' . $this->count([
'id:gt' => 3000
]));
var_dump('max : ' . $this->max([
'id:gt' => 3000
], 'id'));
var_dump('min : ' . $this->min([
'id:gt' => 3000
], 'id'));
var_dump('avg : ' . $this->avg([
'id:gt' => 3000
], 'id'));
var_dump('sum : ' . $this->sum([
'id:gt' => 3000
], 'id'));
}
// get 查询案例
public function get_case()
{
// $result = $this->first([
// // 'id' => 2054,
// 'or' => [
// 'gender' => [1, 2, 3],
// [
// 'id:lt' => 2011,
// 'mobile' => 2066,
// ],
// [
// 'id:gt' => 1344,
// 'mobile' => 1233,
// 'or' => [
// 'nickname' => "1111",
// 'email' => '22222'
// ]
// ],
// ]
// ]);
}
} }

View File

@ -2,7 +2,7 @@
namespace App\Service; namespace App\Service;
use App\Helper\Hash; use App\Helper\HashHelper;
use App\Model\Robot; use App\Model\Robot;
use App\Model\User; use App\Model\User;
use Hyperf\DbConnection\Db; use Hyperf\DbConnection\Db;
@ -20,7 +20,7 @@ class RobotService
try { try {
$user = User::create([ $user = User::create([
'mobile' => '100' . mt_rand(1000, 9999) . mt_rand(1000, 9999), 'mobile' => '100' . mt_rand(1000, 9999) . mt_rand(1000, 9999),
'password' => Hash::make(Str::random(10)), 'password' => HashHelper::make(Str::random(10)),
'is_robot' => 1 'is_robot' => 1
]); ]);

View File

@ -2,7 +2,7 @@
namespace App\Service; namespace App\Service;
use App\Helper\Hash; use App\Helper\HashHelper;
use App\Model\User; use App\Model\User;
use App\Model\Article\ArticleClass; use App\Model\Article\ArticleClass;
use App\Model\UsersFriend; use App\Model\UsersFriend;
@ -53,7 +53,7 @@ class UserService extends BaseService
{ {
Db::beginTransaction(); Db::beginTransaction();
try { try {
$data['password'] = Hash::make($data['password']); $data['password'] = HashHelper::make($data['password']);
$data['created_at'] = date('Y-m-d H:i:s'); $data['created_at'] = date('Y-m-d H:i:s');
$data['updated_at'] = date('Y-m-d H:i:s'); $data['updated_at'] = date('Y-m-d H:i:s');
@ -86,7 +86,7 @@ class UserService extends BaseService
*/ */
public function resetPassword(string $mobile, string $password) public function resetPassword(string $mobile, string $password)
{ {
return (bool)User::where('mobile', $mobile)->update(['password' => Hash::make($password)]); return (bool)User::where('mobile', $mobile)->update(['password' => HashHelper::make($password)]);
} }
/** /**

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace HyperfTest\Cases\Controller\Api;
use HyperfTest\HttpTestCase;
/**
* 授权控制器单元测试
*
* Class AuthControllerTest
* @package HyperfTest\Cases\Controller\Api
*/
class AuthControllerTest extends HttpTestCase
{
public function testLogin()
{
$response = $this->post('/api/v1/auth/login', [
'mobile' => '231231',
'password' => 'asdfasf',
'platform' => 'sdfas',
]);
$this->assertArrayHasKey('code', $response);
}
}

View File

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace HyperfTest\Cases\Helper;
use App\Helper\RegularHelper;
use HyperfTest\HttpTestCase;
class RegularHelperTest extends HttpTestCase
{
public function testPhoneTest()
{
$this->assertTrue(!RegularHelper::verify('phone', ''), '手机号验证失败1!');
$this->assertTrue(!RegularHelper::verify('phone', ' '), '手机号验证失败2!');
$this->assertTrue(!RegularHelper::verify('phone', 'test'), '手机号验证失败3!');
$this->assertTrue(!RegularHelper::verify('phone', '18720431234 '), '手机号验证失败4!');
$this->assertTrue(!RegularHelper::verify('phone', ' 18720431234'), '手机号验证失败5!');
$this->assertTrue(!RegularHelper::verify('phone', ' 18720431234 '), '手机号验证失败6!');
$this->assertTrue(!RegularHelper::verify('phone', '-18720431234 '), '手机号验证失败7!');
$this->assertTrue(!RegularHelper::verify('phone', '28720431234 '), '手机号验证失败8!');
$this->assertTrue(!RegularHelper::verify('phone', '18q20431234'), '手机号验证失败9!');
$this->assertTrue(RegularHelper::verify('phone', '18720431234'), '手机号验证失败10!');
}
public function testIdsTest()
{
$this->assertTrue(!RegularHelper::verify('ids', ''), 'ids 格式验证失败1!');
$this->assertTrue(!RegularHelper::verify('ids', ' '), 'ids 格式验证失败2!');
$this->assertTrue(!RegularHelper::verify('ids', ' 1234'), 'ids 格式验证失败3!');
$this->assertTrue(!RegularHelper::verify('ids', '1234 '), 'ids 格式验证失败4!');
$this->assertTrue(!RegularHelper::verify('ids', ' 1234 '), 'ids 格式验证失败5!');
$this->assertTrue(!RegularHelper::verify('ids', 'test'), 'ids 格式验证失败6!');
$this->assertTrue(!RegularHelper::verify('ids', 'test,tes'), 'ids 格式验证失败7!');
$this->assertTrue(!RegularHelper::verify('ids', '123,tes'), 'ids 格式验证失败8!');
$this->assertTrue(!RegularHelper::verify('ids', '123,1213,tes'), 'ids 格式验证失败9!');
$this->assertTrue(!RegularHelper::verify('ids', '-123,1213'), 'ids 格式验证失败10!');
$this->assertTrue(!RegularHelper::verify('ids', '1w23,1213'), 'ids 格式验证失败11!');
$this->assertTrue(!RegularHelper::verify('ids', '123,1213,'), 'ids 格式验证失败12!');
$this->assertTrue(!RegularHelper::verify('ids', '123,1213,,'), 'ids 格式验证失败13!');
$this->assertTrue(!RegularHelper::verify('ids', '123,1213,,234'), 'ids 格式验证失败14!');
$this->assertTrue(RegularHelper::verify('ids', '123,1213'), 'ids 格式验证失败15!');
}
}

View File

@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace HyperfTest\Cases;
use App\Repository\ExampleRepository;
use HyperfTest\HttpTestCase;
class RepositoryTest extends HttpTestCase
{
public function testRepositoryExample()
{
$repository = di()->get(ExampleRepository::class);
$sql1 = $repository->toSql([
'id' => [1, 2, 3, 4]
]);
$this->assertEquals($sql1,"select * from `lar_users` where `id` in (?, ?, ?, ?)");
}
}

View File

@ -9,6 +9,7 @@ declare(strict_types=1);
* @contact group@hyperf.io * @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/ */
namespace HyperfTest; namespace HyperfTest;
use Hyperf\Testing\Client; use Hyperf\Testing\Client;