10
10
11
11
namespace OpenCodeModeling \CodeAst \Code ;
12
12
13
+ use PhpParser \Comment \Doc ;
13
14
use PhpParser \Node ;
14
15
use PhpParser \Node \Stmt \Property ;
15
16
23
24
*/
24
25
final class PropertyGenerator extends AbstractMemberGenerator
25
26
{
27
+ /**
28
+ * @var TypeGenerator|null
29
+ */
30
+ private $ type ;
31
+
26
32
/**
27
33
* @var ValueGenerator
28
34
*/
@@ -31,37 +37,61 @@ final class PropertyGenerator extends AbstractMemberGenerator
31
37
/**
32
38
* @var bool
33
39
*/
34
- private $ omitDefaultValue = false ;
40
+ private $ typed = false ;
35
41
36
- /**
37
- * @param string $name
38
- * @param ValueGenerator| string|array $defaultValue
39
- * @param int $flags
40
- */
41
- public function __construct ( $ name = null , $ defaultValue = null , $ flags = self ::FLAG_PRIVATE )
42
- {
42
+ public function __construct (
43
+ string $ name = null ,
44
+ string $ type = null ,
45
+ $ defaultValue = null ,
46
+ bool $ typed = false ,
47
+ int $ flags = self ::FLAG_PRIVATE
48
+ ) {
43
49
if (null !== $ name ) {
44
50
$ this ->setName ($ name );
45
51
}
52
+
53
+ if (null !== $ type ) {
54
+ $ this ->setType ($ type );
55
+ }
56
+
46
57
if (null !== $ defaultValue ) {
47
58
$ this ->setDefaultValue ($ defaultValue );
48
59
}
60
+
61
+ $ this ->typed = $ typed ;
62
+
49
63
if ($ flags !== self ::FLAG_PUBLIC ) {
50
64
$ this ->setFlags ($ flags );
51
65
}
52
66
}
53
67
68
+ /**
69
+ * @param string $type
70
+ * @return ParameterGenerator
71
+ */
72
+ public function setType ($ type ): self
73
+ {
74
+ $ this ->type = TypeGenerator::fromTypeString ($ type );
75
+
76
+ return $ this ;
77
+ }
78
+
79
+ public function getType (): TypeGenerator
80
+ {
81
+ return $ this ->type ;
82
+ }
83
+
54
84
/**
55
85
* @param ValueGenerator|mixed $defaultValue
56
- * @param string $defaultValueType
86
+ * @param string $defaultValueType
57
87
*
58
88
* @return PropertyGenerator
59
89
*/
60
90
public function setDefaultValue (
61
91
$ defaultValue ,
62
92
$ defaultValueType = ValueGenerator::TYPE_AUTO
63
93
): self {
64
- if (! $ defaultValue instanceof ValueGenerator) {
94
+ if (!$ defaultValue instanceof ValueGenerator) {
65
95
$ defaultValue = new ValueGenerator ($ defaultValue , $ defaultValueType );
66
96
}
67
97
@@ -80,14 +110,27 @@ public function getDefaultValue(): ValueGenerator
80
110
81
111
public function generate (): Property
82
112
{
113
+ $ propComment = <<<EOF
114
+ /**
115
+ * @var {$ this ->type ->type ()}
116
+ */
117
+ EOF ;
118
+ $ attributes = [];
119
+
120
+ if ($ this ->typed === false ) {
121
+ $ attributes = ['comments ' => [new Doc ($ propComment )]];
122
+ }
123
+
83
124
return new Property (
84
125
$ this ->flags ,
85
126
[
86
127
new Node \Stmt \PropertyProperty (
87
128
$ this ->name ,
88
129
$ this ->defaultValue ? $ this ->defaultValue ->generate () : null
89
130
),
90
- ]
131
+ ],
132
+ $ attributes ,
133
+ $ this ->typed ? $ this ->type ->type () : null
91
134
);
92
135
}
93
136
}
0 commit comments