-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseResponseDTO.php
More file actions
81 lines (65 loc) · 2.01 KB
/
BaseResponseDTO.php
File metadata and controls
81 lines (65 loc) · 2.01 KB
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
namespace WebmanTech\DTO;
use WebmanTech\CommonUtils\Response;
use WebmanTech\DTO\Helper\ConfigHelper;
class BaseResponseDTO extends BaseDTO
{
private array $responseHeaders = [];
public function withResponseHeaders(array $headers): static
{
$this->responseHeaders = $headers;
return $this;
}
public function getResponseHeaders(): array
{
return $this->responseHeaders;
}
private int $responseStatus = 200;
public function withResponseStatus(int $status): static
{
$this->responseStatus = $status;
return $this;
}
public function getResponseStatus(): int
{
return $this->responseStatus;
}
private ?string $responseStatusText = null;
public function withResponseStatusText(?string $text): static
{
$this->responseStatusText = $text;
return $this;
}
public function getResponseStatusText(): ?string
{
return $this->responseStatusText;
}
private string|\Closure|null $toResponseFormat = null;
/**
* 转为 Response
* @return mixed
*/
public function toResponse()
{
if ($this->toResponseFormat === null) {
$this->toResponseFormat = ConfigHelper::get('dto.to_response_format', 'json');
}
if ($this->toResponseFormat === 'json') {
$data = $this->toArray();
if ($data === []) {
$data = new \stdClass();
}
return Response::make()
->withStatus($this->getResponseStatus(), $this->getResponseStatusText())
->withHeaders(array_merge([
'Content-Type' => 'application/json',
], $this->getResponseHeaders()))
->withBody(json_encode($data) ?: '')
->getRaw();
}
if ($this->toResponseFormat instanceof \Closure) {
return ($this->toResponseFormat)($this);
}
throw new \InvalidArgumentException('toResponseFormat error');
}
}