1010
1111namespace OpenCodeModeling \CodeAst \Code ;
1212
13+ use PhpParser \Comment \Doc ;
1314use PhpParser \Node ;
1415use PhpParser \Node \Stmt \Property ;
1516
2324 */
2425final class PropertyGenerator extends AbstractMemberGenerator
2526{
27+ /**
28+ * @var TypeGenerator|null
29+ */
30+ private $ type ;
31+
2632 /**
2733 * @var ValueGenerator
2834 */
@@ -31,37 +37,61 @@ final class PropertyGenerator extends AbstractMemberGenerator
3137 /**
3238 * @var bool
3339 */
34- private $ omitDefaultValue = false ;
40+ private $ typed = false ;
3541
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+ ) {
4349 if (null !== $ name ) {
4450 $ this ->setName ($ name );
4551 }
52+
53+ if (null !== $ type ) {
54+ $ this ->setType ($ type );
55+ }
56+
4657 if (null !== $ defaultValue ) {
4758 $ this ->setDefaultValue ($ defaultValue );
4859 }
60+
61+ $ this ->typed = $ typed ;
62+
4963 if ($ flags !== self ::FLAG_PUBLIC ) {
5064 $ this ->setFlags ($ flags );
5165 }
5266 }
5367
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+
5484 /**
5585 * @param ValueGenerator|mixed $defaultValue
56- * @param string $defaultValueType
86+ * @param string $defaultValueType
5787 *
5888 * @return PropertyGenerator
5989 */
6090 public function setDefaultValue (
6191 $ defaultValue ,
6292 $ defaultValueType = ValueGenerator::TYPE_AUTO
6393 ): self {
64- if (! $ defaultValue instanceof ValueGenerator) {
94+ if (!$ defaultValue instanceof ValueGenerator) {
6595 $ defaultValue = new ValueGenerator ($ defaultValue , $ defaultValueType );
6696 }
6797
@@ -80,14 +110,27 @@ public function getDefaultValue(): ValueGenerator
80110
81111 public function generate (): Property
82112 {
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+
83124 return new Property (
84125 $ this ->flags ,
85126 [
86127 new Node \Stmt \PropertyProperty (
87128 $ this ->name ,
88129 $ this ->defaultValue ? $ this ->defaultValue ->generate () : null
89130 ),
90- ]
131+ ],
132+ $ attributes ,
133+ $ this ->typed ? $ this ->type ->type () : null
91134 );
92135 }
93136}
0 commit comments