Skip to content

Instantly share code, notes, and snippets.

@Ocramius
Created April 25, 2011 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ocramius/940549 to your computer and use it in GitHub Desktop.
Save Ocramius/940549 to your computer and use it in GitHub Desktop.
Doctrine2 Zend_Validate_DbRecord_NotExists (Gamempire\Validate\Entity\Field\Unique) implementation
<?php
namespace Gamempire\Validate\Entity\Field;
/**
* Validates input entity field to check if it is unique
*
* @author Ocramius
*/
class Unique extends \Zend_Validate_Abstract {
/**
* Error constants
*/
const ERROR_RECORD_FOUND = 'recordFound';
/**
* @var array Message templates
*/
protected $_messageTemplates = array(
self::ERROR_RECORD_FOUND => 'Duplicate \'%value%\'',
);
/**
*
* @var \Doctrine\ORM\EntityManager
*/
protected $_em;
/**
*
* @var \Gamempire\Entity
*/
protected $_matchedEntity;
/**
*
* @var string
*/
protected $_matchedEntityClass;
/**
*
* @var string
*/
protected $_field;
public function __construct(\Doctrine\ORM\EntityManager $em, \Gamempire\Entity $matchedEntity, $field) {
$this->_em = $em;
$this->_field = $field;
$this->_matchedEntity = $matchedEntity;
$metadata = $this
->_em
->getMetadataFactory()
->getMetadataFor(\get_class($this->_matchedEntity));
$this->_matchedEntityClass = $metadata->reflClass->getName();
if(!\is_string($field)) {
throw new \Zend_Validate_Exception('Provided parameter $field must be a string!');
}
try {
if(!$metadata->getFieldMapping($field)) {
throw new \Zend_Validate_Exception('Matched entity does not contain field \'' . $field . '\'!');
}
}catch(\Exception $e) {
throw new \Zend_Validate_Exception('Matched entity does not contain field \'' . $field . '\'!', 0, $e);
}
}
public function isValid($value) {
if(
\is_object($value)
&& $value instanceof \Gamempire\Entity
) {
if(!($value instanceof $this->_matchedEntityClass)) {
throw new \Zend_Validate_Exception('Value to be validated must be an instance of \'' . $this->_matchedEntityClass . '\'!');
}
$value = $value[$this->_field];
}
$this->_setValue($value);
if(
$match = $this
->_em
->getRepository($this->_matchedEntityClass)
->findOneBy(array($this->_field => $value))
) {
if($match->id !== $this->_matchedEntity->id) {
$this->_error(self::ERROR_RECORD_FOUND);
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment