Created
November 7, 2013 10:53
-
-
Save pgasiorowski/7352767 to your computer and use it in GitHub Desktop.
Allows to validate if model is unique across slected fields. Pass additional option "exclude" string or array of fileds to be excluded from the check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ELS\Model\Validator\MultiUniqueness | |
* | |
* Allows to validate if model is unique across selected fields | |
*/ | |
class MultiUniqueness extends \Phalcon\Mvc\Model\Validator | |
{ | |
/** | |
* Executes the validator | |
* | |
* @param \Phalcon\Mvc\ModelInterface $record | |
* @return boolean | |
*/ | |
public function validate($record) | |
{ | |
$fields = (array) $this->getOption('field'); | |
$excludes = (array) $this->getOption('exclude'); | |
if (array_intersect($fields, $excludes)) | |
throw new \InvalidArgumentException('Trying to exclude fields already used to uniqueness'); | |
$query = $record->query(); | |
$binds = []; | |
// Add fields which must be unique | |
foreach($fields as $field) | |
{ | |
if (!empty($field)) | |
{ | |
$query->andWhere("$field = :$field:"); | |
$binds[$field] = $record->$field; | |
} | |
} | |
// Add fields which must should be excluded from the check | |
foreach($excludes as $field) | |
{ | |
if (!empty($field) && !empty($record->$field)) | |
{ | |
$query->andWhere("$field <> :$field:"); | |
$binds[$field] = $record->$field; | |
} | |
} | |
if ($query->bind($binds)->execute()->count()) | |
{ | |
$message = $this->getOption('message')? $this->getOption('message') : 'Value must be unique'; | |
foreach($fields as $field) | |
{ | |
$this->appendMessage($message, $field, 'MultiUniqueness'); | |
} | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage in models: