-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathBunqModel.php
More file actions
469 lines (399 loc) · 13.5 KB
/
BunqModel.php
File metadata and controls
469 lines (399 loc) · 13.5 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
<?php
namespace bunq\Model\Core;
use bunq\Context\ApiContext;
use bunq\Context\BunqContext;
use bunq\Exception\BunqException;
use bunq\Http\BunqResponse;
use bunq\Http\BunqResponseRaw;
use bunq\Http\Pagination;
use bunq\Util\FileUtil;
use bunq\Util\ModelUtil;
use JsonSerializable;
use ReflectionClass;
use ReflectionProperty;
/**
* Base class for all endpoints, responsible for parsing json received from the server.
*/
abstract class BunqModel implements JsonSerializable
{
/**
* Field constants.
*/
const FIELD_RESPONSE = 'Response';
const FIELD_PAGINATION = 'Pagination';
const FIELD_ID = 'Id';
const FIELD_UUID = 'Uuid';
/**
* Regex constants.
*/
const REGEX_DOC_BLOCK_VARIABLE = '/@var\s(\w+)(\[\])?/';
const REGEX_EXPECTED_ONE = 1;
const REGEX_MATCH_RESULT_TYPE = 1;
const REGEX_MATCH_RESULT_IS_ARRAY = 2;
/**
* Index of the very first item in an array.
*/
const INDEX_FIRST = 0;
/**
* Depth counter constants.
*/
const DEPTH_COUNTER_BEGIN = 0;
const DEPTH_COUNTER_MAX = 2;
const DEPTH_COUNTER_INCREMENTER = 1;
/**
* Type constants.
*/
const SCALAR_TYPE_STRING = 'string';
const SCALAR_TYPE_BOOL = 'bool';
const SCALAR_TYPE_INT = 'int';
const SCALAR_TYPE_FLOAT = 'float';
/**
* @var string[]
*/
protected static $fieldNameOverrideMap = [];
/**
* Set of the PHP scalar types. Mimicking a constant, and therefore should be used with self::.
*
* @var bool[]
*/
private static $scalarTypes = [
self::SCALAR_TYPE_STRING => true,
self::SCALAR_TYPE_BOOL => true,
self::SCALAR_TYPE_INT => true,
self::SCALAR_TYPE_FLOAT => true,
];
/**
* Format constants.
*/
const FORMAT_STRING_EMPTY = '';
const SUFFIX_REQUEST_FIELD = '_field_for_request';
/**
* @param string $json
*
* @return static
*/
public static function createFromJsonString(string $json): BunqModel
{
$responseArray = ModelUtil::deserializeResponseArray($json);
return static::createFromResponseArray($responseArray);
}
/**
* @param mixed[] $responseArray
* @param string $wrapper
*
* @return BunqModel|null
*/
protected static function createFromResponseArray(
array $responseArray,
string $wrapper = null
) {
if (is_subclass_of(get_called_class(), AnchorObjectInterface::class)) {
return self::createFromResponseArrayAnchorObject($responseArray);
}
if (is_string($wrapper) && !empty($wrapper)) {
$pattern = '/^' . preg_quote($wrapper, '/') . '/i';
$matchingKeys = preg_grep($pattern, array_keys($responseArray));
if (!empty($matchingKeys)) {
$firstMatchingKey = reset($matchingKeys);
$responseArray = $responseArray[$firstMatchingKey];
}
}
return self::createInstanceFromResponseArray($responseArray);
}
/**
* @param mixed[] $responseArray
* @param int|null $depthCounter
*
* @return BunqModel|null
*/
private static function createFromResponseArrayAnchorObject(
array $responseArray,
int $depthCounter = null
) {
if (empty($responseArray)) {
return null;
}
if (is_null($depthCounter)) {
$depthCounter = self::DEPTH_COUNTER_BEGIN;
}
$model = self::createInstanceFromResponseArray($responseArray);
if ($model->isAllFieldNull() && $depthCounter < self::DEPTH_COUNTER_MAX) {
$model = self::decodeInsideModelFields($responseArray, $model, $depthCounter);
}
return $model;
}
/**
* @param mixed[] $responseArray
*
* @return BunqModel
*/
private static function createInstanceFromResponseArray(array $responseArray): BunqModel
{
$classDefinition = new \ReflectionClass(static::class);
/** @var BunqModel $instance */
$instance = $classDefinition->newInstanceWithoutConstructor();
foreach ($responseArray as $fieldNameRaw => $contents) {
$fieldName = static::determineResponseFieldName($fieldNameRaw);
if ($classDefinition->hasProperty($fieldName)) {
$property = $classDefinition->getProperty($fieldName);
$instance->{$fieldName} = static::determineFieldContents($property, $contents);
}
}
return $instance;
}
/**
* @param string $fieldNameRaw
*
* @return string
*/
private static function determineResponseFieldName(string $fieldNameRaw): string
{
$fieldNameOverrideMapFlipped = array_flip(static::$fieldNameOverrideMap);
if (isset($fieldNameOverrideMapFlipped[$fieldNameRaw])) {
$fieldNameRaw = $fieldNameOverrideMapFlipped[$fieldNameRaw];
}
return ModelUtil::snakeCaseToCamelCase($fieldNameRaw);
}
/**
* @param ReflectionProperty $property
* @param mixed|mixed[] $contents
*
* @return BunqModel|BunqModel[]|mixed
*/
private static function determineFieldContents(ReflectionProperty $property, $contents)
{
$docComment = $property->getDocComment();
if (preg_match(self::REGEX_DOC_BLOCK_VARIABLE, $docComment, $matches) === self::REGEX_EXPECTED_ONE) {
$fieldType = $matches[self::REGEX_MATCH_RESULT_TYPE];
if (is_null($contents) || static::isTypeScalar($fieldType)) {
return $contents;
} elseif (isset($matches[self::REGEX_MATCH_RESULT_IS_ARRAY])) {
/** @var BunqModel $modelClassNameQualified */
$modelClassNameQualified = ModelUtil::determineModelClassNameQualified($fieldType);
return $modelClassNameQualified::createListFromResponseArray($contents);
} else {
/** @var BunqModel $modelClassNameQualified */
$modelClassNameQualified = ModelUtil::determineModelClassNameQualified($fieldType);
$parentClassName = $property->getDeclaringClass()->getName();
$additionalWrappingKey = BunqModelWrapper::determineWrappingKey($parentClassName, $property->getName());
if (!is_null($additionalWrappingKey)) {
if (isset($contents[$additionalWrappingKey])) {
return $modelClassNameQualified::createFromResponseArray($contents[$additionalWrappingKey]);
}
}
return $modelClassNameQualified::createFromResponseArray($contents);
}
} else {
return $contents;
}
}
/**
* @param string $type
*
* @return bool
*/
private static function isTypeScalar(string $type): bool
{
return isset(self::$scalarTypes[$type]);
}
/**
* @param mixed[] $responseArray
* @param string $wrapper
*
* @return BunqModel[]
*/
protected static function createListFromResponseArray(
array $responseArray,
string $wrapper = null
): array {
$list = [];
foreach ($responseArray as $className => $element) {
if (!is_array($element)) {
return $list;
}
$list[] = static::createFromResponseArray($element, $wrapper);
}
return $list;
}
/**
* @return bool
*/
abstract protected function isAllFieldNull();
/**
* @param mixed[] $responseArray
* @param BunqModel $model
* @param int $depthCounter
*
* @return BunqModel
*/
private static function decodeInsideModelFields(array $responseArray, BunqModel $model, int $depthCounter)
{
$modelFields = (array_keys(get_object_vars($model)));
foreach ($modelFields as $field) {
$fieldClass = ModelUtil::getModelClassNameQualifiedOrNull($field);
if (is_null($fieldClass)) {
continue;
}
$reflectionClass = new ReflectionClass($fieldClass);
/** @var BunqModel $bunqModelSubClass */
$bunqModelSubClass = $reflectionClass->newInstanceWithoutConstructor();
$fieldContents = $bunqModelSubClass::createFromResponseArrayAnchorObject(
$responseArray,
$depthCounter + self::DEPTH_COUNTER_INCREMENTER
);
if ($fieldContents->isAllFieldNull()) {
$model->{$field} = null;
} else {
$model->{$field} = $fieldContents;
}
}
return $model;
}
/**
* @param BunqResponseRaw $responseRaw
* @param string $wrapper
*
* @return BunqResponse
*/
protected static function fromJsonList(
BunqResponseRaw $responseRaw,
string $wrapper = null
): BunqResponse {
$json = $responseRaw->getBodyString();
$responseArray = ModelUtil::deserializeResponseArray($json);
$response = $responseArray[self::FIELD_RESPONSE];
$value = static::createListFromResponseArray($response, $wrapper);
$pagination = null;
if (isset($responseArray[self::FIELD_PAGINATION])) {
$pagination = Pagination::restore($responseArray[self::FIELD_PAGINATION]);
}
return new BunqResponse($value, $responseRaw->getHeaders(), $pagination);
}
/**
* @param BunqResponseRaw $responseRaw
*
* @return BunqResponse
*/
protected static function classFromJson(BunqResponseRaw $responseRaw): BunqResponse
{
$json = $responseRaw->getBodyString();
$response = ModelUtil::deserializeResponseArray($json)[self::FIELD_RESPONSE];
$formattedResponseArray = ModelUtil::formatResponseArray($response);
$value = static::createFromResponseArray($formattedResponseArray);
return new BunqResponse($value, $responseRaw->getHeaders());
}
/**
* @param BunqResponseRaw $responseRaw
*
* @return BunqResponse
*/
protected static function processForId(BunqResponseRaw $responseRaw): BunqResponse
{
$id = Id::fromJson($responseRaw, self::FIELD_ID)->getValue();
return new BunqResponse($id->getId(), $responseRaw->getHeaders());
}
/**
* @param BunqResponseRaw $responseRaw
* @param string|null $wrapper
*
* @return BunqResponse
* @throws BunqException when the result is not expected.
*/
protected static function fromJson(BunqResponseRaw $responseRaw, string $wrapper = null): BunqResponse
{
$json = $responseRaw->getBodyString();
$responseArray = ModelUtil::deserializeResponseArray($json);
$response = $responseArray[self::FIELD_RESPONSE];
$value = static::createListFromResponseArray($response, $wrapper);
return new BunqResponse($value[self::INDEX_FIRST], $responseRaw->getHeaders());
}
/**
* @param string $path
*
* @return BunqModel
*/
public static function fromJsonFile(string $path): BunqModel
{
$decodedArray = ModelUtil::deserializeResponseArray(
FileUtil::getFileContents($path)
);
return static::createInstanceFromResponseArray($decodedArray);
}
/**
* @param BunqResponseRaw $responseRaw
*
* @return BunqResponse
*/
protected static function processForUuid(BunqResponseRaw $responseRaw): BunqResponse
{
$uuid = Uuid::fromJson($responseRaw, self::FIELD_UUID)->getValue();
return new BunqResponse($uuid->getUuid(), $responseRaw->getHeaders());
}
/**
* @return ApiContext
*/
protected static function getApiContext(): ApiContext
{
return BunqContext::getApiContext();
}
/**
* @return int
*/
protected static function determineUserId(): int
{
return BunqContext::getUserContext()->getUserId();
}
/**
* @param int|null $monetaryAccountId
*
* @return int
*/
protected static function determineMonetaryAccountId(int $monetaryAccountId = null): int
{
if (is_null($monetaryAccountId)) {
return BunqContext::getUserContext()->getMainMonetaryAccountId();
} else {
return $monetaryAccountId;
}
}
/**
* @return mixed[]
*/
public function jsonSerialize(): array
{
$array = [];
foreach ($this->getNonStaticProperties() as $property) {
$fieldName = static::determineRequestFieldName($property);
if (!is_null($this->{$property->getName()})) {
$fieldName = str_replace(self::SUFFIX_REQUEST_FIELD, self::FORMAT_STRING_EMPTY, $fieldName);
$array[$fieldName] = $this->{$property->getName()};
}
}
return $array;
}
/**
* @return ReflectionProperty[]
*/
private function getNonStaticProperties(): array
{
$reflectionClass = new ReflectionClass($this);
return array_diff(
$reflectionClass->getProperties(ReflectionProperty::IS_PROTECTED),
$reflectionClass->getProperties(ReflectionProperty::IS_STATIC)
);
}
/**
* @param ReflectionProperty $property
*
* @return string
*/
private static function determineRequestFieldName(ReflectionProperty $property): string
{
$fieldName = ModelUtil::camelCaseToSnakeCase($property->getName());
if (isset(static::$fieldNameOverrideMap[$fieldName])) {
return static::$fieldNameOverrideMap[$fieldName];
} else {
return $fieldName;
}
}
}