-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResponseServiceProvider.php
92 lines (83 loc) · 2.65 KB
/
ResponseServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
namespace Mesak\LaravelApiResponse;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;
use Mesak\LaravelApiResponse\Exceptions\BadRequestException;
use Mesak\LaravelApiResponse\Exceptions\BaseException;
class ResponseServiceProvider extends ServiceProvider
{
static $responseClass = \Mesak\LaravelApiResponse\Http\ApiResponse::class;
static $responseSchema = \Mesak\LaravelApiResponse\Http\ApiResponseSchema::class;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../config/api-response.php' => config_path('api-response.php'),
], 'api-response');
}
$this->defaultResponseConfig();
$this->registerResponseMacro();
$this->registerErrorHandling();
}
/**
* Register any application services.
*
* @return void
*/
public function register(): void
{
//註冊 config 檔案
$this->mergeConfigFrom(__DIR__ . '/../config/api-response.php', 'api-response');
}
/**
* Register default response config
*
* @return void
*/
public function defaultResponseConfig(): void
{
static::$responseClass = config('api-response.response', static::$responseClass);
static::$responseSchema = config('api-response.schema', static::$responseSchema);
}
/**
* Register the event listener for the event.
*
* @return void
*/
public function registerResponseMacro(): void
{
Response::macro('success', function ($result = null, $statusCode = 200) {
return tap(new ResponseServiceProvider::$responseClass($result), function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
});
});
Response::macro('error', function ($exception = null, $statusCode = 400) {
if ($exception instanceof BaseException) {
$statusCode = $exception->getStatusCode();
} else if ($exception instanceof \Throwable) {
$statusCode = property_exists($exception, 'status') ? $exception->status : $statusCode;
} else {
$exception = new BadRequestException((string)$exception);
}
return tap(new ResponseServiceProvider::$responseClass($exception), function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
});
});
}
/**
* Register Error Handling api render
*
* @return void
*/
public function registerErrorHandling(): void
{
$this->app->bind(\Illuminate\Contracts\Debug\ExceptionHandler::class, function ($app) {
return new Exceptions\Handler($app['Illuminate\Contracts\Container\Container']);
});
}
}