Skip to content

Commit

Permalink
Update unique document validator.
Browse files Browse the repository at this point in the history
  • Loading branch information
richsage committed Jun 8, 2015
1 parent 36e2ff4 commit dc02b3d
Showing 1 changed file with 38 additions and 40 deletions.
78 changes: 38 additions & 40 deletions Validator/Constraint/UniqueDocumentValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,41 +35,6 @@ public function __construct(Mandango $mandango)
$this->mandango = $mandango;
}

/**
* Validates the document uniqueness.
*
* @param value $value The document.
* @param Constraint $constraint The constraint.
*
* @return Boolean Whether or not the document is unique.
*/
public function isValid($value, Constraint $constraint)
{
$document = $this->parseDocument($value);
$fields = $this->parseFields($constraint->fields);
$caseInsensitive = $this->parseCaseInsensitive($constraint->caseInsensitive);

$query = $this->createQuery($document, $fields, $caseInsensitive);
$numberResults = $query->count();

if (0 === $numberResults) {
return true;
}

if (1 === $numberResults) {
$result = $query->one();
if ($result === $document) {
return true;
}
}

if ($this->context) {
$this->addFieldViolation($fields[0], $constraint->message);
}

return false;
}

private function parseDocument($document)
{
if (!$document instanceof Document) {
Expand Down Expand Up @@ -127,9 +92,42 @@ private function createCriteria(Document $document, array $fields, array $caseIn

private function addFieldViolation($field, $message)
{
$oldPath = $this->context->getPropertyPath();
$this->context->setPropertyPath(empty($oldPath) ? $field : $oldPath.'.'.$field);
$this->context->addViolation($message, array(), null);
$this->context->setPropertyPath($oldPath);
$this->context->addViolationAt($field, $message);
}
}

/**
* Validates the document uniqueness.
*
* @param value $value The document.
* @param Constraint $constraint The constraint.
*
* @return Boolean Whether or not the document is unique.
*/
public function validate($value, Constraint $constraint)
{
$document = $this->parseDocument($value);
$fields = $this->parseFields($constraint->fields);
$caseInsensitive = $this->parseCaseInsensitive($constraint->caseInsensitive);

$query = $this->createQuery($document, $fields, $caseInsensitive);
$numberResults = $query->count();

if (0 === $numberResults) {
return true;
}

if (1 === $numberResults) {
$result = $query->one();
if ($result === $document) {
return true;
}
}

if ($this->context) {
$this->addFieldViolation($fields[0], $constraint->message);
}

return false;
}
}

0 comments on commit dc02b3d

Please sign in to comment.