-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresources.ts
More file actions
815 lines (748 loc) · 31.8 KB
/
Copy pathresources.ts
File metadata and controls
815 lines (748 loc) · 31.8 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import type { Service, Operation, Model, EmitterContext, GeneratedFile, ResolvedOperation } from '@workos/oagen';
import { planOperation, toCamelCase, toPascalCase } from '@workos/oagen';
import { mapTypeRef, mapTypeRefForPHPDoc } from './type-map.js';
import { className, fieldName, resolveMethodName } from './naming.js';
import { isListWrapperModel } from './models.js';
import {
groupByMount,
buildResolvedLookup,
lookupResolved,
getOpDefaults,
getOpInferFromClient,
collectGroupedParamNames,
collectBodyFieldTypes,
} from '../shared/resolved-ops.js';
import { generateWrapperMethods } from './wrappers.js';
import { phpDocComment } from './utils.js';
import { buildPhpPathExpression } from './path-expression.js';
/**
* Resolve the resource class name for a service (used by client.ts).
*/
export function resolveResourceClassName(service: Service, ctx: EmitterContext): string {
for (const r of ctx.resolvedOperations ?? []) {
if (r.service.name === service.name) return r.mountOn;
}
return className(service.name);
}
/**
* Generate PHP resource class files from IR services.
* Uses mount-based grouping: one resource file per mount target.
*/
export function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {
if (services.length === 0) return [];
const files: GeneratedFile[] = [];
const modelMap = new Map(ctx.spec.models.map((m) => [m.name, m]));
// Group operations by mount target
const mountGroups = groupByMount(ctx);
const entries: Array<{ name: string; operations: Operation[] }> =
mountGroups.size > 0
? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))
: services.map((s) => ({ name: className(s.name), operations: s.operations }));
for (const { name: mountName, operations } of entries) {
if (operations.length === 0) continue;
const resourceName = className(mountName);
const mergedService: Service = { name: mountName, operations };
const lines: string[] = [];
// No <?php here — the file header from fileHeader() provides it
lines.push(`namespace ${ctx.namespacePascal}\\Service;`);
lines.push('');
// Build resolved lookup early — used by both imports and method generation
const resolvedLookup = buildResolvedLookup(ctx);
// Collect imports
const imports = collectImports(mergedService, ctx, resolvedLookup);
for (const imp of imports) {
lines.push(`use ${imp};`);
}
if (imports.length > 0) lines.push('');
lines.push(`class ${resourceName}`);
lines.push('{');
lines.push(' public function __construct(');
lines.push(` private readonly \\${ctx.namespacePascal}\\HttpClient $client,`);
lines.push(' ) {');
lines.push(' }');
// Track emitted method names to avoid duplicates
const emittedMethods = new Set<string>();
for (const op of operations) {
const method = resolveMethodName(op, mergedService, ctx);
if (emittedMethods.has(method)) continue;
emittedMethods.add(method);
const resolved = lookupResolved(op, resolvedLookup);
// When wrappers exist, skip the base method and only emit wrappers
if (resolved?.wrappers && resolved.wrappers.length > 0) {
lines.push(...generateWrapperMethods(resolved, ctx));
} else {
lines.push('');
generateMethod(lines, op, mergedService, ctx, modelMap, resolved ?? undefined);
}
}
lines.push('}');
files.push({
path: `lib/Service/${resourceName}.php`,
content: lines.join('\n'),
overwriteExisting: true,
});
// Generate variant class files for operations with parameter groups
for (const op of operations) {
if ((op.parameterGroups?.length ?? 0) > 0) {
files.push(...generateParameterGroupFiles(op, ctx, modelMap));
}
}
}
return files;
}
/**
* Check if an operation is a redirect endpoint that should construct a URL
* instead of making an HTTP request.
*
* Detection: GET endpoints with no response body (primitive unknown) and query
* params are redirect endpoints (e.g., SSO/OAuth authorize and logout flows).
* Also respects an explicit urlBuilder flag on the resolved operation and
* catches endpoints with 302 success responses.
*/
export function isRedirectEndpoint(op: Operation, resolvedOp?: ResolvedOperation): boolean {
if ((resolvedOp as any)?.urlBuilder) return true;
if ((op as any).successResponses?.some((r: any) => r.statusCode >= 300 && r.statusCode < 400)) return true;
if (
op.httpMethod === 'get' &&
op.response.kind === 'primitive' &&
(op.response as any).type === 'unknown' &&
op.queryParams.length > 0
) {
return true;
}
return false;
}
// ---------------------------------------------------------------------------
// Mutually-exclusive parameter group support
// ---------------------------------------------------------------------------
/** PHP class name for a parameter group variant (e.g. ParentResourceById). */
function groupVariantClassName(groupName: string, variantName: string): string {
return `${className(groupName)}${className(variantName)}`;
}
/**
* Derive a short PHP property name for a parameter within a variant class.
* Strips the group name prefix when present to avoid stuttering
* (e.g. parent_resource_id in group parent_resource -> id -> camelCase).
*/
export function deriveVariantFieldName(paramName: string, groupName: string): string {
const prefix = groupName + '_';
const stripped = paramName.startsWith(prefix) ? paramName.slice(prefix.length) : paramName;
return fieldName(stripped);
}
/**
* Generate PHP variant class files for all parameter groups on an operation.
* Each variant becomes a simple PHP class with readonly constructor properties.
*/
function generateParameterGroupFiles(
op: Operation,
ctx: EmitterContext,
modelMap: Map<string, Model>,
): GeneratedFile[] {
const files: GeneratedFile[] = [];
const bodyFieldTypes = collectBodyFieldTypes(op, [...modelMap.values()]);
for (const group of op.parameterGroups ?? []) {
for (const variant of group.variants) {
const variantClass = groupVariantClassName(group.name, variant.name);
const lines: string[] = [];
lines.push(`namespace ${ctx.namespacePascal}\\Service;`);
lines.push('');
lines.push(`class ${variantClass}`);
lines.push('{');
lines.push(' public function __construct(');
for (let i = 0; i < variant.parameters.length; i++) {
const param = variant.parameters[i];
const effectiveType = bodyFieldTypes.get(param.name) ?? param.type;
const phpType = mapTypeRef(effectiveType, { qualified: true });
const phpName = deriveVariantFieldName(param.name, group.name);
const comma = ',';
lines.push(` public readonly ${phpType} $${phpName}${comma}`);
}
lines.push(' ) {');
lines.push(' }');
lines.push('}');
files.push({
path: `lib/Service/${variantClass}.php`,
content: lines.join('\n'),
overwriteExisting: true,
});
}
}
return files;
}
/**
* Generate instanceof dispatch lines to serialize a grouped parameter
* into a target array ($query or $body) using each variant's wire names.
*/
function generateGroupDispatch(op: Operation, indent: string, target: '$query' | '$body' = '$query'): string[] {
const lines: string[] = [];
for (const group of op.parameterGroups ?? []) {
const phpParamName = fieldName(group.name);
for (let vi = 0; vi < group.variants.length; vi++) {
const variant = group.variants[vi];
const variantClass = groupVariantClassName(group.name, variant.name);
const keyword = vi === 0 ? 'if' : 'elseif';
lines.push(`${indent}${keyword} ($${phpParamName} instanceof ${variantClass}) {`);
for (const param of variant.parameters) {
const phpField = deriveVariantFieldName(param.name, group.name);
lines.push(`${indent} ${target}['${param.name}'] = $${phpParamName}->${phpField};`);
}
lines.push(`${indent}}`);
}
}
return lines;
}
function generateMethod(
lines: string[],
op: Operation,
service: Service,
ctx: EmitterContext,
modelMap: Map<string, Model>,
resolvedOp?: ResolvedOperation,
): void {
const plan = planOperation(op);
const method = resolveMethodName(op, service, ctx);
// Build the set of params hidden from the method signature
// (injected from client config or as constant defaults)
const hiddenParams = new Set<string>([
...Object.keys(getOpDefaults(resolvedOp)),
...getOpInferFromClient(resolvedOp),
]);
const isRedirect = isRedirectEndpoint(op, resolvedOp);
const params = buildMethodParams(op, plan, modelMap, ctx, hiddenParams);
const returnType = isRedirect ? 'string' : getReturnType(plan, ctx);
// PHPDoc block
const docParts: string[] = [];
if (op.description) docParts.push(op.description);
const seenDocParams = new Set<string>();
// @param for path params
for (const p of op.pathParams) {
const docType = mapTypeRefForPHPDoc(p.type);
const phpName = fieldName(p.name);
seenDocParams.add(phpName);
const prefix = p.deprecated ? '(deprecated) ' : '';
let desc = p.description ? ` ${prefix}${p.description}` : p.deprecated ? ' (deprecated)' : '';
if (p.default != null) desc += ` Defaults to ${JSON.stringify(p.default)}.`;
docParts.push(`@param ${docType} $${phpName}${desc}`);
}
// @param for body fields
const groupedParamNames = collectGroupedParamNames(op);
if (plan.hasBody && op.requestBody?.kind === 'model') {
const bodyModel = modelMap.get(op.requestBody.name);
if (bodyModel) {
const bodyParamMap = buildBodyParamMap(op, bodyModel);
for (const field of bodyModel.fields) {
if (hiddenParams.has(field.name)) continue;
if (groupedParamNames.has(field.name)) continue;
const docType = mapTypeRefForPHPDoc(field.type);
const phpName = bodyParamMap.get(field.name) ?? fieldName(field.name);
if (seenDocParams.has(phpName)) continue;
seenDocParams.add(phpName);
const nullSuffix = !field.required && !docType.endsWith('|null') ? '|null' : '';
const prefix = field.deprecated ? '(deprecated) ' : '';
const desc = field.description ? ` ${prefix}${field.description}` : field.deprecated ? ' (deprecated)' : '';
docParts.push(`@param ${docType}${nullSuffix} $${phpName}${desc}`);
}
}
}
// @param for parameter groups (union-typed)
for (const group of op.parameterGroups ?? []) {
const phpName = fieldName(group.name);
if (seenDocParams.has(phpName)) continue;
seenDocParams.add(phpName);
const variantTypes = group.variants.map((v) => groupVariantClassName(group.name, v.name));
const unionDocType = variantTypes.join('|');
const nullPrefix = group.optional ? 'null|' : '';
docParts.push(`@param ${nullPrefix}${unionDocType} $${phpName}`);
}
// @param for query params (skip grouped params — they appear as group union params)
for (const q of op.queryParams) {
if (hiddenParams.has(q.name)) continue;
if (groupedParamNames.has(q.name)) continue;
const docType = mapTypeRefForPHPDoc(q.type);
const phpName = fieldName(q.name);
if (seenDocParams.has(phpName)) continue;
seenDocParams.add(phpName);
// order params with enum defaults are non-nullable (they default to Desc, not null)
const isNonNullableOrder = q.name === 'order' && q.type.kind === 'enum';
const nullSuffix = !q.required && !isNonNullableOrder && !docType.endsWith('|null') ? '|null' : '';
const prefix = q.deprecated ? '(deprecated) ' : '';
let desc = q.description ? ` ${prefix}${q.description}` : q.deprecated ? ' (deprecated)' : '';
if (q.default != null) desc += ` Defaults to ${JSON.stringify(q.default)}.`;
docParts.push(`@param ${docType}${nullSuffix} $${phpName}${desc}`);
}
// @return -- use generic annotation for paginated responses
if (plan.isPaginated && op.pagination?.itemType.kind === 'model') {
const itemType = op.pagination.itemType;
const itemModel = ctx.spec.models.find((m) => m.name === itemType.name);
let resolvedName = itemType.name;
if (itemModel && isListWrapperModel(itemModel)) {
const dataField = itemModel.fields.find((f) => f.name === 'data');
if (dataField?.type.kind === 'array' && dataField.type.items.kind === 'model') {
resolvedName = dataField.type.items.name;
}
}
const itemClass = className(resolvedName);
docParts.push(
`@return \\${ctx.namespacePascal}\\PaginatedResponse<\\${ctx.namespacePascal}\\Resource\\${itemClass}>`,
);
} else {
docParts.push(`@return ${returnType}`);
}
// @throws — scope to what the method actually calls
if (!isRedirect) {
// HTTP methods can throw any WorkOSException (config, transport, API response)
docParts.push(`@throws \\${ctx.namespacePascal}\\Exception\\WorkOSException`);
} else if (getOpInferFromClient(resolvedOp).length > 0) {
// Redirect endpoints that inject client fields can throw ConfigurationException
docParts.push(`@throws \\${ctx.namespacePascal}\\Exception\\ConfigurationException`);
}
// Redirect endpoints with no inferFromClient: buildUrl() is pure, no @throws
if (op.deprecated) docParts.push('@deprecated');
lines.push(...phpDocComment(docParts.join('\n'), 4));
// Method signature
lines.push(` public function ${method}(`);
for (let i = 0; i < params.length; i++) {
const comma = i < params.length - 1 ? ',' : ',';
lines.push(` ${params[i]}${comma}`);
}
lines.push(` ): ${returnType} {`);
// Method body
const httpMethod = op.httpMethod.toUpperCase();
const path = buildPathString(op);
if (isRedirect) {
// Redirect endpoint: construct URL client-side instead of making HTTP request
const queryLines = buildQueryArray(op, hiddenParams);
const hasDefaults = Object.keys(getOpDefaults(resolvedOp)).length > 0;
const hasInferred = getOpInferFromClient(resolvedOp).length > 0;
const hasGroups = (op.parameterGroups?.length ?? 0) > 0;
const needsQuery = queryLines.length > 0 || hasDefaults || hasInferred || hasGroups;
if (needsQuery) {
const groupedParams = collectGroupedParamNames(op);
const hasOptionalQuery = op.queryParams.some(
(q) => !q.required && !hiddenParams.has(q.name) && !groupedParams.has(q.name),
);
if (hasOptionalQuery) {
lines.push(' $query = array_filter([');
} else if (queryLines.length > 0) {
lines.push(' $query = [');
} else {
lines.push(' $query = [');
}
for (const q of queryLines) {
lines.push(` ${q}`);
}
// Inject constant defaults
for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {
lines.push(` '${key}' => ${phpLiteral(value)},`);
}
if (hasOptionalQuery) {
lines.push(' ], fn ($v) => $v !== null);');
} else {
lines.push(' ];');
}
// Inject fields from client config
for (const clientField of getOpInferFromClient(resolvedOp)) {
lines.push(` $query['${clientField}'] = ${clientFieldExpression(clientField)};`);
}
// Inject parameter group dispatch (instanceof checks)
lines.push(...generateGroupDispatch(op, ' '));
lines.push(` return $this->client->buildUrl(path: ${path}, query: $query, options: $options);`);
} else {
lines.push(` return $this->client->buildUrl(path: ${path}, query: [], options: $options);`);
}
} else if (plan.isPaginated) {
const queryLines = buildQueryArray(op);
const hasGroups = (op.parameterGroups?.length ?? 0) > 0;
const needsQuery = queryLines.length > 0 || hasGroups;
if (needsQuery) {
if (queryLines.length > 0) {
lines.push(' $query = array_filter([');
for (const q of queryLines) {
lines.push(` ${q}`);
}
lines.push(' ], fn ($v) => $v !== null);');
} else {
lines.push(' $query = [];');
}
// Inject parameter group dispatch (instanceof checks)
lines.push(...generateGroupDispatch(op, ' '));
}
lines.push(' return $this->client->requestPage(');
lines.push(` method: '${httpMethod}',`);
lines.push(` path: ${path},`);
if (needsQuery) {
lines.push(' query: $query,');
}
const itemType = op.pagination?.itemType;
if (itemType?.kind === 'model') {
// Unwrap list wrapper models to the inner item type
const itemModel = ctx.spec.models.find((m) => m.name === itemType.name);
let resolvedName = itemType.name;
if (itemModel && isListWrapperModel(itemModel)) {
const dataField = itemModel.fields.find((f) => f.name === 'data');
if (dataField?.type.kind === 'array' && dataField.type.items.kind === 'model') {
resolvedName = dataField.type.items.name;
}
}
const itemClass = className(resolvedName);
lines.push(` modelClass: ${itemClass}::class,`);
}
lines.push(' options: $options,');
lines.push(' );');
} else if (plan.isDelete) {
// Build body if the operation has a request body (e.g., DELETE with criteria)
if (plan.hasBody) {
const bodyModel = op.requestBody?.kind === 'model' ? modelMap.get(op.requestBody.name) : null;
const bodyParamMap = buildBodyParamMap(op, bodyModel ?? null);
const deleteGroupedParams = collectGroupedParamNames(op);
const visibleFields =
bodyModel?.fields.filter((f) => !hiddenParams.has(f.name) && !deleteGroupedParams.has(f.name)) ?? [];
const hasOptionalFields = visibleFields.some((f) => !f.required);
if (hasOptionalFields) {
lines.push(' $body = array_filter([');
} else {
lines.push(' $body = [');
}
for (const field of visibleFields) {
const phpName = bodyParamMap.get(field.name) ?? fieldName(field.name);
const nullsafe = field.required ? '' : '?';
const valueExpr = isEnumType(field.type) ? `$${phpName}${nullsafe}->value` : `$${phpName}`;
lines.push(` '${field.name}' => ${valueExpr},`);
}
// Inject constant defaults
for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {
lines.push(` '${key}' => ${phpLiteral(value)},`);
}
if (hasOptionalFields) {
lines.push(' ], fn ($v) => $v !== null);');
} else {
lines.push(' ];');
}
// Inject fields from client config
for (const clientField of getOpInferFromClient(resolvedOp)) {
lines.push(` $body['${clientField}'] = ${clientFieldExpression(clientField)};`);
}
// Inject parameter group dispatch into body
if ((op.parameterGroups?.length ?? 0) > 0) {
lines.push(...generateGroupDispatch(op, ' ', '$body'));
}
}
// Build query params if present
const deleteQueryLines = buildQueryArray(op);
if (deleteQueryLines.length > 0) {
lines.push(' $query = array_filter([');
for (const q of deleteQueryLines) {
lines.push(` ${q}`);
}
lines.push(' ], fn ($v) => $v !== null);');
}
lines.push(' $this->client->request(');
lines.push(` method: '${httpMethod}',`);
lines.push(` path: ${path},`);
if (plan.hasBody) {
lines.push(' body: $body,');
}
if (deleteQueryLines.length > 0) {
lines.push(' query: $query,');
}
lines.push(' options: $options,');
lines.push(' );');
} else if (plan.hasBody) {
const bodyModel = op.requestBody?.kind === 'model' ? modelMap.get(op.requestBody.name) : null;
const bodyParamMap = buildBodyParamMap(op, bodyModel ?? null);
const bodyGroupedParams = collectGroupedParamNames(op);
const visibleFields =
bodyModel?.fields.filter((f) => !hiddenParams.has(f.name) && !bodyGroupedParams.has(f.name)) ?? [];
const hasOptionalFields = visibleFields.some((f) => !f.required);
if (hasOptionalFields) {
lines.push(' $body = array_filter([');
} else {
lines.push(' $body = [');
}
for (const field of visibleFields) {
const phpName = bodyParamMap.get(field.name) ?? fieldName(field.name);
const nullsafe = field.required ? '' : '?';
const valueExpr = isEnumType(field.type) ? `$${phpName}${nullsafe}->value` : `$${phpName}`;
lines.push(` '${field.name}' => ${valueExpr},`);
}
// Inject constant defaults
for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {
lines.push(` '${key}' => ${phpLiteral(value)},`);
}
if (hasOptionalFields) {
lines.push(' ], fn ($v) => $v !== null);');
} else {
lines.push(' ];');
}
// Inject fields from client config
for (const clientField of getOpInferFromClient(resolvedOp)) {
lines.push(` $body['${clientField}'] = ${clientFieldExpression(clientField)};`);
}
// Inject parameter group dispatch into body so sensitive fields
// (passwords, role slugs) never leak into the URL query string.
if ((op.parameterGroups?.length ?? 0) > 0) {
lines.push(...generateGroupDispatch(op, ' ', '$body'));
}
lines.push(' $response = $this->client->request(');
lines.push(` method: '${httpMethod}',`);
lines.push(` path: ${path},`);
lines.push(' body: $body,');
lines.push(' options: $options,');
lines.push(' );');
if (plan.responseModelName) {
const responseClass = className(plan.responseModelName);
if (op.response.kind === 'array') {
lines.push(` return array_map(fn ($item) => ${responseClass}::fromArray($item), $response);`);
} else {
lines.push(` return ${responseClass}::fromArray($response);`);
}
} else {
lines.push(' return $response;');
}
} else {
const queryLines = buildQueryArray(op, hiddenParams);
const hasDefaults = Object.keys(getOpDefaults(resolvedOp)).length > 0;
const hasInferred = getOpInferFromClient(resolvedOp).length > 0;
const hasGroups = (op.parameterGroups?.length ?? 0) > 0;
const needsQuery = queryLines.length > 0 || hasDefaults || hasInferred || hasGroups;
if (needsQuery) {
const groupedParams = collectGroupedParamNames(op);
const hasOptionalQuery = op.queryParams.some(
(q) => !q.required && !hiddenParams.has(q.name) && !groupedParams.has(q.name),
);
if (hasOptionalQuery) {
lines.push(' $query = array_filter([');
} else if (queryLines.length > 0) {
lines.push(' $query = [');
} else {
lines.push(' $query = [');
}
for (const q of queryLines) {
lines.push(` ${q}`);
}
// Inject constant defaults
for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {
lines.push(` '${key}' => ${phpLiteral(value)},`);
}
if (hasOptionalQuery) {
lines.push(' ], fn ($v) => $v !== null);');
} else {
lines.push(' ];');
}
// Inject fields from client config
for (const clientField of getOpInferFromClient(resolvedOp)) {
lines.push(` $query['${clientField}'] = ${clientFieldExpression(clientField)};`);
}
// Inject parameter group dispatch (instanceof checks)
lines.push(...generateGroupDispatch(op, ' '));
}
lines.push(' $response = $this->client->request(');
lines.push(` method: '${httpMethod}',`);
lines.push(` path: ${path},`);
if (needsQuery) {
lines.push(' query: $query,');
}
lines.push(' options: $options,');
lines.push(' );');
if (plan.responseModelName) {
const responseClass = className(plan.responseModelName);
if (op.response.kind === 'array') {
lines.push(` return array_map(fn ($item) => ${responseClass}::fromArray($item), $response);`);
} else {
lines.push(` return ${responseClass}::fromArray($response);`);
}
} else {
lines.push(' return $response;');
}
}
lines.push(' }');
}
function buildMethodParams(
op: Operation,
plan: ReturnType<typeof planOperation>,
modelMap: Map<string, Model>,
ctx: EmitterContext,
hiddenParams?: Set<string>,
): string[] {
// Collect all params into required/optional buckets to avoid
// PHP's "required after optional" deprecation.
const required: string[] = [];
const optional: string[] = [];
const usedNames = new Set<string>();
const hidden = hiddenParams ?? new Set();
const groupedParams = collectGroupedParamNames(op);
// Path params (always required)
for (const p of op.pathParams) {
const phpType = mapTypeRef(p.type, { qualified: true });
let phpName = fieldName(p.name);
if (usedNames.has(phpName)) phpName = `path${phpName.charAt(0).toUpperCase()}${phpName.slice(1)}`;
usedNames.add(phpName);
required.push(`${phpType} $${phpName}`);
}
// Body fields
if (plan.hasBody && op.requestBody?.kind === 'model') {
const bodyModel = modelMap.get(op.requestBody.name);
if (bodyModel) {
for (const field of bodyModel.fields) {
if (hidden.has(field.name)) continue;
if (groupedParams.has(field.name)) continue;
const phpType = mapTypeRef(field.type, { qualified: true });
let phpName = fieldName(field.name);
if (usedNames.has(phpName)) {
// Disambiguate body field from path param with same name
phpName = `body${phpName.charAt(0).toUpperCase()}${phpName.slice(1)}`;
if (usedNames.has(phpName)) continue; // truly duplicate, skip
}
usedNames.add(phpName);
if (field.required) {
required.push(`${phpType} $${phpName}`);
} else {
const nullableType = phpType.startsWith('?') ? phpType : `?${phpType}`;
optional.push(`${nullableType} $${phpName} = null`);
}
}
}
}
// Parameter group union-typed params (before individual query params)
for (const group of op.parameterGroups ?? []) {
const phpName = fieldName(group.name);
if (usedNames.has(phpName)) continue;
usedNames.add(phpName);
// PHP 8.0+ union syntax: VariantA|VariantB $paramName
const variantTypes = group.variants.map((v) => groupVariantClassName(group.name, v.name));
const unionType = variantTypes.join('|');
if (group.optional) {
optional.push(`null|${unionType} $${phpName} = null`);
} else {
required.push(`${unionType} $${phpName}`);
}
}
// Query params (skip grouped params — they are serialized via group dispatch)
for (const q of op.queryParams) {
if (hidden.has(q.name)) continue;
if (groupedParams.has(q.name)) continue;
const phpType = mapTypeRef(q.type, { qualified: true });
let phpName = fieldName(q.name);
if (usedNames.has(phpName)) continue;
usedNames.add(phpName);
if (q.required) {
required.push(`${phpType} $${phpName}`);
} else if (q.name === 'order') {
// Hardcode order default to desc for pagination consistency
if (q.type.kind === 'enum') {
const enumType = mapTypeRef(q.type, { qualified: true });
const caseName = toPascalCase('desc');
optional.push(`${enumType} $${phpName} = ${enumType}::${caseName}`);
} else {
const nullableType = phpType.startsWith('?') ? phpType : `?${phpType}`;
optional.push(`${nullableType} $${phpName} = 'desc'`);
}
} else {
const nullableType = phpType.startsWith('?') ? phpType : `?${phpType}`;
optional.push(`${nullableType} $${phpName} = null`);
}
}
// RequestOptions (always last, always optional)
optional.push(`?\\${ctx.namespacePascal}\\RequestOptions $options = null`);
return [...required, ...optional];
}
function getReturnType(plan: ReturnType<typeof planOperation>, ctx: EmitterContext): string {
if (plan.isDelete) return 'void';
if (plan.isPaginated) return `\\${ctx.namespacePascal}\\PaginatedResponse`;
if (plan.responseModelName) {
if (plan.operation.response.kind === 'array') {
return 'array';
}
return `\\${ctx.namespacePascal}\\Resource\\${className(plan.responseModelName)}`;
}
return 'mixed';
}
/**
* Build a mapping from wire name to PHP variable name for body fields,
* disambiguating collisions with path param names.
*/
function buildBodyParamMap(op: Operation, bodyModel: Model | null): Map<string, string> {
const map = new Map<string, string>();
if (!bodyModel) return map;
const pathParamNames = new Set(op.pathParams.map((p) => fieldName(p.name)));
for (const field of bodyModel.fields) {
let phpName = fieldName(field.name);
if (pathParamNames.has(phpName)) {
phpName = `body${phpName.charAt(0).toUpperCase()}${phpName.slice(1)}`;
}
map.set(field.name, phpName);
}
return map;
}
function buildPathString(op: Operation): string {
const valueAccessor = new Set<string>();
for (const p of op.pathParams) {
if (p.type.kind === 'enum' || p.type.kind === 'model') valueAccessor.add(p.name);
}
return buildPhpPathExpression(op.path, { valueAccessorParams: valueAccessor });
}
function isEnumType(ref: import('@workos/oagen').TypeRef): boolean {
if (ref.kind === 'enum') return true;
if (ref.kind === 'nullable') return isEnumType(ref.inner);
return false;
}
function buildQueryArray(op: Operation, hiddenParams?: Set<string>): string[] {
const hidden = hiddenParams ?? new Set();
const groupedParams = collectGroupedParamNames(op);
return op.queryParams
.filter((q) => !hidden.has(q.name) && !groupedParams.has(q.name))
.map((q) => {
const phpName = fieldName(q.name);
if (isEnumType(q.type)) {
// order params with enum defaults are non-nullable (default to Desc, not null)
const isNonNullableOrder = q.name === 'order' && q.type.kind === 'enum';
const nullsafe = q.required || isNonNullableOrder ? '' : '?';
return `'${q.name}' => $${phpName}${nullsafe}->value,`;
}
return `'${q.name}' => $${phpName},`;
});
}
function phpLiteral(value: unknown): string {
if (typeof value === 'string') return `'${value}'`;
if (typeof value === 'number') return String(value);
if (typeof value === 'boolean') return value ? 'true' : 'false';
return 'null';
}
function clientFieldExpression(field: string): string {
switch (field) {
case 'client_id':
return '$this->client->requireClientId()';
case 'client_secret':
return '$this->client->requireApiKey()';
default:
return `$this->client->${toCamelCase(field)}`;
}
}
function collectImports(
service: Service,
ctx: EmitterContext,
resolvedLookup?: Map<string, ResolvedOperation>,
): string[] {
const imports = new Set<string>();
const ns = ctx.namespacePascal;
for (const op of service.operations) {
const plan = planOperation(op);
const resolved = resolvedLookup ? lookupResolved(op, resolvedLookup) : undefined;
if (plan.responseModelName && !plan.isPaginated && !isRedirectEndpoint(op, resolved)) {
imports.add(`${ns}\\Resource\\${className(plan.responseModelName)}`);
}
if (op.pagination?.itemType.kind === 'model') {
// Unwrap list wrapper models to import the inner item type
const itemModel = ctx.spec.models.find((m) => m.name === (op.pagination!.itemType as { name: string }).name);
let resolvedName = (op.pagination!.itemType as { name: string }).name;
if (itemModel && isListWrapperModel(itemModel)) {
const dataField = itemModel.fields.find((f) => f.name === 'data');
if (dataField?.type.kind === 'array' && dataField.type.items.kind === 'model') {
resolvedName = dataField.type.items.name;
}
}
imports.add(`${ns}\\Resource\\${className(resolvedName)}`);
}
}
return [...imports].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
}