From f683958fe1a01aefcb9f623fa463cdd6ad2d1bee Mon Sep 17 00:00:00 2001 From: Peter Date: Tue, 21 Feb 2017 10:43:55 +0100 Subject: [PATCH] model validation --- src/Components/Model.php | 53 +++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/src/Components/Model.php b/src/Components/Model.php index bbf3ad3..a72ee14 100644 --- a/src/Components/Model.php +++ b/src/Components/Model.php @@ -21,6 +21,13 @@ public static function getDocBlock() { } } + /** + * @return static + */ + public static function model() { + return new static(); + } + /** * Magic getter. * @@ -118,19 +125,24 @@ public function validateBoolean($key) { */ public function setAttributes(array $data) { foreach ($data as $key => $value) { + $key = $this->getFormattedKey($key); $this->$key = $value; } } + protected function getMap() { + return []; + } + /** - * Return the key, allow models to do mapping + * Returns the mapped key * * @param $key * * @return mixed */ protected function getFormattedKey($key) { - return $key; + return array_key_exists($key, $this->getMap()) ? $this->getMap()[$key] : $key; } /** @@ -141,12 +153,37 @@ protected function getFormattedKey($key) { abstract public function getRules(); /** - * Run preprocessing when required + * Before we validate the model + * @return bool */ - protected function beforeGetAttributes() { + protected function beforeValidate() { return true; } + /** + * Validate the model + * @return bool + */ + public function validate() { + if ($this->beforeValidate()) { + foreach ($this->attributes as &$attribute) { + if ($attribute->value instanceof \ArrayObject) { + foreach ($attribute->value as &$item) { + $item->validate(); + } + } else if ($attribute->value instanceof Model) { + $attribute->value->validate(); + } else { + $attribute->validate(); + } + } + + return true; + } + + return false; + } + /** * Returns the params as array * @@ -155,8 +192,7 @@ protected function beforeGetAttributes() { public function getAttributes() { $data = []; - if ($this->beforeGetAttributes()) { - + if ($this->validate()) { foreach ($this->attributes as $attribute) { if ($attribute->value instanceof \ArrayObject) { foreach ($attribute->value as $item) { @@ -165,13 +201,12 @@ public function getAttributes() { } else if ($attribute->value instanceof Model) { $data[$this->getFormattedKey($attribute->key)] = $attribute->value->getAttributes(); } else { - $attribute->validate(); $data[$this->getFormattedKey($attribute->key)] = $attribute->value; } } - } - return $data; + return $data; + } } } \ No newline at end of file