From e971fc53242a6674b1b6552913ccfc1b425e0ed9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=C5=A1o=20Belica?= Date: Fri, 10 Nov 2023 20:24:18 +0000 Subject: [PATCH] Deserialize PHP associative arrays as `new Map()` This way the order of the original PHP array is always preserved. --- src/unserialize.ts | 18 +++++++++++++----- test/unserialize-test.ts | Bin 4635 -> 5015 bytes 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/unserialize.ts b/src/unserialize.ts index ca7025d..d15fe25 100644 --- a/src/unserialize.ts +++ b/src/unserialize.ts @@ -6,6 +6,8 @@ import { isInteger, getClass, getIncompleteClass, __PHP_Incomplete_Class } from export type Options = { strict: boolean encoding: BufferEncoding + /** Preserves the order of PHP arrays as Map in JS. Otherwise Object is retunred. Defaults to true. */ + preserveOrder: boolean } function getClassReference(className: string, scope: Record, strict: boolean): any { @@ -60,11 +62,14 @@ function unserializeItem(parser: Parser, scope: Record, options: Op const pairs = parser.getByLength('{', '}', length => unserializePairs(parser, length, scope, options)) const isArray = pairs.every((item, idx) => isInteger(item.key) && idx === item.key) - const result = isArray ? [] : {} - pairs.forEach(({ key, value }) => { - result[key] = value - }) - return result + if (isArray) { + return pairs.map(({ value }) => value) + } + if (options.preserveOrder) { + return new Map(pairs.map(({ key, value }) => [key, value])) + } + + return pairs.reduce((acc, { key, value }) => ({ ...acc, [key]: value }), {}) } if (type === 'notserializable-class') { const name = parser.getByLength('"', '"', length => parser.readAhead(length)) @@ -109,6 +114,9 @@ function unserialize(item: string | Buffer, scope: Record = {}, giv if (typeof options.encoding === 'undefined') { options.encoding = 'utf8' } + if (typeof options.preserveOrder === 'undefined') { + options.preserveOrder = true + } const parser = new Parser(Buffer.from(item), 0, options) return unserializeItem(parser, scope, options) } diff --git a/test/unserialize-test.ts b/test/unserialize-test.ts index a7fff95c308080c984d4047228598fadc0c9eea4..3a96c266387243d5daff37cb5e3ae9038a91f4a8 100644 GIT binary patch delta 473 zcmZ{g!AiqG5QeG8P>dJFi#i7(2`s@jsX|J76TFB$xAd@dr*A!@Xg!#%6sqEjtR_ji3(+bcaot@U`$hmi%q}wRcE72 zC=JZ!oTmI4p#y%AfYOqS`v5v!n2O)fFNm=W$6O%$Z*kxN=uioot4XGPhUL|Mch8hr zRX(b+b`Q(CdujvXZu7N!RKB<;cCvOqmjY*SOLKn!=9!%UgJz3Bz2${Wy`DBN^o1RBNTj06bKFZ3} zIa_)(iIX``T5X;*jAEmvQS>9*$L)nzF*C&c`f*BAe-MV@pS!UTg*hlHKNu4D17vx2 ZG%