This repository has been archived by the owner on Jan 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial commit of AutoValidateBehavior.php
- Loading branch information
Florian Krämer
committed
Jul 24, 2013
1 parent
ba1e6e3
commit f87b7ac
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
<?php | ||
App::uses('ModelBehavior', 'Model'); | ||
|
||
/** | ||
* AutoValidateBehavior | ||
* | ||
* @author Florian Krämer | ||
* @copyright 2013 Florian Krämer | ||
* @license MIT | ||
*/ | ||
class AutoValidateBehavior extends ModelBehavior { | ||
|
||
/** | ||
* beforeValidate | ||
* | ||
* @param Model $Model | ||
* @return boolean | ||
*/ | ||
public function beforeValidate(Model $Model) { | ||
$this->generateValidationRules($Model); | ||
return true; | ||
} | ||
|
||
/** | ||
* generateValidationRules | ||
* | ||
* @param Model $Model | ||
* @param array | ||
* @return void | ||
*/ | ||
public function generateValidationRules(Model $Model) { | ||
$schema = $Model->schema(); | ||
foreach ($schema as $field => $meta) { | ||
if ($field === $Model->primaryKey) { | ||
continue; | ||
} | ||
|
||
if ($meta['null'] === false) { | ||
$Model->validate[$field]['notEmpty'] = array( | ||
'rule' => 'notEmpty', | ||
'empty' => false, | ||
'message' => __('This field can not be empty.'), | ||
); | ||
} | ||
|
||
if ($meta['type'] === 'boolean') { | ||
$Model->validate[$field]['boolean'] = array( | ||
'rule' => 'boolean', | ||
'empty' => false, | ||
'message' => __('This field can not be empty.'), | ||
); | ||
} | ||
|
||
if ($meta['type'] === 'string') { | ||
$Model->validate[$field]['length'] = array( | ||
'rule' => array('length', $meta['length']), | ||
'empty' => false, | ||
'message' => __('This field can not be longer than %d.', $meta['length']), | ||
); | ||
} | ||
} | ||
} | ||
|
||
} |