Skip to content

Commit f730dca

Browse files
committed
New instances form in rest models
Removing the timezone
1 parent 6ac4281 commit f730dca

File tree

4 files changed

+56
-2
lines changed

4 files changed

+56
-2
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
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": {

src/Model.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace taguz91\CommonRest;
44

55
use taguz91\CommonHelpers\RequestHelpers;
6+
use taguz91\CommonRest\exceptions\InvalidClassException;
67
use taguz91\ErrorHandler\exceptions\DataInvalidException;
78
use Yii;
89
use 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
}

src/RestController.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff 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;
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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+
}

0 commit comments

Comments
 (0)