<?php

use Eloquent;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

/*
	Hints:
	$this->validator->errors()->all() - array with messages for view
	$this->validator->errors() - like with all(), but can obtain what field has what errors
	$this->validator->failed() - to obtain what field has what exatly errors
	$user->validator->messages()->errors()->has('email') - if field has any errors
*/

class ValidatorEloquent extends Eloquent {
    public $validator;
    protected $attributes_to_validate;
    protected static $rules = array();

    public function __construct($attributes = array())
    {
        parent::__construct($attributes);
        $this->validator = Validator::make(array(), static::$rules);
    }

    public function setAttribute($key, $value)
    {
        $this->attributes_to_validate[$key] = $value;
        return parent::setAttribute($key, $value);
    }

    public function validate()
    {
        // Set data for validator
        $this->validator->setData( $this->attributes_to_validate );

        // Sets the connection, based on the model's connection variable.
        $this->validator->getPresenceVerifier()->setConnection($this->connection);

        if ($this->validator->passes())
        {
            return true;
        }

        $this->validationErrors = $this->validator->messages();
        return false;
    }

    public function purgeConfirmation()
    {
        foreach ($this->attributes as $key => $value)
        {
            if (Str::endsWith($key, '_confirmation') AND ! Str::startsWith($key, '_'))
                unset($this->attributes[$key]);
        }
    }

    public function save(array $options = array())
    {
        if($this->validate())
        {
            $this->purgeConfirmation();
            return parent::save($options);
        }else{
            return false;
        }
    }
}