-
-
Notifications
You must be signed in to change notification settings - Fork 636
Expand file tree
/
Copy pathBaseAction.php
More file actions
224 lines (192 loc) · 7.41 KB
/
BaseAction.php
File metadata and controls
224 lines (192 loc) · 7.41 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<?php
declare(strict_types=1);
namespace HiEvents\Http\Actions;
use HiEvents\DataTransferObjects\BaseDataObject;
use HiEvents\DataTransferObjects\BaseDTO;
use HiEvents\DomainObjects\Enums\Role;
use HiEvents\DomainObjects\Interfaces\DomainObjectInterface;
use HiEvents\DomainObjects\Interfaces\IsFilterable;
use HiEvents\DomainObjects\Interfaces\IsSortable;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Exceptions\UnauthorizedException;
use HiEvents\Http\DTO\QueryParamsDTO;
use HiEvents\Http\ResponseCodes;
use HiEvents\Resources\BaseResource;
use HiEvents\Services\Domain\Auth\AuthUserService;
use HiEvents\Services\Infrastructure\Authorization\IsAuthorizedService;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response as LaravelResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Controller;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
use Spatie\LaravelData\Data;
abstract class BaseAction extends Controller
{
use ValidatesRequests;
/**
* @param class-string<BaseResource> $resource
* @param Collection|DomainObjectInterface|LengthAwarePaginator $data
* @param int $statusCode
* @param class-string<IsSortable|IsFilterable> $domainObject
* @return JsonResponse
*/
protected function filterableResourceResponse(
string $resource,
Collection|DomainObjectInterface|LengthAwarePaginator $data,
string $domainObject,
int $statusCode = ResponseCodes::HTTP_OK,
): JsonResponse
{
$metaFields = [];
if (is_a($domainObject, IsFilterable::class, true)) {
$metaFields['allowed_filter_fields'] = $domainObject::getAllowedFilterFields();
}
if (is_a($domainObject, IsSortable::class, true)) {
$metaFields['allowed_sorts'] = $domainObject::getAllowedSorts()->toArray();
$metaFields['default_sort'] = $domainObject::getDefaultSort();
$metaFields['default_sort_direction'] = $domainObject::getDefaultSortDirection();
}
return $this->resourceResponse($resource, $data, $statusCode, $metaFields);
}
/**
* @param class-string<BaseResource> $resource
* @param Collection|DomainObjectInterface|LengthAwarePaginator|BaseDTO|Paginator $data
* @param int $statusCode
* @param array $meta
* @param array $headers
* @param array $errors
* @return JsonResponse
*/
protected function resourceResponse(
string $resource,
Collection|DomainObjectInterface|LengthAwarePaginator|BaseDTO|Paginator|BaseDataObject $data,
int $statusCode = ResponseCodes::HTTP_OK,
array $meta = [],
array $headers = [],
array $errors = [],
): JsonResponse
{
if ($data instanceof Collection || $data instanceof Paginator) {
$additional = array_filter([
'meta' => $meta ?? null,
'errors' => $errors ?? null,
]);
$response = ($resource::collection($data)->additional($additional))
->response()
->setStatusCode($statusCode);
} else {
$response = (new $resource($data))
->response()
->setStatusCode($statusCode);
}
foreach ($headers as $header => $value) {
$response->header($header, $value);
}
return $response;
}
protected function noContentResponse(int $status = ResponseCodes::HTTP_NO_CONTENT): LaravelResponse
{
return Response::noContent($status);
}
protected function deletedResponse(): LaravelResponse
{
return Response::noContent();
}
protected function notFoundResponse(): LaravelResponse
{
return Response::noContent(ResponseCodes::HTTP_NOT_FOUND);
}
protected function errorResponse(
string $message,
int $statusCode = ResponseCodes::HTTP_BAD_REQUEST,
array $errors = [],
): JsonResponse
{
return $this->jsonResponse([
'message' => $message,
'errors' => $errors,
], $statusCode);
}
protected function jsonResponse(
mixed $data,
int $statusCode = ResponseCodes::HTTP_OK,
bool $wrapInData = false,
): JsonResponse
{
if ($wrapInData) {
$data = [
'data' => $data,
];
}
return new JsonResponse($data, $statusCode);
}
protected function isActionAuthorized(
int $entityId,
string $entityType,
Role $minimumRole = Role::ORGANIZER
): void
{
/** @var IsAuthorizedService $authService */
$authService = app()->make(IsAuthorizedService::class);
$authService->isActionAuthorized(
$entityId,
$entityType,
$this->getAuthenticatedUser(),
$this->getAuthenticatedAccountId(),
$minimumRole
);
}
protected function getAuthenticatedAccountId(): int
{
if (Auth::check()) {
/** @var AuthUserService $service */
$service = app(AuthUserService::class);
$accountId = $service->getAuthenticatedAccountId();
if ($accountId === null) {
throw new UnauthorizedException(__('No account ID found in token'));
}
return $accountId;
}
throw new UnauthorizedException();
}
protected function getAuthenticatedUser(): UserDomainObject|DomainObjectInterface
{
if (Auth::check()) {
/** @var AuthUserService $service */
$service = app(AuthUserService::class);
return $service->getUser();
}
throw new UnauthorizedException();
}
protected function isUserAuthenticated(): bool
{
return Auth::check();
}
protected function minimumAllowedRole(Role $minimumRole): void
{
/** @var IsAuthorizedService $authService */
$authService = app()->make(IsAuthorizedService::class);
$authService->validateUserRole($minimumRole, $this->getAuthenticatedUser());
}
public function getClientIp(Request $request): ?string
{
// If the request is coming from a DigitalOcean load balancer, use the connecting IP
if ($digitalOceanIp = $request->server('HTTP_DO_CONNECTING_IP')) {
return $digitalOceanIp;
}
return $request->getClientIp();
}
public function getPaginationQueryParams(Request $request): QueryParamsDTO
{
return QueryParamsDTO::fromArray($request->query->all());
}
public function isIncludeRequested(Request $request, string $include): bool
{
return in_array($include, explode(',', $request->query('include', '')), true);
}
}