Skip to content

Instantly share code, notes, and snippets.

@JacobBennett
Last active October 2, 2015 12:33
Show Gist options
  • Save JacobBennett/bcb1025afe47f86641b4 to your computer and use it in GitHub Desktop.
Save JacobBennett/bcb1025afe47f86641b4 to your computer and use it in GitHub Desktop.
Validator that accounts for context of validation
<?php
// After injecting the class into your controller, you would call it on a method like so
// store here is the context
// this will validate it against that set of rules
$this->validator->validate(Input::all(), 'store');
<?php namespace Acme\Exceptions;
use Illuminate\Support\MessageBag;
class FormValidationException extends \Exception
{
/**
* @var MessageBag
*/
protected $errors;
function __construct($message, MessageBag $errors)
{
$this->errors = $errors;
parent::__construct($message);
}
public function getErrors()
{
return $this->errors;
}
}
<?php namespace Acme\Forms;
use Illuminate\Validation\Factory as Validator;
use Acme\Exceptions\FormValidationException;
abstract class FormValidator {
/**
* @var Validator
*/
protected $validator;
/**
* @var Validator
*/
protected $validation;
/**
* @param Validator $validator
*/
function __construct(Validator $validator)
{
$this->validator = $validator;
}
public function validate(array $formData, $context)
{
$this->validation = $this->validator->make($formData, $this->getValidationRules($context));
if($this->validation->fails())
{
throw new FormValidationException("Validation failed", $this->getValidationErrors());
}
return true;
}
protected function getValidationRules($context)
{
if(isset($context) && isset($this->rules[$context])) return $this->rules[$context];
return $this->rules;
}
protected function getValidationErrors()
{
return $this->validation->errors();
}
}
<?php namespace Acme\Forms;
class ClaimsForm extends FormValidator {
protected $rules = [
'store' => [
"email" => "required|unique",
"password" => "required"
],
'update' => [
"email" => "required"
]
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment