diff --git a/src/ResponseTrait.php b/src/ResponseTrait.php deleted file mode 100644 index 49623da..0000000 --- a/src/ResponseTrait.php +++ /dev/null @@ -1,84 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Jiannei\Response\Laravel; - -use ErrorException; -use Illuminate\Http\Exceptions\HttpResponseException; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Config; -use Throwable; - -/** - * Trait Helpers. - * - * @property Response $response - */ -trait ResponseTrait -{ - public function __get($key) - { - $callable = [ - 'response', - ]; - - if (in_array($key, $callable, true) && method_exists($this, $key)) { - return $this->$key(); - } - - throw new ErrorException('Undefined property '.get_class($this).'::'.$key); - } - - /** - * @return Response - */ - protected function response(): Response - { - return app(Response::class); - } - - /** - * Custom Normal Exception response. - * - * @param $request - * @param Throwable $e - */ - protected function prepareJsonResponse($request, Throwable $e) - { - // 要求请求头 header 中包含 /json 或 +json,如:Accept:application/json - // 或者是 ajax 请求,header 中包含 X-Requested-With:XMLHttpRequest; - return $this->response->fail( - '', - $this->isHttpException($e) ? $e->getStatusCode() : 500, - config('app.debug', false) ? $this->convertExceptionToArray($e) : [], - $this->isHttpException($e) ? $e->getHeaders() : [], - JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES - ); - } - - /** - * Custom Failed Validation Response. - * - * @param Request $request - * @param array $errors - * - * @return mixed - * @throws HttpResponseException - */ - protected function buildFailedValidationResponse(Request $request, array $errors) - { - if (isset(static::$responseBuilder)) { - return (static::$responseBuilder)($request, $errors); - } - - return $this->response->fail('', Config::get('response.validation_error_code', 422), $errors); - } -} diff --git a/src/Support/Traits/ExceptionTrait.php b/src/Support/Traits/ExceptionTrait.php index 328df38..fa8517b 100644 --- a/src/Support/Traits/ExceptionTrait.php +++ b/src/Support/Traits/ExceptionTrait.php @@ -12,8 +12,10 @@ namespace Jiannei\Response\Laravel\Support\Traits; use Illuminate\Http\Exceptions\HttpResponseException; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; +use Illuminate\Validation\ValidationException; use Jiannei\Response\Laravel\Response; use Throwable; @@ -24,6 +26,7 @@ trait ExceptionTrait * * @param $request * @param Throwable $e + * @return JsonResponse */ protected function prepareJsonResponse($request, Throwable $e) { @@ -39,7 +42,7 @@ protected function prepareJsonResponse($request, Throwable $e) } /** - * Custom Failed Validation Response. + * Custom Failed Validation Response for Lumen. * * @param Request $request * @param array $errors @@ -55,4 +58,16 @@ protected function buildFailedValidationResponse(Request $request, array $errors return app(Response::class)->fail('', Config::get('response.validation_error_code', 422), $errors); } + + /** + * Custom Failed Validation Response for Laravel. + * + * @param Request $request + * @param ValidationException $exception + * @return JsonResponse + */ + protected function invalidJson($request, ValidationException $exception) + { + return app(Response::class)->fail('', Config::get('response.validation_error_code', $exception->status), $exception->errors()); + } } diff --git a/tests/FailTest.php b/tests/FailTest.php index cd532a4..1647bb3 100644 --- a/tests/FailTest.php +++ b/tests/FailTest.php @@ -13,7 +13,8 @@ use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Support\Arr; -use Jiannei\Response\Laravel\ResponseTrait; +use Jiannei\Response\Laravel\Support\Facades\Response; +use Jiannei\Response\Laravel\Support\Traits\ExceptionTrait; use Jiannei\Response\Laravel\Tests\Repositories\Enums\ResponseCodeEnum; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; @@ -21,14 +22,14 @@ class FailTest extends TestCase { - use ResponseTrait; + use ExceptionTrait; public function testFail() { try { // 方式一:Controller 中直接返回失败,这里本质上是通过 JsonResponse 是抛出了一个 HttpResponseException,需要捕获异常后才能拿到真实响应 // 不需要在前面加 return - $this->response()->fail(); + Response::fail(); } catch (HttpResponseException $e) { $response = $e->getResponse(); @@ -52,7 +53,7 @@ public function testFailWithMessage() { try { // 方式二:Controller 中返回指定的 Message - $this->response()->fail('操作失败'); + Response::fail('操作失败'); } catch (HttpResponseException $e) { $response = $e->getResponse(); @@ -73,7 +74,7 @@ public function testFailWithCustomCodeAndMessage() { try { // 方式三:Controller 中返回预先定义的业务错误码和错误描述 - $this->response()->fail('', ResponseCodeEnum::SERVICE_LOGIN_ERROR); + Response::fail('', ResponseCodeEnum::SERVICE_LOGIN_ERROR); } catch (HttpResponseException $e) { $response = $e->getResponse(); @@ -96,7 +97,7 @@ public function testFailOutController() // 方式四:Controller 中默认引入了 ResponseTrait;在没有引入 ResponseTrait 的地方可以直接使用 abort 来抛出 HttpException 异常然后返回错误信息 abort(ResponseCodeEnum::SYSTEM_ERROR); } catch (HttpException $httpException) { - $response = $this->response()->fail( + $response = Response::fail( '', $this->isHttpException($httpException) ? $httpException->getStatusCode() : 500, config('app.debug', false) ? $this->convertExceptionToArray($httpException) : [], diff --git a/tests/SuccessTest.php b/tests/SuccessTest.php index b9ee6bb..3d52652 100644 --- a/tests/SuccessTest.php +++ b/tests/SuccessTest.php @@ -13,7 +13,7 @@ use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\RefreshDatabase; -use Jiannei\Response\Laravel\ResponseTrait; +use Jiannei\Response\Laravel\Support\Facades\Response; use Jiannei\Response\Laravel\Tests\Repositories\Enums\ResponseCodeEnum; use Jiannei\Response\Laravel\Tests\Repositories\Models\User; use Jiannei\Response\Laravel\Tests\Repositories\Resources\UserCollection; @@ -21,12 +21,12 @@ class SuccessTest extends TestCase { - use ResponseTrait, DatabaseMigrations,RefreshDatabase; + use DatabaseMigrations, RefreshDatabase; public function testSuccess() { // 方式一:直接返回响应成功 - $response = $this->response()->success(); // 注意:这里必须使用 this->response() 函数方式调用,因为 MakesHttpRequests 中有 response 属性 + $response = Response::success(); // 注意:这里必须使用 this->response() 函数方式调用,因为 MakesHttpRequests 中有 response 属性 $this->assertEquals(200, $response->status()); @@ -43,7 +43,7 @@ public function testSuccess() public function testCreated() { // 方式二:返回创建成功 - $response = $this->response()->created(); + $response = Response::created(); $this->assertEquals(201, $response->status()); @@ -60,7 +60,7 @@ public function testCreated() public function testAccepted() { // 方式三:返回接收成功 - $response = $this->response()->accepted(); + $response = Response::accepted(); $this->assertEquals(202, $response->status()); @@ -77,7 +77,7 @@ public function testAccepted() public function testNoContent() { // 方式四:返回空内容;创建成功或删除成功等场景 - $response = $this->response()->noContent(); + $response = Response::noContent(); $this->assertEquals(204, $response->status()); @@ -99,7 +99,7 @@ public function testSuccessWithArrayData() 'name' => 'Jiannei', 'email' => 'longjian.huang@foxmail.com', ]; - $response = $this->response()->success($data); + $response = Response::success($data); $this->assertEquals(200, $response->status()); @@ -117,7 +117,7 @@ public function testSuccessWithResourceData() { // 方式六:返回 Api resource $user = User::factory()->make(); - $response = $this->response()->success(new UserResource($user)); + $response = Response::success(new UserResource($user)); $this->assertEquals(200, $response->status()); $expectedJson = json_encode([ @@ -138,7 +138,7 @@ public function testSuccessWithCollectionData() { // 方式七:返回 Api collection $users = User::factory()->count(10)->make(); - $response = $this->response()->success(new UserCollection($users)); + $response = Response::success(new UserCollection($users)); $this->assertEquals(200, $response->status()); @@ -164,7 +164,7 @@ public function testSuccessWithPaginatedData() User::factory()->count(20)->create(); $users = User::paginate(); - $response = $this->response()->success(new UserCollection($users)); + $response = Response::success(new UserCollection($users)); $this->assertEquals(200, $response->status()); @@ -205,7 +205,7 @@ public function testSuccessWithPaginatedData() public function testSuccessWithMessage() { // 方式九:返回指定的 Message - $response = $this->response()->success(null, '成功'); + $response = Response::success(null, '成功'); $expectedJson = json_encode([ 'status' => 'success', @@ -221,7 +221,7 @@ public function testSuccessWithMessage() public function testSuccessWithCustomMessageAndCode() { // 方式十:根据预定义的「业务码」和「对应的描述信息」返回 - $response = $this->response()->success(null, '', ResponseCodeEnum::SERVICE_LOGIN_SUCCESS); + $response = Response::success(null, '', ResponseCodeEnum::SERVICE_LOGIN_SUCCESS); $expectedJson = json_encode([ 'status' => 'success',