|
| 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