File tree Expand file tree Collapse file tree 4 files changed +56
-2
lines changed
Expand file tree Collapse file tree 4 files changed +56
-2
lines changed Original file line number Diff line number Diff line change 1818 "require" : {
1919 "php" : " >=7.0.0" ,
2020 "yiisoft/yii2" : " ~2.0.0" ,
21- "taguz91/yii2-common-helpers" : " v2 .0.0" ,
21+ "taguz91/yii2-common-helpers" : " ^2 .0.0" ,
2222 "taguz91/yii2-error-handler" : " ^2.0.0"
2323 },
2424 "config" : {
Original file line number Diff line number Diff line change 33namespace taguz91 \CommonRest ;
44
55use taguz91 \CommonHelpers \RequestHelpers ;
6+ use taguz91 \CommonRest \exceptions \InvalidClassException ;
67use taguz91 \ErrorHandler \exceptions \DataInvalidException ;
78use Yii ;
89use yii \base \Model as BaseModel ;
@@ -79,4 +80,45 @@ public function loadValidOrEnd(
7980 }
8081 return $ this ;
8182 }
83+
84+ /**
85+ * Create a model
86+ */
87+ public static function instanceModel (array $ data )
88+ {
89+ $ model = new static ();
90+ $ model ->load ($ data , '' );
91+ return $ model ;
92+ }
93+
94+ public static function instanceRecursive (
95+ array $ data ,
96+ array $ recursive
97+ ) {
98+ foreach ($ recursive as $ attribute => $ class ) {
99+
100+ if (is_array ($ class )) {
101+ list ($ classPath , $ recursiveChild ) = $ class ;
102+
103+ $ recursiveModel = new $ classPath ();
104+ if (!$ recursiveModel instanceof Model) {
105+ throw new InvalidClassException ("The class ' {$ classPath }' isn't recursive. " );
106+ }
107+
108+ $ data [$ attribute ] = $ recursiveModel ::instanceRecursive (
109+ $ data [$ attribute ],
110+ $ recursiveChild
111+ );
112+ } elseif (is_string ($ class )) {
113+ $ recursiveModel = new $ class ();
114+ if (!$ recursiveModel instanceof Model) {
115+ throw new InvalidClassException ("The class ' {$ class }' isn't recursive. " );
116+ }
117+
118+ $ data [$ attribute ] = $ recursiveModel ::instanceModel ($ data [$ attribute ]);
119+ }
120+ }
121+
122+ return self ::instanceModel ($ data );
123+ }
82124}
Original file line number Diff line number Diff line change @@ -17,7 +17,6 @@ class RestController extends BaseController
1717 */
1818 public function beforeAction ($ action )
1919 {
20- date_default_timezone_set ("America/Guayaquil " );
2120 Yii::$ app ->response ->format = Response::FORMAT_JSON ;
2221 Yii::$ app ->response ->headers ->add ('Content-Type ' , 'application/json ' );
2322 $ this ->enableCsrfValidation = false ;
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace taguz91 \CommonRest \exceptions ;
4+
5+ use Exception ;
6+
7+ class InvalidClassException extends Exception
8+ {
9+ public function __construct (string $ message )
10+ {
11+ parent ::__construct ($ message , 2003 );
12+ }
13+ }
You can’t perform that action at this time.
0 commit comments