-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Response.php
81 lines (68 loc) · 2.21 KB
/
Response.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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Kernel\Http;
use Hyperf\Context\ResponseContext;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\HttpMessage\Cookie\Cookie;
use Hyperf\HttpMessage\Exception\BadRequestHttpException;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;
use Swow\Psr7\Message\ResponsePlusInterface;
class Response
{
public const OK = 0;
protected ResponseInterface $response;
public function __construct(protected ContainerInterface $container)
{
$this->response = $container->get(ResponseInterface::class);
}
public function success(mixed $data = []): ResponsePlusInterface
{
return $this->response->json([
'code' => 0,
'data' => $data,
]);
}
public function fail(int $code, string $message = ''): ResponsePlusInterface
{
return $this->response->json([
'code' => $code,
'message' => $message,
]);
}
public function redirect($url, int $status = 302): ResponsePlusInterface
{
return $this->response()
->setHeader('Location', (string) $url)
->setStatus($status);
}
public function cookie(Cookie $cookie)
{
ResponseContext::set($this->response()->withCookie($cookie));
return $this;
}
public function handleException(HttpException $throwable): ResponsePlusInterface
{
if ($throwable instanceof BadRequestHttpException) {
di()->get(StdoutLoggerInterface::class)->warning('body: ' . $throwable->getRequest()?->getBody() . ' ' . $throwable);
}
return $this->response()
->addHeader('Server', 'Hyperf')
->setStatus($throwable->getStatusCode())
->setBody(new SwooleStream($throwable->getMessage()));
}
public function response(): ResponsePlusInterface
{
return ResponseContext::get();
}
}