-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsumup.go
More file actions
227 lines (190 loc) · 5.44 KB
/
sumup.go
File metadata and controls
227 lines (190 loc) · 5.44 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
package generator
import (
"bytes"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"github.com/iancoleman/strcase"
)
//nolint:unused // retained for future SumUp class generation
var reservedServiceNames = map[string]struct{}{
"Authorization": {},
}
//nolint:unused // writeSumUpClass is kept for the legacy SumUp SDK surface
func (g *Generator) writeSumUpClass() error {
dir := g.cfg.Out
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return fmt.Errorf("create SumUp directory: %w", err)
}
filename := filepath.Join(dir, "SumUp.php")
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
return fmt.Errorf("open %q: %w", filename, err)
}
defer func() {
_ = f.Close()
}()
services := g.collectServiceDefinitions()
var buf bytes.Buffer
buf.WriteString(`<?php
namespace SumUp;
`)
for _, useStmt := range sumUpUseStatements(services) {
fmt.Fprintf(&buf, "use %s;\n", useStmt)
}
buf.WriteString("\n")
buf.WriteString(`/**
* Class SumUp
*
* @package SumUp
*/
class SumUp
{
/**
* The access token for API authentication.
*
* @var string|null
*/
protected $accessToken;
/**
* @var HttpClientInterface
*/
protected $client;
`)
buf.WriteString(`
/**
* SumUp constructor.
*
* @param string|array|null $configOrApiKey
*
* @throws SDKException
*/
public function __construct($configOrApiKey = null)
{
$config = [];
if (is_string($configOrApiKey) && $configOrApiKey !== '') {
$config['api_key'] = $configOrApiKey;
} elseif (is_array($configOrApiKey)) {
$config = $configOrApiKey;
}
$customHttpClient = $config['client'] ?? null;
if (array_key_exists('client', $config)) {
unset($config['client']);
}
$config = $this->normalizeConfig($config);
if ($customHttpClient instanceof HttpClientInterface) {
$this->client = $customHttpClient;
} else {
$this->client = new CurlClient(
$config['base_uri'],
$config['custom_headers'],
$config['ca_bundle_path']
);
}
if (!empty($config['api_key'])) {
$this->accessToken = $config['api_key'];
} elseif (!empty($config['access_token'])) {
$this->accessToken = $config['access_token'];
}
}
/**
* Returns the default access token.
*
* @return string|null
*/
public function getDefaultAccessToken()
{
return $this->accessToken;
}
/**
* Normalize configuration and apply defaults.
*
* @param array $config
*
* @return array
*
* @throws ConfigurationException
*/
private function normalizeConfig(array $config)
{
$config = array_merge([
'api_key' => null,
'access_token' => null,
'base_uri' => 'https://api.sumup.com',
'custom_headers' => [],
'ca_bundle_path' => null,
], $config);
if ($config['api_key'] === null) {
$config['api_key'] = getenv('SUMUP_API_KEY') ?: null;
}
if ($config['access_token'] === null) {
$config['access_token'] = getenv('SUMUP_ACCESS_TOKEN') ?: null;
}
$headers = is_array($config['custom_headers']) ? $config['custom_headers'] : [];
$headers['Accept'] = 'application/problem+json, application/json';
$headers['User-Agent'] = SdkInfo::getUserAgent();
$config['custom_headers'] = $headers;
return $config;
}
`)
for _, service := range services {
method := strcase.ToLowerCamel(service)
fmt.Fprintf(&buf, " public function %s()\n", method)
buf.WriteString(" {\n")
buf.WriteString(" if (empty($this->accessToken)) {\n")
buf.WriteString(" throw new ConfigurationException('No access token provided');\n")
buf.WriteString(" }\n\n")
fmt.Fprintf(&buf, " return new %s($this->client, $this->accessToken);\n", service)
buf.WriteString(" }\n\n")
}
buf.WriteString(`
}
`)
if _, err := f.Write(buf.Bytes()); err != nil {
return fmt.Errorf("write SumUp file %q: %w", filename, err)
}
return nil
}
//nolint:unused // helper is used when SumUp class generation is re-enabled
func (g *Generator) collectServiceDefinitions() []string {
if len(g.operationsByTag) == 0 {
return nil
}
tagKeys := slices.Collect(maps.Keys(g.operationsByTag))
slices.Sort(tagKeys)
services := make([]string, 0, len(tagKeys))
for _, tagKey := range tagKeys {
if tagKey == sharedTagKey {
continue
}
operations := g.operationsByTag[tagKey]
if len(operations) == 0 {
continue
}
className := g.displayTagName(tagKey)
if _, reserved := reservedServiceNames[className]; reserved {
continue
}
services = append(services, className)
}
return services
}
//nolint:unused // helper for the SumUp class code generation
func sumUpUseStatements(serviceNames []string) []string {
uses := []string{
"SumUp\\Exception\\ConfigurationException",
"SumUp\\Exception\\SDKException",
"SumUp\\HttpClient\\CurlClient",
"SumUp\\HttpClient\\HttpClientInterface",
"SumUp\\SdkInfo",
}
serviceSet := map[string]struct{}{}
for _, name := range serviceNames {
serviceSet[fmt.Sprintf("SumUp\\Services\\%s", name)] = struct{}{}
}
serviceUses := slices.Collect(maps.Keys(serviceSet))
slices.Sort(serviceUses)
return append(uses, serviceUses...)
}