Skip to content

Commit

Permalink
feat: 适配 laravel
Browse files Browse the repository at this point in the history
  • Loading branch information
jiannei committed Dec 16, 2020
1 parent c7cc89a commit 84fcd6b
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 103 deletions.
84 changes: 0 additions & 84 deletions src/ResponseTrait.php

This file was deleted.

17 changes: 16 additions & 1 deletion src/Support/Traits/ExceptionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -24,6 +26,7 @@ trait ExceptionTrait
*
* @param $request
* @param Throwable $e
* @return JsonResponse
*/
protected function prepareJsonResponse($request, Throwable $e)
{
Expand All @@ -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
Expand All @@ -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());
}
}
13 changes: 7 additions & 6 deletions tests/FailTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,23 @@

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;
use Throwable;

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

Expand All @@ -52,7 +53,7 @@ public function testFailWithMessage()
{
try {
// 方式二:Controller 中返回指定的 Message
$this->response()->fail('操作失败');
Response::fail('操作失败');
} catch (HttpResponseException $e) {
$response = $e->getResponse();

Expand All @@ -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();

Expand All @@ -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) : [],
Expand Down
24 changes: 12 additions & 12 deletions tests/SuccessTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@

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;
use Jiannei\Response\Laravel\Tests\Repositories\Resources\UserResource;

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

Expand All @@ -43,7 +43,7 @@ public function testSuccess()
public function testCreated()
{
// 方式二:返回创建成功
$response = $this->response()->created();
$response = Response::created();

$this->assertEquals(201, $response->status());

Expand All @@ -60,7 +60,7 @@ public function testCreated()
public function testAccepted()
{
// 方式三:返回接收成功
$response = $this->response()->accepted();
$response = Response::accepted();

$this->assertEquals(202, $response->status());

Expand All @@ -77,7 +77,7 @@ public function testAccepted()
public function testNoContent()
{
// 方式四:返回空内容;创建成功或删除成功等场景
$response = $this->response()->noContent();
$response = Response::noContent();

$this->assertEquals(204, $response->status());

Expand All @@ -99,7 +99,7 @@ public function testSuccessWithArrayData()
'name' => 'Jiannei',
'email' => '[email protected]',
];
$response = $this->response()->success($data);
$response = Response::success($data);

$this->assertEquals(200, $response->status());

Expand All @@ -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([
Expand All @@ -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());

Expand All @@ -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());

Expand Down Expand Up @@ -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',
Expand All @@ -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',
Expand Down

0 comments on commit 84fcd6b

Please sign in to comment.