Add ControllerTraits.

This commit is contained in:
Amast 2019-11-01 14:54:48 +08:00
parent 3b147cd3be
commit 58848bfecd
3 changed files with 1633 additions and 106 deletions

View File

@ -14,6 +14,6 @@
} }
}, },
"require": { "require": {
"illuminate/http": "^5.5" "laravel/lumen-framework": "5.6.*"
} }
} }

1695
composer.lock generated

File diff suppressed because it is too large Load Diff

View 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());
}
}