quicktype-core 7.0.28 → 7.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,6 +20,7 @@ const Dart_1 = require("./Dart");
20
20
  const Python_1 = require("./Python");
21
21
  const Pike_1 = require("./Pike");
22
22
  const Haskell_1 = require("./Haskell");
23
+ const Php_1 = require("./Php");
23
24
  exports.all = [
24
25
  new CSharp_1.CSharpTargetLanguage(),
25
26
  new Golang_1.GoTargetLanguage(),
@@ -40,7 +41,8 @@ exports.all = [
40
41
  new Dart_1.DartTargetLanguage(),
41
42
  new Python_1.PythonTargetLanguage("Python", ["python", "py"], "py"),
42
43
  new Pike_1.PikeTargetLanguage(),
43
- new Haskell_1.HaskellTargetLanguage()
44
+ new Haskell_1.HaskellTargetLanguage(),
45
+ new Php_1.PhpTargetLanguage()
44
46
  ];
45
47
  function languageNamed(name, targetLanguages) {
46
48
  if (targetLanguages === undefined) {
@@ -29,6 +29,7 @@ class DartTargetLanguage extends TargetLanguage_1.TargetLanguage {
29
29
  }
30
30
  getOptions() {
31
31
  return [
32
+ exports.dartOptions.nullSafety,
32
33
  exports.dartOptions.justTypes,
33
34
  exports.dartOptions.codersInClass,
34
35
  exports.dartOptions.methodNamesWithMap,
@@ -0,0 +1,80 @@
1
+ import { ConvenienceRenderer, ForbiddenWordsInfo } from "../ConvenienceRenderer";
2
+ import { Name, Namer } from "../Naming";
3
+ import { RenderContext } from "../Renderer";
4
+ import { BooleanOption, Option, OptionValues } from "../RendererOptions";
5
+ import { Sourcelike } from "../Source";
6
+ import { AcronymStyleOptions } from "../support/Acronyms";
7
+ import { TargetLanguage } from "../TargetLanguage";
8
+ import { ClassProperty, ClassType, EnumType, Type, UnionType } from "../Type";
9
+ import { StringTypeMapping } from "..";
10
+ export declare const phpOptions: {
11
+ withGet: BooleanOption;
12
+ fastGet: BooleanOption;
13
+ withSet: BooleanOption;
14
+ withClosing: BooleanOption;
15
+ acronymStyle: import("../RendererOptions").EnumOption<AcronymStyleOptions>;
16
+ };
17
+ export declare class PhpTargetLanguage extends TargetLanguage {
18
+ constructor();
19
+ protected getOptions(): Option<any>[];
20
+ readonly supportsUnionsWithBothNumberTypes: boolean;
21
+ protected makeRenderer(renderContext: RenderContext, untypedOptionValues: {
22
+ [name: string]: any;
23
+ }): PhpRenderer;
24
+ readonly stringTypeMapping: StringTypeMapping;
25
+ }
26
+ export declare const stringEscape: (s: string) => string;
27
+ export declare function phpNameStyle(startWithUpper: boolean, upperUnderscore: boolean, original: string, acronymsStyle?: (s: string) => string): string;
28
+ export interface FunctionNames {
29
+ readonly getter: Name;
30
+ readonly setter: Name;
31
+ readonly validate: Name;
32
+ readonly from: Name;
33
+ readonly to: Name;
34
+ readonly sample: Name;
35
+ }
36
+ export declare class PhpRenderer extends ConvenienceRenderer {
37
+ protected readonly _options: OptionValues<typeof phpOptions>;
38
+ private readonly _gettersAndSettersForPropertyName;
39
+ private _haveEmittedLeadingComments;
40
+ protected readonly _converterClassname: string;
41
+ protected readonly _converterKeywords: string[];
42
+ constructor(targetLanguage: TargetLanguage, renderContext: RenderContext, _options: OptionValues<typeof phpOptions>);
43
+ protected forbiddenForObjectProperties(_c: ClassType, _className: Name): ForbiddenWordsInfo;
44
+ protected makeNamedTypeNamer(): Namer;
45
+ protected namerForObjectProperty(): Namer;
46
+ protected makeUnionMemberNamer(): Namer;
47
+ protected makeEnumCaseNamer(): Namer;
48
+ protected unionNeedsName(u: UnionType): boolean;
49
+ protected namedTypeToNameForTopLevel(type: Type): Type | undefined;
50
+ protected makeNamesForPropertyGetterAndSetter(_c: ClassType, _className: Name, _p: ClassProperty, _jsonName: string, name: Name): FunctionNames;
51
+ protected makePropertyDependencyNames(c: ClassType, className: Name, p: ClassProperty, jsonName: string, name: Name): Name[];
52
+ private getNameStyling;
53
+ protected startFile(_basename: Sourcelike): void;
54
+ protected finishFile(): void;
55
+ protected emitFileHeader(fileName: Sourcelike, _imports: string[]): void;
56
+ emitDescriptionBlock(lines: Sourcelike[]): void;
57
+ emitBlock(line: Sourcelike, f: () => void): void;
58
+ protected phpType(_reference: boolean, t: Type, isOptional?: boolean, prefix?: string, suffix?: string): Sourcelike;
59
+ protected phpDocConvertType(className: Name, t: Type): Sourcelike;
60
+ protected phpConvertType(className: Name, t: Type): Sourcelike;
61
+ protected phpToObjConvert(className: Name, t: Type, lhs: Sourcelike[], args: Sourcelike[]): void;
62
+ private transformDateTime;
63
+ protected phpFromObjConvert(className: Name, t: Type, lhs: Sourcelike[], args: Sourcelike[]): void;
64
+ protected phpSampleConvert(className: Name, t: Type, lhs: Sourcelike[], args: Sourcelike[], idx: number, suffix: Sourcelike): void;
65
+ private phpValidate;
66
+ protected emitFromMethod(names: FunctionNames, p: ClassProperty, className: Name, _name: Name, desc?: string[]): void;
67
+ protected emitToMethod(names: FunctionNames, p: ClassProperty, className: Name, name: Name, desc?: string[]): void;
68
+ protected emitValidateMethod(names: FunctionNames, p: ClassProperty, className: Name, name: Name, desc?: string[]): void;
69
+ protected emitGetMethod(names: FunctionNames, p: ClassProperty, className: Name, name: Name, desc?: string[]): void;
70
+ protected emitSetMethod(names: FunctionNames, p: ClassProperty, className: Name, name: Name, desc?: string[]): void;
71
+ protected emitSampleMethod(names: FunctionNames, p: ClassProperty, className: Name, name: Name, desc: string[] | undefined, idx: number): void;
72
+ protected emitClassDefinition(c: ClassType, className: Name): void;
73
+ protected emitUnionAttributes(_u: UnionType, _unionName: Name): void;
74
+ protected emitUnionSerializer(_u: UnionType, _unionName: Name): void;
75
+ protected emitUnionDefinition(_u: UnionType, _unionName: Name): void;
76
+ protected emitEnumSerializationAttributes(_e: EnumType): void;
77
+ protected emitEnumDeserializationAttributes(_e: EnumType): void;
78
+ protected emitEnumDefinition(e: EnumType, enumName: Name): void;
79
+ protected emitSourceStructure(givenFilename: string): void;
80
+ }
@@ -0,0 +1,677 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const Annotation_1 = require("../Annotation");
4
+ const ConvenienceRenderer_1 = require("../ConvenienceRenderer");
5
+ const Naming_1 = require("../Naming");
6
+ const RendererOptions_1 = require("../RendererOptions");
7
+ const Source_1 = require("../Source");
8
+ const Acronyms_1 = require("../support/Acronyms");
9
+ const Strings_1 = require("../support/Strings");
10
+ const Support_1 = require("../support/Support");
11
+ const TargetLanguage_1 = require("../TargetLanguage");
12
+ const TypeUtils_1 = require("../TypeUtils");
13
+ const _ = require("lodash");
14
+ exports.phpOptions = {
15
+ withGet: new RendererOptions_1.BooleanOption("with-get", "Create Getter", true),
16
+ fastGet: new RendererOptions_1.BooleanOption("fast-get", "getter without validation", false),
17
+ withSet: new RendererOptions_1.BooleanOption("with-set", "Create Setter", false),
18
+ withClosing: new RendererOptions_1.BooleanOption("with-closing", "PHP Closing Tag", false),
19
+ acronymStyle: Acronyms_1.acronymOption(Acronyms_1.AcronymStyleOptions.Pascal)
20
+ };
21
+ class PhpTargetLanguage extends TargetLanguage_1.TargetLanguage {
22
+ constructor() {
23
+ super("Php", ["php"], "php");
24
+ }
25
+ getOptions() {
26
+ return _.values(exports.phpOptions);
27
+ }
28
+ get supportsUnionsWithBothNumberTypes() {
29
+ return true;
30
+ }
31
+ makeRenderer(renderContext, untypedOptionValues) {
32
+ const options = RendererOptions_1.getOptionValues(exports.phpOptions, untypedOptionValues);
33
+ return new PhpRenderer(this, renderContext, options);
34
+ }
35
+ get stringTypeMapping() {
36
+ const mapping = new Map();
37
+ mapping.set("date", "date"); // TODO is not implemented yet
38
+ mapping.set("time", "time"); // TODO is not implemented yet
39
+ mapping.set("uuid", "uuid"); // TODO is not implemented yet
40
+ mapping.set("date-time", "date-time");
41
+ return mapping;
42
+ }
43
+ }
44
+ exports.PhpTargetLanguage = PhpTargetLanguage;
45
+ exports.stringEscape = Strings_1.utf16ConcatMap(Strings_1.escapeNonPrintableMapper(Strings_1.isAscii, Strings_1.standardUnicodeHexEscape));
46
+ function isStartCharacter(codePoint) {
47
+ if (codePoint === 0x5f)
48
+ return true; // underscore
49
+ return Strings_1.isAscii(codePoint) && Strings_1.isLetter(codePoint);
50
+ }
51
+ function isPartCharacter(codePoint) {
52
+ return isStartCharacter(codePoint) || (Strings_1.isAscii(codePoint) && Strings_1.isDigit(codePoint));
53
+ }
54
+ const legalizeName = Strings_1.utf16LegalizeCharacters(isPartCharacter);
55
+ function phpNameStyle(startWithUpper, upperUnderscore, original, acronymsStyle = Strings_1.allUpperWordStyle) {
56
+ const words = Strings_1.splitIntoWords(original);
57
+ return Strings_1.combineWords(words, legalizeName, upperUnderscore ? Strings_1.allUpperWordStyle : startWithUpper ? Strings_1.firstUpperWordStyle : Strings_1.allLowerWordStyle, upperUnderscore ? Strings_1.allUpperWordStyle : Strings_1.firstUpperWordStyle, upperUnderscore || startWithUpper ? Strings_1.allUpperWordStyle : Strings_1.allLowerWordStyle, acronymsStyle, upperUnderscore ? "_" : "", isStartCharacter);
58
+ }
59
+ exports.phpNameStyle = phpNameStyle;
60
+ class PhpRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
61
+ constructor(targetLanguage, renderContext, _options) {
62
+ super(targetLanguage, renderContext);
63
+ this._options = _options;
64
+ this._gettersAndSettersForPropertyName = new Map();
65
+ this._haveEmittedLeadingComments = false;
66
+ this._converterClassname = "Converter";
67
+ this._converterKeywords = [];
68
+ }
69
+ forbiddenForObjectProperties(_c, _className) {
70
+ return { names: [], includeGlobalForbidden: true };
71
+ }
72
+ makeNamedTypeNamer() {
73
+ return this.getNameStyling("typeNamingFunction");
74
+ }
75
+ namerForObjectProperty() {
76
+ return this.getNameStyling("propertyNamingFunction");
77
+ }
78
+ makeUnionMemberNamer() {
79
+ return this.getNameStyling("propertyNamingFunction");
80
+ }
81
+ makeEnumCaseNamer() {
82
+ return this.getNameStyling("enumCaseNamingFunction");
83
+ }
84
+ unionNeedsName(u) {
85
+ return TypeUtils_1.nullableFromUnion(u) === null;
86
+ }
87
+ namedTypeToNameForTopLevel(type) {
88
+ return TypeUtils_1.directlyReachableSingleNamedType(type);
89
+ }
90
+ makeNamesForPropertyGetterAndSetter(_c, _className, _p, _jsonName, name) {
91
+ const getterName = new Naming_1.DependencyName(this.getNameStyling("propertyNamingFunction"), name.order, lookup => `get_${lookup(name)}`);
92
+ const setterName = new Naming_1.DependencyName(this.getNameStyling("propertyNamingFunction"), name.order, lookup => `set_${lookup(name)}`);
93
+ const validateName = new Naming_1.DependencyName(this.getNameStyling("propertyNamingFunction"), name.order, lookup => `validate_${lookup(name)}`);
94
+ const fromName = new Naming_1.DependencyName(this.getNameStyling("propertyNamingFunction"), name.order, lookup => `from_${lookup(name)}`);
95
+ const toName = new Naming_1.DependencyName(this.getNameStyling("propertyNamingFunction"), name.order, lookup => `to_${lookup(name)}`);
96
+ const sampleName = new Naming_1.DependencyName(this.getNameStyling("propertyNamingFunction"), name.order, lookup => `sample_${lookup(name)}`);
97
+ return {
98
+ getter: getterName,
99
+ setter: setterName,
100
+ validate: validateName,
101
+ from: fromName,
102
+ to: toName,
103
+ sample: sampleName
104
+ };
105
+ }
106
+ makePropertyDependencyNames(c, className, p, jsonName, name) {
107
+ const getterAndSetterNames = this.makeNamesForPropertyGetterAndSetter(c, className, p, jsonName, name);
108
+ this._gettersAndSettersForPropertyName.set(name, getterAndSetterNames);
109
+ return [
110
+ getterAndSetterNames.getter,
111
+ getterAndSetterNames.setter,
112
+ getterAndSetterNames.validate,
113
+ getterAndSetterNames.to,
114
+ getterAndSetterNames.from,
115
+ getterAndSetterNames.sample
116
+ ];
117
+ }
118
+ getNameStyling(convention) {
119
+ const styling = {
120
+ typeNamingFunction: Naming_1.funPrefixNamer("types", n => phpNameStyle(true, false, n, Acronyms_1.acronymStyle(this._options.acronymStyle))),
121
+ propertyNamingFunction: Naming_1.funPrefixNamer("properties", n => phpNameStyle(false, false, n, Acronyms_1.acronymStyle(this._options.acronymStyle))),
122
+ enumCaseNamingFunction: Naming_1.funPrefixNamer("enum-cases", n => phpNameStyle(true, true, n, Acronyms_1.acronymStyle(this._options.acronymStyle)))
123
+ };
124
+ return styling[convention];
125
+ }
126
+ startFile(_basename) {
127
+ this.ensureBlankLine();
128
+ if (!this._haveEmittedLeadingComments && this.leadingComments !== undefined) {
129
+ this.emitCommentLines(this.leadingComments);
130
+ this.ensureBlankLine();
131
+ this._haveEmittedLeadingComments = true;
132
+ }
133
+ }
134
+ finishFile() {
135
+ // empty
136
+ }
137
+ emitFileHeader(fileName, _imports) {
138
+ this.startFile(fileName);
139
+ this.emitLine("// This is a autogenerated file:", fileName);
140
+ this.ensureBlankLine();
141
+ }
142
+ emitDescriptionBlock(lines) {
143
+ this.emitCommentLines(lines, " * ", "/**", " */");
144
+ }
145
+ emitBlock(line, f) {
146
+ this.emitLine(line, " {");
147
+ this.indent(f);
148
+ this.emitLine("}");
149
+ }
150
+ phpType(_reference, t, isOptional = false, prefix = "?", suffix = "") {
151
+ function optionalize(s) {
152
+ return [isOptional ? prefix : "", s, isOptional ? suffix : ""];
153
+ }
154
+ return TypeUtils_1.matchType(t, _anyType => Source_1.maybeAnnotated(isOptional, Annotation_1.anyTypeIssueAnnotation, "Object"), _nullType => Source_1.maybeAnnotated(isOptional, Annotation_1.nullTypeIssueAnnotation, "Object"), _boolType => optionalize("bool"), _integerType => optionalize("int"), _doubleType => optionalize("float"), _stringType => optionalize("string"), _arrayType => optionalize("array"), classType => optionalize(this.nameForNamedType(classType)), _mapType => optionalize("stdClass"), enumType => optionalize(this.nameForNamedType(enumType)), unionType => {
155
+ const nullable = TypeUtils_1.nullableFromUnion(unionType);
156
+ if (nullable !== null)
157
+ return this.phpType(true, nullable, true, prefix, suffix);
158
+ return this.nameForNamedType(unionType);
159
+ }, transformedStringType => {
160
+ if (transformedStringType.kind === "time") {
161
+ throw Error('transformedStringType.kind === "time"');
162
+ }
163
+ if (transformedStringType.kind === "date") {
164
+ throw Error('transformedStringType.kind === "date"');
165
+ }
166
+ if (transformedStringType.kind === "date-time") {
167
+ return "DateTime";
168
+ }
169
+ if (transformedStringType.kind === "uuid") {
170
+ throw Error('transformedStringType.kind === "uuid"');
171
+ }
172
+ return "string";
173
+ });
174
+ }
175
+ phpDocConvertType(className, t) {
176
+ return TypeUtils_1.matchType(t, _anyType => "any", _nullType => "null", _boolType => "bool", _integerType => "int", _doubleType => "float", _stringType => "string", arrayType => [this.phpDocConvertType(className, arrayType.items), "[]"], _classType => _classType.getCombinedName(), _mapType => "stdClass", enumType => this.nameForNamedType(enumType), unionType => {
177
+ const nullable = TypeUtils_1.nullableFromUnion(unionType);
178
+ if (nullable !== null) {
179
+ return [this.phpDocConvertType(className, nullable), "|null"];
180
+ }
181
+ throw Error("union are not supported");
182
+ }, transformedStringType => {
183
+ if (transformedStringType.kind === "date-time") {
184
+ return "DateTime";
185
+ }
186
+ throw Error('transformedStringType.kind === "unknown"');
187
+ });
188
+ }
189
+ phpConvertType(className, t) {
190
+ return TypeUtils_1.matchType(t, _anyType => "any", _nullType => "null", _boolType => "bool", _integerType => "int", _doubleType => "float", _stringType => "string", _arrayType => "array", _classType => "stdClass", _mapType => "stdClass", _enumType => "string", // TODO number this.nameForNamedType(enumType),
191
+ // TODO number this.nameForNamedType(enumType),
192
+ unionType => {
193
+ const nullable = TypeUtils_1.nullableFromUnion(unionType);
194
+ if (nullable !== null) {
195
+ return ["?", this.phpConvertType(className, nullable)];
196
+ }
197
+ throw Error("union are not supported");
198
+ }, transformedStringType => {
199
+ if (transformedStringType.kind === "date-time") {
200
+ return "string";
201
+ }
202
+ throw Error('transformedStringType.kind === "unknown"');
203
+ });
204
+ }
205
+ phpToObjConvert(className, t, lhs, args) {
206
+ return TypeUtils_1.matchType(t, _anyType => this.emitLine(...lhs, ...args, "; /*any*/"), _nullType => this.emitLine(...lhs, ...args, "; /*null*/"), _boolType => this.emitLine(...lhs, ...args, "; /*bool*/"), _integerType => this.emitLine(...lhs, ...args, "; /*int*/"), _doubleType => this.emitLine(...lhs, ...args, "; /*float*/"), _stringType => this.emitLine(...lhs, ...args, "; /*string*/"), arrayType => {
207
+ this.emitLine(...lhs, "array_map(function ($value) {");
208
+ this.indent(() => {
209
+ this.phpToObjConvert(className, arrayType.items, ["return "], ["$value"]);
210
+ // this.emitLine("return $tmp;");
211
+ });
212
+ this.emitLine("}, ", ...args, ");");
213
+ }, _classType => this.emitLine(...lhs, ...args, "->to(); ", "/*class*/"), mapType => {
214
+ this.emitBlock(["function to($my): stdClass"], () => {
215
+ this.emitLine("$out = new stdClass();");
216
+ this.emitBlock(["foreach ($my as $k => $v)"], () => {
217
+ this.phpToObjConvert(className, mapType.values, ["$my->$k = "], ["$v"]);
218
+ });
219
+ this.emitLine("return $out;");
220
+ });
221
+ this.emitLine("return to(", ...args, ");");
222
+ }, enumType => this.emitLine(...lhs, this.nameForNamedType(enumType), "::to(", ...args, "); ", "/*enum*/"), unionType => {
223
+ const nullable = TypeUtils_1.nullableFromUnion(unionType);
224
+ if (nullable !== null) {
225
+ this.emitLine("if (!is_null(", ...args, ")) {");
226
+ this.indent(() => this.phpToObjConvert(className, nullable, lhs, args));
227
+ this.emitLine("} else {");
228
+ this.indent(() => this.emitLine(...lhs, " null;"));
229
+ this.emitLine("}");
230
+ return;
231
+ }
232
+ throw Error("union are not supported");
233
+ }, transformedStringType => {
234
+ if (transformedStringType.kind === "date-time") {
235
+ this.emitLine(...lhs, ...args, "->format(DateTimeInterface::ISO8601);");
236
+ return;
237
+ }
238
+ throw Error('transformedStringType.kind === "unknown"');
239
+ });
240
+ }
241
+ transformDateTime(className, attrName, scopeAttrName) {
242
+ this.emitBlock(["if (!is_a(", scopeAttrName, ", 'DateTime'))"], () => this.emitLine("throw new Exception('Attribute Error:", className, "::", attrName, "');"));
243
+ // if (lhs !== undefined) {
244
+ // this.emitLine(lhs, "$tmp;");
245
+ // }
246
+ }
247
+ phpFromObjConvert(className, t, lhs, args) {
248
+ return TypeUtils_1.matchType(t, _anyType => this.emitLine(...lhs, ...args, "; /*any*/"), _nullType => this.emitLine(...lhs, ...args, "; /*null*/"), _boolType => this.emitLine(...lhs, ...args, "; /*bool*/"), _integerType => this.emitLine(...lhs, ...args, "; /*int*/"), _doubleType => this.emitLine(...lhs, ...args, "; /*float*/"), _stringType => this.emitLine(...lhs, ...args, "; /*string*/"), arrayType => {
249
+ this.emitLine(...lhs, " array_map(function ($value) {");
250
+ this.indent(() => {
251
+ this.phpFromObjConvert(className, arrayType.items, ["return "], ["$value"]);
252
+ // this.emitLine("return $tmp;");
253
+ });
254
+ this.emitLine("}, ", ...args, ");");
255
+ }, classType => this.emitLine(...lhs, this.nameForNamedType(classType), "::from(", ...args, "); ", "/*class*/"), mapType => {
256
+ this.emitBlock(["function from($my): stdClass"], () => {
257
+ this.emitLine("$out = new stdClass();");
258
+ this.emitBlock(["foreach ($my as $k => $v)"], () => {
259
+ this.phpFromObjConvert(className, mapType.values, ["$out->$k = "], ["$v"]);
260
+ });
261
+ this.emitLine("return $out;");
262
+ });
263
+ this.emitLine("return from(", ...args, ");");
264
+ }, enumType => this.emitLine(...lhs, this.nameForNamedType(enumType), "::from(", ...args, "); ", "/*enum*/"), unionType => {
265
+ const nullable = TypeUtils_1.nullableFromUnion(unionType);
266
+ if (nullable !== null) {
267
+ this.emitLine("if (!is_null(", ...args, ")) {");
268
+ this.indent(() => this.phpFromObjConvert(className, nullable, lhs, args));
269
+ this.emitLine("} else {");
270
+ this.indent(() => this.emitLine("return null;"));
271
+ this.emitLine("}");
272
+ return;
273
+ }
274
+ throw Error("union are not supported");
275
+ }, transformedStringType => {
276
+ if (transformedStringType.kind === "date-time") {
277
+ this.emitLine("$tmp = ", "DateTime::createFromFormat(DateTimeInterface::ISO8601, ", args, ");");
278
+ this.transformDateTime(className, "", ["$tmp"]);
279
+ this.emitLine("return $tmp;");
280
+ return;
281
+ }
282
+ throw Error('transformedStringType.kind === "unknown"');
283
+ });
284
+ }
285
+ phpSampleConvert(className, t, lhs, args, idx, suffix) {
286
+ return TypeUtils_1.matchType(t, _anyType => this.emitLine(...lhs, "'AnyType::", className, "::", args, "::" + idx, "'", suffix, "/*", "" + idx, ":", args, "*/"), _nullType => this.emitLine(...lhs, "null", suffix, " /*", "" + idx, ":", args, "*/"), _boolType => this.emitLine(...lhs, "true", suffix, " /*", "" + idx, ":", args, "*/"), _integerType => this.emitLine(...lhs, "" + idx, suffix, " /*", "" + idx, ":", args, "*/"), _doubleType => this.emitLine(...lhs, "" + (idx + idx / 1000), suffix, " /*", "" + idx, ":", args, "*/"), _stringType => this.emitLine(...lhs, "'", className, "::", args, "::" + idx, "'", suffix, " /*", "" + idx, ":", args, "*/"), arrayType => {
287
+ this.emitLine(...lhs, " array(");
288
+ this.indent(() => {
289
+ this.phpSampleConvert(className, arrayType.items, [], [], idx, "");
290
+ });
291
+ this.emitLine("); /* ", "" + idx, ":", args, "*/");
292
+ }, classType => this.emitLine(...lhs, this.nameForNamedType(classType), "::sample()", suffix, " /*", "" + idx, ":", args, "*/"), mapType => {
293
+ this.emitBlock(["function sample(): stdClass"], () => {
294
+ this.emitLine("$out = new stdClass();");
295
+ this.phpSampleConvert(className, mapType.values, ["$out->{'", className, "'} = "], args, idx, ";");
296
+ this.emitLine("return $out;");
297
+ });
298
+ this.emitLine("return sample();");
299
+ }, enumType => this.emitLine(...lhs, this.nameForNamedType(enumType), "::sample()", suffix, " /*enum*/"), unionType => {
300
+ const nullable = TypeUtils_1.nullableFromUnion(unionType);
301
+ if (nullable !== null) {
302
+ this.phpSampleConvert(className, nullable, lhs, args, idx, suffix);
303
+ return;
304
+ }
305
+ throw Error("union are not supported:" + unionType);
306
+ }, transformedStringType => {
307
+ if (transformedStringType.kind === "date-time") {
308
+ const x = _.pad("" + (1 + (idx % 31)), 2, "0");
309
+ this.emitLine(...lhs, "DateTime::createFromFormat(DateTimeInterface::ISO8601, '", `2020-12-${x}T12:${x}:${x}+00:00`, "')", suffix);
310
+ // this.emitLine("return sample();");
311
+ return;
312
+ }
313
+ throw Error('transformedStringType.kind === "unknown"');
314
+ });
315
+ }
316
+ phpValidate(className, t, attrName, scopeAttrName) {
317
+ const is = (isfn, myT = className) => {
318
+ this.emitBlock(["if (!", isfn, "(", scopeAttrName, "))"], () => this.emitLine('throw new Exception("Attribute Error:', myT, "::", attrName, '");'));
319
+ };
320
+ return TypeUtils_1.matchType(t, _anyType => is("defined"), _nullType => is("is_null"), _boolType => is("is_bool"), _integerType => is("is_integer"), _doubleType => is("is_float"), _stringType => is("is_string"), arrayType => {
321
+ is("is_array");
322
+ this.emitLine("array_walk(", scopeAttrName, ", function(", scopeAttrName, "_v) {");
323
+ this.indent(() => {
324
+ this.phpValidate(className, arrayType.items, attrName, `${scopeAttrName}_v`);
325
+ });
326
+ this.emitLine("});");
327
+ }, _classType => {
328
+ this.emitLine(scopeAttrName, "->validate();");
329
+ }, mapType => {
330
+ this.emitLine("foreach (", scopeAttrName, " as $k => $v) {");
331
+ this.indent(() => {
332
+ this.phpValidate(className, mapType.values, attrName, "$v");
333
+ });
334
+ this.emitLine("}");
335
+ }, enumType => {
336
+ this.emitLine(this.phpType(false, enumType), "::to(", scopeAttrName, ");");
337
+ }, unionType => {
338
+ const nullable = TypeUtils_1.nullableFromUnion(unionType);
339
+ if (nullable !== null) {
340
+ this.emitBlock(["if (!is_null(", scopeAttrName, "))"], () => {
341
+ this.phpValidate(className, nullable, attrName, scopeAttrName);
342
+ });
343
+ return;
344
+ }
345
+ throw Error("not implemented");
346
+ }, transformedStringType => {
347
+ if (transformedStringType.kind === "date-time") {
348
+ this.transformDateTime(className, attrName, [scopeAttrName]);
349
+ return;
350
+ }
351
+ throw Error(`transformedStringType.kind === ${transformedStringType.kind}`);
352
+ });
353
+ }
354
+ emitFromMethod(names, p, className, _name, desc) {
355
+ this.emitLine("/**");
356
+ if (desc !== undefined) {
357
+ this.emitLine(" * ", desc);
358
+ this.emitLine(" *");
359
+ }
360
+ // this.emitLine(" * @param ", this.phpType(false, p.type, false, "", "|null"));
361
+ this.emitLine(" * @param ", this.phpConvertType(className, p.type), " $value");
362
+ this.emitLine(" * @throws Exception");
363
+ this.emitLine(" * @return ", this.phpType(false, p.type));
364
+ this.emitLine(" */");
365
+ this.emitBlock([
366
+ "public static function ",
367
+ names.from,
368
+ "(",
369
+ this.phpConvertType(className, p.type),
370
+ " $value): ",
371
+ this.phpType(false, p.type)
372
+ ], () => {
373
+ this.phpFromObjConvert(className, p.type, ["return "], [`$value`]);
374
+ // this.emitLine("return $ret;");
375
+ });
376
+ }
377
+ emitToMethod(names, p, className, name, desc) {
378
+ this.emitLine("/**");
379
+ if (desc !== undefined) {
380
+ this.emitLine(" * ", desc);
381
+ this.emitLine(" *");
382
+ }
383
+ this.emitLine(" * @throws Exception");
384
+ this.emitLine(" * @return ", this.phpConvertType(className, p.type));
385
+ this.emitLine(" */");
386
+ this.emitBlock(["public function ", names.to, "(): ", this.phpConvertType(className, p.type)], () => {
387
+ this.emitBlock(["if (", className, "::", names.validate, "($this->", name, ")) "], () => {
388
+ this.phpToObjConvert(className, p.type, ["return "], ["$this->", name]);
389
+ });
390
+ this.emitLine("throw new Exception('never get to this ", className, "::", name, "');");
391
+ });
392
+ }
393
+ emitValidateMethod(names, p, className, name, desc) {
394
+ this.emitLine("/**");
395
+ if (desc !== undefined) {
396
+ this.emitLine(" * ", desc);
397
+ this.emitLine(" *");
398
+ }
399
+ this.emitLine(" * @param ", this.phpType(false, p.type, false, "", "|null"));
400
+ this.emitLine(" * @return bool");
401
+ this.emitLine(" * @throws Exception");
402
+ this.emitLine(" */");
403
+ this.emitBlock(["public static function ", names.validate, "(", this.phpType(false, p.type), " $value): bool"], () => {
404
+ this.phpValidate(className, p.type, name, `$value`);
405
+ this.emitLine("return true;");
406
+ });
407
+ }
408
+ emitGetMethod(names, p, className, name, desc) {
409
+ if (this._options.withGet) {
410
+ this.emitLine("/**");
411
+ if (desc !== undefined) {
412
+ this.emitLine(" * ", desc);
413
+ this.emitLine(" *");
414
+ }
415
+ if (!this._options.fastGet) {
416
+ this.emitLine(` * @throws Exception`);
417
+ }
418
+ const rendered = this.phpType(false, p.type);
419
+ this.emitLine(" * @return ", rendered);
420
+ this.emitLine(" */");
421
+ this.emitBlock(["public function ", names.getter, "(): ", rendered], () => {
422
+ if (!this._options.fastGet) {
423
+ this.emitBlock(["if (", className, "::", names.validate, "($this->", name, ")) "], () => {
424
+ this.emitLine("return $this->", name, ";");
425
+ });
426
+ this.emitLine("throw new Exception('never get to ", names.getter, " ", className, "::", name, "');");
427
+ }
428
+ else {
429
+ this.emitLine("return $this->", name, ";");
430
+ }
431
+ });
432
+ }
433
+ }
434
+ emitSetMethod(names, p, className, name, desc) {
435
+ if (this._options.withSet) {
436
+ this.emitLine("/**");
437
+ if (desc !== undefined) {
438
+ this.emitLine(" * ", desc);
439
+ this.emitLine(" *");
440
+ }
441
+ this.emitLine(" * @param ", this.phpType(false, p.type, false, "", "|null"));
442
+ this.emitLine(` * @throws Exception`);
443
+ this.emitLine(" */");
444
+ this.emitBlock(["public function ", names.setter, "(", this.phpType(false, p.type), " $value)"], () => {
445
+ this.emitBlock(["if (", className, "::", names.validate, "($value)) "], () => {
446
+ this.emitLine("$this->", name, " = $value;");
447
+ });
448
+ });
449
+ }
450
+ }
451
+ emitSampleMethod(names, p, className, name, desc, idx) {
452
+ if (this._options.withGet) {
453
+ this.emitLine("/**");
454
+ if (desc !== undefined) {
455
+ this.emitLine(" * ", desc);
456
+ this.emitLine(" *");
457
+ }
458
+ const rendered = this.phpType(false, p.type);
459
+ this.emitLine(" * @return ", rendered);
460
+ this.emitLine(" */");
461
+ this.emitBlock(["public static function ", names.sample, "(): ", rendered], () => {
462
+ this.phpSampleConvert(className, p.type, ["return "], [name], idx, ";");
463
+ });
464
+ }
465
+ }
466
+ emitClassDefinition(c, className) {
467
+ this.emitFileHeader(className, []);
468
+ this.emitBlock(["class ", className], () => {
469
+ this.forEachClassProperty(c, "none", (name, jsonName, p) => {
470
+ this.emitLine("private ", this.phpType(false, p.type), " $", name, "; // json:", jsonName, " ", p.type.isNullable ? "Optional" : "Required");
471
+ });
472
+ this.ensureBlankLine();
473
+ const comments = [];
474
+ const args = [];
475
+ let prefix = "";
476
+ this.forEachClassProperty(c, "none", (name, __, p) => {
477
+ args.push([prefix, this.phpType(false, p.type), " $", name]);
478
+ prefix = ", ";
479
+ comments.push([" * @param ", this.phpType(false, p.type, false, "", "|null"), " $", name, "\n"]);
480
+ });
481
+ this.emitBlock(["/**\n", ...comments, " */\n", "public function __construct(", ...args, ")"], () => {
482
+ this.forEachClassProperty(c, "none", name => {
483
+ this.emitLine("$this->", name, " = $", name, ";");
484
+ });
485
+ });
486
+ let idx = 31;
487
+ this.forEachClassProperty(c, "leading-and-interposing", (name, jsonName, p) => {
488
+ const desc = this.descriptionForClassProperty(c, jsonName);
489
+ const names = Support_1.defined(this._gettersAndSettersForPropertyName.get(name));
490
+ this.ensureBlankLine();
491
+ this.emitFromMethod(names, p, className, name, desc);
492
+ this.ensureBlankLine();
493
+ this.emitToMethod(names, p, className, name, desc);
494
+ this.ensureBlankLine();
495
+ this.emitValidateMethod(names, p, className, name, desc);
496
+ this.ensureBlankLine();
497
+ this.emitGetMethod(names, p, className, name, desc);
498
+ this.ensureBlankLine();
499
+ this.emitSetMethod(names, p, className, name, desc);
500
+ this.ensureBlankLine();
501
+ this.emitSampleMethod(names, p, className, name, desc, idx++);
502
+ });
503
+ this.ensureBlankLine();
504
+ this.emitBlock(["/**\n", ` * @throws Exception\n`, ` * @return bool\n`, " */\n", "public function validate(): bool"], () => {
505
+ let lines = [];
506
+ let p = "return ";
507
+ this.forEachClassProperty(c, "none", (name, _jsonName, _p) => {
508
+ const names = Support_1.defined(this._gettersAndSettersForPropertyName.get(name));
509
+ lines.push([p, className, "::", names.validate, "($this->", name, ")"]);
510
+ p = "|| ";
511
+ });
512
+ lines.forEach((line, jdx) => {
513
+ this.emitLine(...line, lines.length === jdx + 1 ? ";" : "");
514
+ });
515
+ });
516
+ this.ensureBlankLine();
517
+ this.emitBlock([
518
+ "/**\n",
519
+ ` * @return stdClass\n`,
520
+ ` * @throws Exception\n`,
521
+ " */\n",
522
+ "public function to(): stdClass "
523
+ ], () => {
524
+ this.emitLine("$out = new stdClass();");
525
+ this.forEachClassProperty(c, "none", (name, jsonName) => {
526
+ const names = Support_1.defined(this._gettersAndSettersForPropertyName.get(name));
527
+ this.emitLine("$out->{'", jsonName, "'} = $this->", names.to, "();");
528
+ });
529
+ this.emitLine("return $out;");
530
+ });
531
+ this.ensureBlankLine();
532
+ this.emitBlock([
533
+ "/**\n",
534
+ ` * @param stdClass $obj\n`,
535
+ ` * @return `,
536
+ className,
537
+ `\n`,
538
+ ` * @throws Exception\n`,
539
+ " */\n",
540
+ "public static function from(stdClass $obj): ",
541
+ className
542
+ ], () => {
543
+ if (this._options.fastGet) {
544
+ this.forEachClassProperty(c, "none", name => {
545
+ const names = Support_1.defined(this._gettersAndSettersForPropertyName.get(name));
546
+ this.emitLine(className, "::", names.validate, "($this->", name, ", true);");
547
+ });
548
+ }
549
+ this.emitLine("return new ", className, "(");
550
+ let comma = " ";
551
+ this.forEachClassProperty(c, "none", (name, jsonName) => {
552
+ const names = Support_1.defined(this._gettersAndSettersForPropertyName.get(name));
553
+ this.emitLine(comma, className, "::", names.from, "($obj->{'", jsonName, "'})");
554
+ comma = ",";
555
+ });
556
+ this.emitLine(");");
557
+ });
558
+ this.ensureBlankLine();
559
+ this.emitBlock(["/**\n", " * @return ", className, "\n", " */\n", "public static function sample(): ", className], () => {
560
+ this.emitLine("return new ", className, "(");
561
+ let comma = " ";
562
+ this.forEachClassProperty(c, "none", name => {
563
+ const names = Support_1.defined(this._gettersAndSettersForPropertyName.get(name));
564
+ this.emitLine(comma, className, "::", names.sample, "()");
565
+ comma = ",";
566
+ });
567
+ this.emitLine(");");
568
+ });
569
+ });
570
+ this.finishFile();
571
+ }
572
+ emitUnionAttributes(_u, _unionName) {
573
+ // empty
574
+ }
575
+ emitUnionSerializer(_u, _unionName) {
576
+ // empty
577
+ }
578
+ emitUnionDefinition(_u, _unionName) {
579
+ throw Error("emitUnionDefinition not implemented");
580
+ }
581
+ emitEnumSerializationAttributes(_e) {
582
+ // Empty
583
+ }
584
+ emitEnumDeserializationAttributes(_e) {
585
+ // Empty
586
+ }
587
+ emitEnumDefinition(e, enumName) {
588
+ this.emitFileHeader(enumName, []);
589
+ this.emitDescription(this.descriptionForType(e));
590
+ const caseNames = [];
591
+ caseNames.push(";");
592
+ const enumSerdeType = "string";
593
+ this.emitBlock(["class ", enumName], () => {
594
+ this.forEachEnumCase(e, "none", (name, _jsonName) => {
595
+ this.emitLine("public static ", enumName, " $", name, ";");
596
+ });
597
+ this.emitBlock("public static function init()", () => {
598
+ this.forEachEnumCase(e, "none", (name, jsonName) => {
599
+ this.emitLine(enumName, "::$", name, " = new ", enumName, "('", jsonName, "');");
600
+ });
601
+ });
602
+ this.emitLine("private ", enumSerdeType, " $enum;");
603
+ this.emitBlock(["public function __construct(", enumSerdeType, " $enum)"], () => {
604
+ this.emitLine("$this->enum = $enum;");
605
+ });
606
+ this.ensureBlankLine();
607
+ this.emitEnumSerializationAttributes(e);
608
+ this.emitBlock([
609
+ "/**\n",
610
+ ` * @param `,
611
+ enumName,
612
+ `\n`,
613
+ ` * @return `,
614
+ enumSerdeType,
615
+ `\n`,
616
+ ` * @throws Exception\n`,
617
+ " */\n",
618
+ "public static function to(",
619
+ enumName,
620
+ " $obj): ",
621
+ enumSerdeType
622
+ ], () => {
623
+ this.emitLine("switch ($obj->enum) {");
624
+ this.indent(() => {
625
+ this.forEachEnumCase(e, "none", (name, jsonName) => {
626
+ // Todo String or Number
627
+ this.emitLine("case ", enumName, "::$", name, "->enum: return '", exports.stringEscape(jsonName), "';");
628
+ });
629
+ });
630
+ this.emitLine("}");
631
+ this.emitLine("throw new Exception('the give value is not an enum-value.');");
632
+ });
633
+ this.ensureBlankLine();
634
+ this.emitEnumDeserializationAttributes(e);
635
+ this.emitBlock([
636
+ "/**\n",
637
+ ` * @param mixed\n`,
638
+ ` * @return `,
639
+ enumName,
640
+ "\n",
641
+ ` * @throws Exception\n`,
642
+ " */\n",
643
+ "public static function from($obj): ",
644
+ enumName
645
+ ], () => {
646
+ this.emitLine("switch ($obj) {");
647
+ this.indent(() => {
648
+ this.forEachEnumCase(e, "none", (name, jsonName) => {
649
+ // Todo String or Enum
650
+ this.emitLine("case '", exports.stringEscape(jsonName), "': return ", enumName, "::$", name, ";");
651
+ });
652
+ });
653
+ this.emitLine("}");
654
+ this.emitLine('throw new Exception("Cannot deserialize ', enumName, '");');
655
+ });
656
+ this.ensureBlankLine();
657
+ this.emitBlock(["/**\n", ` * @return `, enumName, "\n", " */\n", "public static function sample(): ", enumName], () => {
658
+ const lines = [];
659
+ this.forEachEnumCase(e, "none", name => {
660
+ lines.push([enumName, "::$", name]);
661
+ });
662
+ this.emitLine("return ", lines[0], ";");
663
+ });
664
+ });
665
+ this.emitLine(enumName, "::init();");
666
+ this.finishFile();
667
+ }
668
+ emitSourceStructure(givenFilename) {
669
+ this.emitLine("<?php");
670
+ this.forEachNamedType("leading-and-interposing", (c, n) => this.emitClassDefinition(c, n), (e, n) => this.emitEnumDefinition(e, n), (u, n) => this.emitUnionDefinition(u, n));
671
+ if (this._options.withClosing) {
672
+ this.emitLine("?>");
673
+ }
674
+ super.finishFile(Support_1.defined(givenFilename));
675
+ }
676
+ }
677
+ exports.PhpRenderer = PhpRenderer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quicktype-core",
3
- "version": "7.0.28",
3
+ "version": "7.0.30",
4
4
  "description": "The quicktype engine as a library",
5
5
  "license": "Apache-2.0",
6
6
  "main": "dist/index.js",
@@ -45,6 +45,6 @@
45
45
  "fs": false
46
46
  },
47
47
  "config": {
48
- "commit": "a65d813cd2fc76f1ac4bd6731b05ebe3d68fdf2d"
48
+ "commit": "3cbae3cad6db6005cefcdbac953be37504c0d952"
49
49
  }
50
50
  }