1
|
|
|
<?php |
2
|
|
|
namespace gossi\codegen\generator; |
3
|
|
|
|
4
|
|
|
use gossi\codegen\config\CodeGeneratorConfig; |
5
|
|
|
use gossi\codegen\generator\utils\Writer; |
6
|
|
|
use gossi\codegen\model\AbstractModel; |
7
|
|
|
use gossi\formatter\Formatter; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Model Generator |
11
|
|
|
* |
12
|
|
|
* @author Thomas Gossmann |
13
|
|
|
*/ |
14
|
|
|
class ModelGenerator { |
15
|
|
|
|
16
|
|
|
/** @var Writer */ |
17
|
|
|
private $writer; |
18
|
|
|
|
19
|
|
|
/** @var BuilderFactory */ |
20
|
|
|
private $factory; |
21
|
|
|
|
22
|
|
|
/** @var CodeGeneratorConfig */ |
23
|
|
|
private $config; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* |
27
|
|
|
* @param CodeGeneratorConfig|array $config |
28
|
|
|
*/ |
29
|
39 |
|
public function __construct($config = null) { |
30
|
39 |
|
if (is_array($config)) { |
31
|
5 |
|
$this->config = new CodeGeneratorConfig($config); |
32
|
39 |
|
} else if ($config instanceof CodeGeneratorConfig) { |
33
|
8 |
|
$this->config = $config; |
34
|
8 |
|
} else { |
35
|
29 |
|
$this->config = new CodeGeneratorConfig(['generateDocblock' => false]); |
36
|
|
|
} |
37
|
|
|
|
38
|
39 |
|
$profile = $this->config->getProfile(); |
39
|
39 |
|
$this->writer = new Writer([ |
40
|
39 |
|
'indentation_character' => $profile->getIndentation('character') == 'tab' ? "\t" : ' ', |
41
|
39 |
|
'indentation_size' => $profile->getIndentation('size') |
42
|
39 |
|
]); |
43
|
39 |
|
$this->formatter = new Formatter($profile); |
|
|
|
|
44
|
39 |
|
$this->factory = new BuilderFactory($this); |
45
|
39 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @return CodeGeneratorConfig |
49
|
|
|
*/ |
50
|
39 |
|
public function getConfig() { |
51
|
39 |
|
return $this->config; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @return Writer |
56
|
|
|
*/ |
57
|
39 |
|
public function getWriter() { |
58
|
39 |
|
return $this->writer; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return BuilderFactory |
63
|
|
|
*/ |
64
|
6 |
|
public function getFactory() { |
65
|
6 |
|
return $this->factory; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param AbstractModel $model |
70
|
|
|
* @return string |
71
|
|
|
*/ |
72
|
37 |
|
public function generate(AbstractModel $model) { |
73
|
37 |
|
$this->writer->reset(); |
74
|
|
|
|
75
|
37 |
|
$builder = $this->factory->getBuilder($model); |
76
|
37 |
|
$builder->build($model); |
77
|
|
|
|
78
|
37 |
|
$code = $this->writer->getContent(); |
79
|
|
|
|
80
|
37 |
|
if ($this->config->isFormattingEnabled()) { |
81
|
|
|
$code = $this->formatter->format($code); |
82
|
|
|
} |
83
|
|
|
|
84
|
37 |
|
return $code; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: