Skip to content

Instantly share code, notes, and snippets.

@thiagomata
Created March 3, 2015 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagomata/9de6f00684c6d704a77c to your computer and use it in GitHub Desktop.
Save thiagomata/9de6f00684c6d704a77c to your computer and use it in GitHub Desktop.
<?php
namespace App\Models\Traits;
use \Validator;
trait ValidateModelTrait
{
private $errors;
private $objValidator;
public function getRules()
{
$arrAfterRules = $this::$rules;
$callback = function( $found ) {
$value = $this->{$found[1]};
if( $value === false ) {
return 'false';
}
if( $value === true ) {
return 'true';
}
if( $value === null ) {
return 'NULL';
}
return $value;
};
foreach( $this::$rules as $fieldRule => $rule ) {
$arrAfterRules[ $fieldRule ] = preg_replace_callback(
"/\{\{([^\}]*)\}\}/",
$callback,
$rule
);
}
return $arrAfterRules;
}
public function modelValidate( $data )
{
return true;
}
public function validate($data = null)
{
if( $data === null ) {
$data = $this->toArray();
}
// make a new validator object
$this->objValidator = Validator::make($data, $this->getRules());
// check for failure
if ($this->objValidator->fails())
{
// set errors and return false
$this->errors = $this->objValidator->errors();
return false;
}
// validation pass
return $this->modelValidate( $data );
}
public function isValid()
{
return $this->validate();
}
public function errors()
{
$this->validate();
return $this->errors;
}
public function getValidator()
{
$this->validate();
return $this->objValidator;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment