Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up is_{,in}valid #290

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 33 additions & 9 deletions lib/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@ class Model
* @var array
*/
private $__dirty = null;

/**
* Flag whether or not this model has been validated. Only used in is_valid and _validate
*
* @var boolean
* @see is_valid
* @see is_invalid
*/
private $__validated = false;

/**
* Flag that determines of this model can have a writer method invoked such as: save/update/insert/delete
Expand Down Expand Up @@ -1040,6 +1049,8 @@ public function values_for($attribute_names)
private function _validate()
{
require_once 'Validations.php';

$this->__validated = false;

$validator = new Validations($this);
$validation_on = 'validation_on_' . ($this->is_new_record() ? 'create' : 'update');
Expand Down Expand Up @@ -1079,9 +1090,13 @@ public function is_dirty()
* @see is_invalid
* @return boolean
*/
public function is_valid()
public function is_valid($force_validation = false)
{
return $this->_validate();
if(!$this->__validated || $force_validation)
return $this->_validate();

// If validated without errors, then it's valid
return $this->errors->is_empty();
}

/**
Expand All @@ -1090,9 +1105,9 @@ public function is_valid()
* @see is_valid
* @return boolean
*/
public function is_invalid()
public function is_invalid($force_validation = false)
{
return !$this->_validate();
return !$this->is_valid($force_validation);
}

/**
Expand Down Expand Up @@ -1239,19 +1254,18 @@ public function set_relationship_from_eager_load(Model $model=null, $name)
*/
public function reload()
{
$this->__relationships = array();
$this->clear_state();

$pk = array_values($this->get_values_for($this->get_primary_key()));

$this->set_attributes_via_mass_assignment($this->find($pk)->attributes, false);
$this->reset_dirty();

return $this;
}

public function __clone()
{
$this->__relationships = array();
$this->reset_dirty();
{
$this->clear_state();
return $this;
}

Expand All @@ -1264,6 +1278,16 @@ public function reset_dirty()
{
$this->__dirty = null;
}

/**
* Clear the state of model.
*/
public function clear_state() {
$this->reset_dirty();
$this->__relationships = array();
$this->__validated = false;
$this->errors = array();
}

/**
* A list of valid finder options.
Expand Down