Skip to content

Commit 4cd9915

Browse files
committed
Common model for rest
1 parent 993d44b commit 4cd9915

File tree

2 files changed

+84
-1
lines changed

2 files changed

+84
-1
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
"require": {
1919
"php": ">=7.0.0",
2020
"yiisoft/yii2": "~2.0.0",
21-
"taguz91/yii2-common-helpers": "v1.0.3.1"
21+
"taguz91/yii2-common-helpers": "v1.0.3.1",
22+
"taguz91/yii2-error-handler": "^1.1"
2223
},
2324
"autoload": {
2425
"psr-4": {

src/Model.php

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
<?php
2+
3+
namespace taguz91\CommonRest;
4+
5+
use taguz91\CommonHelpers\RequestHelpers;
6+
use taguz91\ErrorHandler\exceptions\DataInvalidException;
7+
use Yii;
8+
use yii\base\Model as BaseModel;
9+
10+
class Model extends BaseModel
11+
{
12+
13+
/**
14+
* @return array $attributes - Nombre de los atributos de la clase
15+
*/
16+
public function getKeysAttributes()
17+
{
18+
return array_keys($this->attributes);
19+
}
20+
21+
public function rules()
22+
{
23+
return [
24+
[
25+
$this->getKeysAttributes(),
26+
'safe',
27+
],
28+
];
29+
}
30+
31+
public function rulesRequired(array $notRequired = [])
32+
{
33+
return [
34+
// Todos seguros
35+
[
36+
$this->getKeysAttributes(),
37+
'safe',
38+
],
39+
// Agregamos que todos son requreidos
40+
[
41+
array_diff($this->getKeysAttributes(), $notRequired),
42+
'required',
43+
],
44+
];
45+
}
46+
47+
/**
48+
* Load the data from post request
49+
*/
50+
public function post(string $node = '')
51+
{
52+
$data = RequestHelpers::getPostData();
53+
$this->load($data, $node);
54+
}
55+
56+
/**
57+
* @return static
58+
*/
59+
public function postValidOrEnd(string $node = '')
60+
{
61+
$this->post($node);
62+
if (!$this->validate()) {
63+
throw new DataInvalidException(Yii::t('app', 'Invalid post data.'), $this);
64+
}
65+
return $this;
66+
}
67+
68+
/**
69+
* @return static
70+
*/
71+
public function loadValidOrEnd(
72+
array $data,
73+
string $errorMessage = '',
74+
string $node = ''
75+
) {
76+
$this->load($data, $node);
77+
if (!$this->validate()) {
78+
throw new DataInvalidException($errorMessage, $this);
79+
}
80+
return $this;
81+
}
82+
}

0 commit comments

Comments
 (0)