Skip to content

Commit

Permalink
Merge pull request #2 from afosto/hotfix/before-get-attributes
Browse files Browse the repository at this point in the history
model validation
  • Loading branch information
bakkerpeter authored Feb 21, 2017
2 parents cf0006a + f683958 commit 42f3492
Showing 1 changed file with 44 additions and 9 deletions.
53 changes: 44 additions & 9 deletions src/Components/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ public static function getDocBlock() {
}
}

/**
* @return static
*/
public static function model() {
return new static();
}

/**
* Magic getter.
*
Expand Down Expand Up @@ -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;
}

/**
Expand All @@ -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
*
Expand All @@ -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) {
Expand All @@ -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;
}
}

}

0 comments on commit 42f3492

Please sign in to comment.