Created
February 28, 2014 21:22
-
-
Save jesseobrien/9280168 to your computer and use it in GitHub Desktop.
Validatable trait
This file contains hidden or 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
| <?php | |
| use Validator; | |
| trait Validatable { | |
| /** | |
| * Validator instance for this check | |
| * @var Validator | |
| */ | |
| protected $validator = null; | |
| /** | |
| * Determine if it's needed to check validity on save | |
| * @var bool | |
| */ | |
| protected $checkValid = true; | |
| /** | |
| * Check to see if this model's attributes are valid | |
| * @return bool | |
| */ | |
| public function isValid() | |
| { | |
| $this->validator = Validator::make($this->attributes, $this->getRules()); | |
| return $this->validator->passes(); | |
| } | |
| /** | |
| * Determine if the model will be checked for validation | |
| * @return bool | |
| */ | |
| public function getsValidated() | |
| { | |
| return $this->checkValid; | |
| } | |
| /** | |
| * Bypass validation checking on save | |
| * @return Eloquent\Model | |
| */ | |
| public function bypassValidation() | |
| { | |
| $this->checkValid = false; | |
| return $this; | |
| } | |
| /** | |
| * Return the validation rules for this model | |
| * @return array | |
| */ | |
| public function getRules() | |
| { | |
| return $this->rules; | |
| } | |
| /** | |
| * Set the rules on the validator | |
| */ | |
| public function setRules(array $rules = array()) | |
| { | |
| $this->rules = $rules; | |
| } | |
| /** | |
| * Return the validator instance | |
| * @return Validator | |
| */ | |
| public function getValidator() | |
| { | |
| return $this->validator; | |
| } | |
| /** | |
| * Override the save functionality | |
| * @param array | |
| * @return mixed | |
| */ | |
| public function save(array $options = array()) | |
| { | |
| if ($this->checkValid and ! $this->isValid()) | |
| { | |
| throw new ValidationException($this->validator); | |
| } | |
| return parent::save(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment