88namespace cebe \openapi ;
99
1010use cebe \openapi \exceptions \ReadonlyPropertyException ;
11+ use cebe \openapi \exceptions \TypeErrorException ;
1112use cebe \openapi \exceptions \UnknownPropertyException ;
1213use cebe \openapi \spec \Type ;
1314
@@ -72,14 +73,14 @@ public function __construct(array $data)
7273 $ this ->_properties [$ property ][] = $ item ;
7374 } else {
7475 // TODO implement reference objects
75- $ this ->_properties [$ property ][] = new $ type [0 ]( $ item );
76+ $ this ->_properties [$ property ][] = $ this -> instantiate ( $ type [0 ], $ item );
7677 }
7778 }
7879 break ;
7980 case 2 :
8081 // map
8182 if ($ type [0 ] !== Type::STRING ) {
82- throw new \ Exception ('Invalid map key type: ' . $ type [0 ]);
83+ throw new TypeErrorException ('Invalid map key type: ' . $ type [0 ]);
8384 }
8485 $ this ->_properties [$ property ] = [];
8586 foreach ($ data [$ property ] as $ key => $ item ) {
@@ -92,13 +93,13 @@ public function __construct(array $data)
9293 $ this ->_properties [$ property ][$ key ] = $ item ;
9394 } else {
9495 // TODO implement reference objects
95- $ this ->_properties [$ property ][$ key ] = new $ type [1 ]( $ item );
96+ $ this ->_properties [$ property ][$ key ] = $ this -> instantiate ( $ type [1 ], $ item );
9697 }
9798 }
9899 break ;
99100 }
100101 } else {
101- $ this ->_properties [$ property ] = new $ type ( $ data [$ property ]);
102+ $ this ->_properties [$ property ] = $ this -> instantiate ( $ type , $ data [$ property ]);
102103 }
103104 unset($ data [$ property ]);
104105 }
@@ -107,6 +108,19 @@ public function __construct(array $data)
107108 }
108109 }
109110
111+ private function instantiate ($ type , $ data )
112+ {
113+ try {
114+ return new $ type ($ data );
115+ } catch (\TypeError $ e ) {
116+ throw new TypeErrorException (
117+ "Unable to instantiate {$ type } Object with data ' " . print_r ($ data , true ) . "' " ,
118+ $ e ->getCode (),
119+ $ e
120+ );
121+ }
122+ }
123+
110124 /**
111125 * Validate object data according to OpenAPI spec.
112126 * @return bool whether the loaded data is valid according to OpenAPI spec
@@ -192,7 +206,12 @@ public function __get($name)
192206 return $ this ->_properties [$ name ];
193207 }
194208 if (isset (static ::attributes ()[$ name ])) {
195- return is_array (static ::attributes ()[$ name ]) ? [] : null ;
209+ if (is_array (static ::attributes ()[$ name ])) {
210+ return [];
211+ } elseif (static ::attributes ()[$ name ] === Type::BOOLEAN ) {
212+ return false ;
213+ }
214+ return null ;
196215 }
197216 throw new UnknownPropertyException ('Getting unknown property: ' . \get_class ($ this ) . ':: ' . $ name );
198217 }
0 commit comments