-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathModelGenerator.php
More file actions
95 lines (85 loc) · 2.7 KB
/
Copy pathModelGenerator.php
File metadata and controls
95 lines (85 loc) · 2.7 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
<?hh // strict
namespace Facebook\HackCodegen;
/**
* For a given ModelSchema, this class generates code for a class
* that will allow to read the data from a database and store it
* in the object.
*/
class ModelGenerator {
public function __construct(
private \ModelSchema $schema,
) {}
private function getSchemaName(): string {
$ref = new \ReflectionClass($this->schema);
$name = $ref->getShortName();
return Str::endsWith($name, 'Schema')
? Str::substr($name, 0, -6)
: $name;
}
public function generate(): void {
$class = codegen_class($this->getSchemaName())
->setIsFinal()
->setConstructor($this->getConstructor())
->addMethod($this->getLoad())
->addMethods($this->getGetters())
->setHasManualMethodSection();
codegen_file(dirname(__FILE__).'/../models/'.$this->getSchemaName().'.php')
->addClass($class)
->save();
}
private function getConstructor(): CodegenConstructor {
return codegen_constructor()
->setPrivate()
->addParameter('private Map<string, mixed> $data');
}
private function getLoad(): CodegenMethod {
$body = hack_builder()
->addLine(
'$result = DB::queryFirstRow("SELECT * FROM %s WHERE %s=%%s", $id);',
$this->schema->getTableName(),
$this->schema->getIdField()
)
->startIfBlock('!$result')
->addReturn('null')
->endIfBlock()
->addReturn('new %s(new Map($result))', $this->getSchemaName());
return codegen_method('load')
->setIsStatic()
->addParameter('int $id')
->setReturnType('?'.$this->getSchemaName())
->setBody($body->getCode());
}
private function getGetters(): Vector<CodegenMethod> {
$methods = Vector {};
foreach ($this->schema->getFields() as $name => $field) {
$return_type = $field->getType();
$data = '$this->data[\''.$field->getDbColumn().'\']';
$return_data = $data;
if ($return_type == 'DateTime') {
$return_data = 'new DateTime('.$data.')';
} else {
$return_data = "($return_type) $data";
}
if ($field->isOptional()) {
$return_type = '?'.$return_type;
$builder = hack_builder();
if ($field->isManual()) {
$builder->beginManualSection($name);
}
$builder->addWithSuggestedLineBreaks(
"return isset($data)\t? $return_data\t: null;",
);
if ($field->isManual()) {
$builder->endManualSection();
}
$body = $builder->getCode();
} else {
$body = 'return '.$return_data.';';
}
$methods[] = codegen_method('get'.$name)
->setReturnType($return_type)
->setBody($body);
}
return $methods;
}
}