Skip to content

Instantly share code, notes, and snippets.

@pgasiorowski
Created November 7, 2013 10:53
Show Gist options
  • Save pgasiorowski/7352767 to your computer and use it in GitHub Desktop.
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
/**
* 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;
}
}
@pgasiorowski
Copy link
Author

Usage in models:

   <?php
    /**
     * Validate the model data
     *
     * @return bool
     */
    public function validation()
    {
        $this->validate(new MultiUniqueness([
            'field'   => ['tag', 'project_id'],
            'exclude' => ['id'],
            'message' => 'Field must be unique within selected project'
        ]));

        return ($this->validationHasFailed() != true);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment