crhayes/laravel-extended-validator — pull request #5 by joshuajabbour (2014-02-18 22:42:56+00:00)
Title: Add setters to override context and attributes

I'm using the repository pattern for my project, and would really like to use Laravel's automatic dependency injection in my constructor to boot up a ContextualValidator instance. The problem is that the validators only accept attributes during instantiation, and at that point I have no access (or even knowledge of) the input. (Furthermore, since I'm reusing the validator, I need to be able to completely reset the context, not just add to it, hence the `ContextualValidator::setContext`.)

I want to be able to do the following, which requires the ability to reset the attributes/context when calling the validator. (In other words, calling `UserValidator::make` or `new UserValidator` in each method isn't possible, because of the dependency injection.)

~~~php
abstract class EloquentRepository implements RepositoryInterface
{
protected $model;

public $validator;

public function __construct(Model $model, ContextualValidator $validator)
{
$this->model = $model;
$this->validator = $validator;
}

public function create(array $attributes)
{
$this->validator->setAttributes($attributes)->setContext('create');
if ($this->validator->passes()) {
return $this->model->create($attributes);
}
return false;
}

public function update($id, array $attributes)
{
$this->validator->setAttributes($attributes)->setContext('update');
if ($this->validator->passes()) {
return $this->model->find($id)->update($attributes);
}
return false;
}
}

class UserEloquentRepository extends EloquentRepository implements UserRepositoryInterface
{
public function __construct(User $model, UserValidator $validator)
{
parent::__construct($model, $validator);
}
}

class UserController extends BaseController
{
protected $repository;

public function __construct(UserRepositoryInterface $repository)
{
$this->repository = $repository;
}

public function store()
{
$user = $this->repository->create(Input::get());
if ($user === false) {
return View::make('pages.user.edit', ['user' => $this->repository->newInstance(Input::get()), 'errors' => $this->repository->validator->errors()]);
}
return View::make('pages.user.show', compact('user'));
}

public function update($id)
{
$updated = $this->repository->update($id, Input::get());
$user = $this->repository->find($id);
if ($updated === false) {
return View::make('pages.user.edit', ['user' => $user, 'errors' => $this->repository->validator->errors()]);
}
return View::make('pages.user.show', compact('user'));
}
}
~~~