Created
April 25, 2011 14:04
-
-
Save Ocramius/940549 to your computer and use it in GitHub Desktop.
Doctrine2 Zend_Validate_DbRecord_NotExists (Gamempire\Validate\Entity\Field\Unique) implementation
This file contains 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
<?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