-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathCodegenMutator.php
268 lines (242 loc) · 8.25 KB
/
CodegenMutator.php
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
<?hh // strict
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
namespace Facebook\HackCodegen;
use namespace HH\Lib\Str;
/**
* For a given DormSchema, this class generates code for a class
* that will allow to insert rows in a database.
*/
final class CodegenMutator {
private HackCodegenFactory $codegen;
public function __construct(
private DormSchema $schema,
) {
$this->codegen = new HackCodegenFactory(
(new HackCodegenConfig())->withRootDir(__DIR__.'/../..'),
);
}
private function getName(): string {
$ref = new \ReflectionClass($this->schema);
$name = $ref->getShortName();
$remove_schema = Str\strip_suffix($name, 'Schema');
return $remove_schema.'Mutator';
}
public function generate(): void {
$cg = $this->codegen;
$name = $this->getName();
// Here's an example of how to generate the code for a class.
// Notice the fluent interface. It's possible to generate
// everything in the same method, however, for clarity
// sometimes it's easier to use helper methods such as
// getConstructor or getLoad in this examples.
$class = $cg->codegenClass($name)
->setIsFinal()
->addProperty($this->getDataVar())
->addProperty($this->getPdoTypeVar())
->setConstructor($this->getConstructor())
->addMethod($this->getCreateMethod())
->addMethod($this->getUpdateMethod())
->addMethod($this->getSaveMethod())
->addMethod($this->getCheckRequiredFieldsMethod())
->addMethods($this->getSetters());
$rc = new \ReflectionClass(\get_class($this->schema));
$path = $rc->getFileName() as string;
$pos = \strrpos($path, '/');
$dir = \substr($path, 0, $pos + 1);
$gen_from = 'codegen.php '.$rc->getShortName();
// This generates a file (we pass the file name) that contains the
// class defined above and saves it.
$cg->codegenFile($dir.$name.'.php')
->addClass($class)
->setGeneratedFrom($cg->codegenGeneratedFromScript($gen_from))
->save();
}
private function getDataVar(): CodegenProperty{
// Example of how to generate a class member variable, including
// setting an initial value.
return $this->codegen->codegenProperty('data')
->setType('Map<string, mixed>')
->setValue(Map {}, HackBuilderValues::export());
}
private function getPdoTypeVar(): CodegenProperty {
$values = Map {};
foreach ($this->schema->getFields() as $field) {
switch($field->getType()) {
case 'string':
case 'DateTime':
$type = 'PDO::PARAM_STR';
break;
case 'int':
$type = 'PDO::PARAM_INT';
break;
case 'bool':
$type = 'PDO::PARAM_BOOL';
break;
default:
invariant_violation('Undefined PDO type for %s', $field->getType());
}
$values[$field->getDbColumn()] = $type;
}
$cg = $this->codegen;
return $cg->codegenProperty('pdoType')
->setType('Map<string, int>')
->setIsStatic()
->setValue(
$values,
HackBuilderValues::map(
HackBuilderKeys::export(),
HackBuilderValues::literal(),
),
);
}
private function getConstructor(): CodegenConstructor {
// This very simple exampe of generating a constructor shows
// how to change its accesibility to private. The same would
// work in a method.
return $this->codegen->codegenConstructor()
->addParameter('private ?int $id = null')
->setPrivate();
}
private function getCreateMethod(): CodegenMethod {
$cg = $this->codegen;
// This is a very simple example of generating a method
return $cg->codegenMethod('create')
->setIsStatic(true)
->setReturnType('this')
->setBody(
$cg->codegenHackBuilder()
->addReturnf('new %s()', $this->getName())
->getCode()
);
}
private function getUpdateMethod(): CodegenMethod {
$cg = $this->codegen;
// This is a very simple example of generating a method
return $cg->codegenMethod('update')
->setIsStatic(true)
->addParameter('int $id')
->setReturnType('this')
->setBody(
$cg->codegenHackBuilder()
->addReturnf('new %s($id)', $this->getName())
->getCode()
);
}
private function getSaveMethod(): CodegenMethod {
$cg = $this->codegen;
// Here's an example of building a piece of code with hack_builder.
// Notice addMultilineCall, which makes easy to call a method and
// wrap it in multiple lines if needed to.
// Also notice that you can use startIfBlock to write an if statement
$body = $cg->codegenHackBuilder()
->addLinef('$conn = new PDO(\'%s\');', $this->schema->getDsn())
->addMultilineCall(
'$quoted = $this->data->mapWithKey',
Vector{'($k, $v) ==> $conn->quote((string) $v, self::$pdoType[$k])'},
)
->addAssignment(
'$id',
'$this->id',
HackBuilderValues::literal(),
)
->startIfBlock('$id === null')
->addLine('$this->checkRequiredFields();')
->addLine('$names = \'(\'.implode(\',\', $quoted->keys()).\')\';')
->addLine('$values = \'(\'.implode(\',\', $quoted->values()).\')\';')
->addLinef(
'$st = \'insert into %s \'.$names.\' values \'.$values;',
$this->schema->getTableName(),
)
->addLine('$conn->exec($st);')
->addReturnf('(int) $conn->lastInsertId()')
->addElseBlock()
->addAssignment(
'$pairs',
'$quoted->mapWithKey(($field, $value) ==> $field.\'=\'.$value)',
HackBuilderValues::literal(),
)
->addLinef(
'$st = \'update %s set \'.implode(\',\', $pairs).\' where %s=\'.$id;',
$this->schema->getTableName(),
$this->schema->getIdField(),
)
->addLine('$conn->exec($st);')
->addReturnf('$id')
->endIfBlock();
return $cg->codegenMethod('save')
->setReturnType('int')
->setBody($body->getCode());
}
private function getCheckRequiredFieldsMethod(): CodegenMethod {
$required = $this->schema->getFields()
->filter($field ==> !$field->isOptional())
->map($field ==> $field->getDbColumn())
->values()->toSet();
$cg = $this->codegen;
$body = $cg->codegenHackBuilder()
->add('$required = ')
->addValue(
$required,
HackBuilderValues::set(
HackBuilderValues::export(),
),
)
->closeStatement()
->addAssignment(
'$missing',
'$required->removeAll($this->data->keys())',
HackBuilderValues::literal(),
)
->addMultilineCall(
'invariant',
Vector {
'$missing->isEmpty()',
'\'The following required fields are missing: %s\'',
'implode(\', \', $missing)',
}
);
return $cg->codegenMethod('checkRequiredFields')
->setReturnType('void')
->setBody($body->getCode());
}
private function getSetters(): Vector<CodegenMethod> {
$cg = $this->codegen;
$methods = Vector {};
foreach($this->schema->getFields() as $name => $field) {
if ($field->getType() === 'DateTime') {
$value = '$value->format(\'Y-m-d\')';
} else {
$value = '$value';
}
$body = $cg->codegenHackBuilder();
if ($field->isManual()) {
// This part illustrates how to include a manual section, which the
// user can edit and it will be kept even if the code is regenerated.
// Notice that each section needs to have a unique name, since that's
// used to match the section when re-generating the code
$body
->startManualSection($name)
->addInlineComment('You may manually change this section of code');
}
$body
->addLinef('$this->data[\'%s\'] = %s;', $field->getDbColumn(), $value);
if ($field->isManual()) {
// You always need to close a manual section
$body->endManualSection();
}
$body->addReturnf('$this');
$methods[] = $cg->codegenMethod('set'.$name)
->setReturnType('this')
->addParameter($field->getType().' $value')
->setBody($body->getCode());
}
return $methods;
}
}