Skip to content

Instantly share code, notes, and snippets.

@robzienert
Created May 2, 2011 21:34
Show Gist options
  • Select an option

  • Save robzienert/952430 to your computer and use it in GitHub Desktop.

Select an option

Save robzienert/952430 to your computer and use it in GitHub Desktop.
<?php
class Entity
{
protected $_ruleSet;
public function __construct([..], RuleSet $ruleSet = null)
{
$this->_ruleSet = $ruleSet
}
public function validate()
{
return $this->_ruleSet->brokenBy($this);
}
public function setRuleSet(RuleSet $ruleSet)
{
$this->_ruleSet = $ruleSet;
}
public function getRuleSet()
{
return $this->_ruleSet;
}
}
class RuleSet
{
protected $_rules = array();
public function __construct(array $rules = array())
{
$this->setRules($rules);
}
public function setRules(array $rules)
{
foreach ($rules as $key => $keyRules) {
foreach ($keyRules as $rule) {
$this->addRule($key, $rule);
}
}
}
public function addRule($key, \Zend_Validate_Interface $validator)
{
$this->_rules[$key] = $validator;
}
public function getRules($key = null)
{
if (null === $key) {
return $this->_keys;
}
if (!isset($this->_rules[$keys])) {
throw new \Exception('Rule key is not valid');
}
return $this->_rules[$keys];
}
public function brokenBy(Entity $entity)
{
$this->_messages = array();
foreach ($this->getRules() as $key => $rules) {
$accessor = 'get' . $key;
if (!is_callable(array($entity, $accessor))) {
continue;
}
if (!$rules->isValid($entity->$accessor())) {
$this->_messages[$key] = $rules->getMessages();
}
}
return (bool) count($this->_messages);
}
}
class EntityFormValidator implements \Zend_Validate_Interface
{
protected $_rule;
public function __construct($entity, $property)
{
$this->_entity = $entity;
$this->_rule = $entity->getRuleSet()->getRules($property);
}
public function isValid($value)
{
return $this->_rule->isValid($value);
}
public function getMessages()
{
return $this->_rule->getMessages();
}
}
// implementation:
$form->getElement('foo')->addValidator(new EntityFormValidator($entity, 'foo'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment