-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportPayloadValidator.php
More file actions
271 lines (234 loc) · 9.24 KB
/
ImportPayloadValidator.php
File metadata and controls
271 lines (234 loc) · 9.24 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
<?php
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and LibreCode contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
declare(strict_types=1);
namespace OCA\ProfileFields\Service;
use DateTimeImmutable;
use InvalidArgumentException;
use OCA\ProfileFields\Db\FieldDefinition;
use OCA\ProfileFields\Enum\FieldVisibility;
use OCP\IUserManager;
class ImportPayloadValidator {
private const SCHEMA_VERSION = 1;
public function __construct(
private FieldDefinitionValidator $fieldDefinitionValidator,
private FieldDefinitionService $fieldDefinitionService,
private IUserManager $userManager,
) {
}
/**
* @param array<string, mixed> $payload
* @return array{
* schema_version: int,
* definitions: list<array{
* field_key: non-empty-string,
* label: non-empty-string,
* type: 'text'|'number'|'boolean'|'date'|'select'|'multiselect',
* edit_policy: 'admins'|'users',
* exposure_policy: 'hidden'|'private'|'users'|'public',
* sort_order: int,
* active: bool,
* created_at?: non-empty-string,
* updated_at?: non-empty-string,
* }>,
* values: list<array{
* field_key: non-empty-string,
* user_uid: non-empty-string,
* value: array{value: mixed},
* current_visibility: 'private'|'users'|'public',
* updated_by_uid: string,
* updated_at: non-empty-string,
* }>,
* }
*/
public function validate(array $payload): array {
$schemaVersion = $payload['schema_version'] ?? null;
if (!is_int($schemaVersion) || $schemaVersion !== self::SCHEMA_VERSION) {
throw new InvalidArgumentException(sprintf('schema_version must be %d', self::SCHEMA_VERSION));
}
$definitions = $this->validateDefinitions($this->requireList($payload, 'definitions'));
$values = $this->validateValues($this->requireList($payload, 'values'), $definitions);
return [
'schema_version' => $schemaVersion,
'definitions' => array_values($definitions),
'values' => $values,
];
}
/**
* @param list<mixed> $definitions
* @return array<non-empty-string, array{
* field_key: non-empty-string,
* label: non-empty-string,
* type: 'text'|'number'|'boolean'|'date'|'select'|'multiselect',
* edit_policy: 'admins'|'users',
* exposure_policy: 'hidden'|'private'|'users'|'public',
* sort_order: int,
* active: bool,
* created_at?: non-empty-string,
* updated_at?: non-empty-string,
* }>
*/
private function validateDefinitions(array $definitions): array {
$normalizedDefinitions = [];
foreach ($definitions as $index => $definition) {
if (!is_array($definition)) {
throw new InvalidArgumentException(sprintf('definitions[%d] must be an object', $index));
}
$validatedDefinition = $this->fieldDefinitionValidator->validate($definition);
$createdAt = $this->normalizeOptionalDate($definition, 'created_at', sprintf('definitions[%d].created_at must be a valid ISO-8601 datetime', $index));
$updatedAt = $this->normalizeOptionalDate($definition, 'updated_at', sprintf('definitions[%d].updated_at must be a valid ISO-8601 datetime', $index));
$fieldKey = $validatedDefinition['field_key'];
if (isset($normalizedDefinitions[$fieldKey])) {
throw new InvalidArgumentException(sprintf('definitions[%d].field_key is duplicated', $index));
}
$existingDefinition = $this->fieldDefinitionService->findByFieldKey($fieldKey);
if ($existingDefinition !== null && !$this->isCompatibleDefinition($existingDefinition, $validatedDefinition)) {
throw new InvalidArgumentException(sprintf('definitions[%d].field_key conflicts with an incompatible existing definition', $index));
}
$normalizedDefinitions[$fieldKey] = $validatedDefinition;
if ($createdAt !== null) {
$normalizedDefinitions[$fieldKey]['created_at'] = $createdAt;
}
if ($updatedAt !== null) {
$normalizedDefinitions[$fieldKey]['updated_at'] = $updatedAt;
}
}
return $normalizedDefinitions;
}
/**
* @param list<mixed> $values
* @param array<non-empty-string, array{
* field_key: non-empty-string,
* label: non-empty-string,
* type: 'text'|'number'|'boolean'|'date'|'select'|'multiselect',
* edit_policy: 'admins'|'users',
* exposure_policy: 'hidden'|'private'|'users'|'public',
* sort_order: int,
* active: bool,
* created_at?: non-empty-string,
* updated_at?: non-empty-string,
* }> $definitions
* @return list<array{
* field_key: non-empty-string,
* user_uid: non-empty-string,
* value: array{value: mixed},
* current_visibility: 'private'|'users'|'public',
* updated_by_uid: string,
* updated_at: non-empty-string,
* }>
*/
private function validateValues(array $values, array $definitions): array {
$normalizedValues = [];
$seenValueKeys = [];
foreach ($values as $index => $value) {
if (!is_array($value)) {
throw new InvalidArgumentException(sprintf('values[%d] must be an object', $index));
}
$fieldKey = $this->requireNonEmptyString($value, 'field_key', sprintf('values[%d].field_key is required', $index));
if (!isset($definitions[$fieldKey])) {
throw new InvalidArgumentException(sprintf('values[%d].field_key references an unknown definition', $index));
}
$userUid = $this->requireNonEmptyString($value, 'user_uid', sprintf('values[%d].user_uid is required', $index));
if (!$this->userManager->userExists($userUid)) {
throw new InvalidArgumentException(sprintf('values[%d].user_uid does not exist in destination instance', $index));
}
$valuePayload = $value['value'] ?? null;
if (!is_array($valuePayload) || !array_key_exists('value', $valuePayload)) {
throw new InvalidArgumentException(sprintf('values[%d].value must be an object payload with a value key', $index));
}
$currentVisibility = $this->requireNonEmptyString($value, 'current_visibility', sprintf('values[%d].current_visibility is required', $index));
if (!FieldVisibility::isValid($currentVisibility)) {
throw new InvalidArgumentException(sprintf('values[%d].current_visibility is not supported', $index));
}
$updatedByUid = $this->requireString($value, 'updated_by_uid', sprintf('values[%d].updated_by_uid is required', $index));
$updatedAt = $this->requireNonEmptyString($value, 'updated_at', sprintf('values[%d].updated_at is required', $index));
$this->assertDate($updatedAt, sprintf('values[%d].updated_at must be a valid ISO-8601 datetime', $index));
$compoundKey = $fieldKey . '\0' . $userUid;
if (isset($seenValueKeys[$compoundKey])) {
throw new InvalidArgumentException(sprintf('values[%d] duplicates field_key/user_uid pair', $index));
}
$seenValueKeys[$compoundKey] = true;
$normalizedValues[] = [
'field_key' => $fieldKey,
'user_uid' => $userUid,
'value' => ['value' => $valuePayload['value']],
'current_visibility' => $currentVisibility,
'updated_by_uid' => $updatedByUid,
'updated_at' => $updatedAt,
];
}
return $normalizedValues;
}
/**
* @param array<string, mixed> $payload
* @return list<mixed>
*/
private function requireList(array $payload, string $key): array {
$value = $payload[$key] ?? null;
if (!is_array($value) || !array_is_list($value)) {
throw new InvalidArgumentException(sprintf('%s must be a list', $key));
}
return $value;
}
/**
* @param array<string, mixed> $payload
*/
private function requireNonEmptyString(array $payload, string $key, string $message): string {
$value = trim((string)($payload[$key] ?? ''));
if ($value === '') {
throw new InvalidArgumentException($message);
}
return $value;
}
/**
* @param array<string, mixed> $payload
*/
private function requireString(array $payload, string $key, string $message): string {
if (!array_key_exists($key, $payload) || !is_string($payload[$key])) {
throw new InvalidArgumentException($message);
}
return $payload[$key];
}
private function assertDate(string $value, string $message): void {
try {
new DateTimeImmutable($value);
} catch (\Exception) {
throw new InvalidArgumentException($message);
}
}
/**
* @param array<string, mixed> $payload
*/
private function normalizeOptionalDate(array $payload, string $key, string $message): ?string {
if (!array_key_exists($key, $payload) || $payload[$key] === null || $payload[$key] === '') {
return null;
}
if (!is_string($payload[$key])) {
throw new InvalidArgumentException($message);
}
try {
return (new DateTimeImmutable($payload[$key]))->format(DATE_ATOM);
} catch (\Exception) {
throw new InvalidArgumentException($message);
}
}
/**
* @param array{
* field_key: non-empty-string,
* label: non-empty-string,
* type: 'text'|'number'|'boolean'|'date'|'select'|'multiselect',
* edit_policy: 'admins'|'users',
* exposure_policy: 'hidden'|'private'|'users'|'public',
* sort_order: int,
* active: bool,
* options?: list<string>|null,
* } $definition
*/
private function isCompatibleDefinition(FieldDefinition $existingDefinition, array $definition): bool {
return $existingDefinition->getType() === $definition['type']
&& $existingDefinition->getEditPolicy() === $definition['edit_policy']
&& $existingDefinition->getExposurePolicy() === $definition['exposure_policy'];
}
}