|
| 1 | +package generator |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "maps" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "slices" |
| 10 | + |
| 11 | + "github.com/iancoleman/strcase" |
| 12 | +) |
| 13 | + |
| 14 | +// writeServiceAccessors keeps the generated API groups separate from the hand-written client. |
| 15 | +func (g *Generator) writeServiceAccessors() error { |
| 16 | + var services []string |
| 17 | + for _, tagKey := range slices.Sorted(maps.Keys(g.operationsByTag)) { |
| 18 | + if g.shouldIncludeService(tagKey, g.operationsByTag[tagKey]) { |
| 19 | + services = append(services, g.displayTagName(tagKey)) |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + var buf bytes.Buffer |
| 24 | + buf.WriteString("<?php\n\n// Code generated by sumup-php/codegen. DO NOT EDIT.\nnamespace SumUp;\n\n") |
| 25 | + for _, service := range services { |
| 26 | + fmt.Fprintf(&buf, "use SumUp\\Services\\%s;\n", service) |
| 27 | + } |
| 28 | + buf.WriteString("\n/** API groups available through the SumUp client. */\ntrait ServiceAccessors\n{\n") |
| 29 | + for i, service := range services { |
| 30 | + if i > 0 { |
| 31 | + buf.WriteString("\n") |
| 32 | + } |
| 33 | + buf.WriteString(" /**\n") |
| 34 | + fmt.Fprintf(&buf, " * Access the %s API endpoints.\n", service) |
| 35 | + buf.WriteString(" */\n") |
| 36 | + fmt.Fprintf(&buf, " public function %s(): %s\n", strcase.ToLowerCamel(service), service) |
| 37 | + buf.WriteString(" {\n") |
| 38 | + fmt.Fprintf(&buf, " return new %s($this->client, $this->resolveAccessToken());\n", service) |
| 39 | + buf.WriteString(" }\n") |
| 40 | + } |
| 41 | + buf.WriteString("}\n") |
| 42 | + |
| 43 | + filename := filepath.Join(g.cfg.Out, "ServiceAccessors.php") |
| 44 | + if err := os.WriteFile(filename, buf.Bytes(), 0o644); err != nil { |
| 45 | + return fmt.Errorf("write service accessors: %w", err) |
| 46 | + } |
| 47 | + return nil |
| 48 | +} |
0 commit comments