Add ControllerTraits.
This commit is contained in:
parent
3b147cd3be
commit
58848bfecd
|
@ -14,6 +14,6 @@
|
|||
}
|
||||
},
|
||||
"require": {
|
||||
"illuminate/http": "^5.5"
|
||||
"laravel/lumen-framework": "5.6.*"
|
||||
}
|
||||
}
|
||||
|
|
1695
composer.lock
generated
1695
composer.lock
generated
File diff suppressed because it is too large
Load Diff
42
src/Traits/ControllerTrait.php
Normal file
42
src/Traits/ControllerTrait.php
Normal file
|
@ -0,0 +1,42 @@
|
|||
<?php
|
||||
|
||||
namespace PdToolKit\Traits;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use PdToolKit\Exceptions\ApiException;
|
||||
use PdToolKit\Exceptions\ApiInvalidParamException;
|
||||
|
||||
trait ControllerTraits
|
||||
{
|
||||
public function success($data = null, $message = '请求成功')
|
||||
{
|
||||
return new JsonResponse([
|
||||
'code' => 0,
|
||||
'message' => $message,
|
||||
'data' => $data,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Request $request
|
||||
* @param array $rules
|
||||
* @param array $messages
|
||||
* @param array $customAttributes
|
||||
* @return array
|
||||
* @throws ApiException
|
||||
*/
|
||||
public function validateRequestParams(Request $request, array $rules, array $messages = [], array $customAttributes = [])
|
||||
{
|
||||
$validator = Validator::make($request->all(), $rules, $messages, $customAttributes);
|
||||
if ($validator->fails()) {
|
||||
throw new ApiInvalidParamException($validator->errors()->first());
|
||||
}
|
||||
|
||||
return $request->only(collect($rules)->keys()->map(function ($rule) {
|
||||
return Str::contains($rule, '.') ? explode('.', $rule)[0] : $rule;
|
||||
})->unique()->toArray());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user