Skip to content

Instantly share code, notes, and snippets.

Created November 22, 2012 23:08
Show Gist options
  • Save anonymous/4133261 to your computer and use it in GitHub Desktop.
Save anonymous/4133261 to your computer and use it in GitHub Desktop.
Symfony2 Validation comapring string with its Hash
use Acme\DemoBundle\Validator\Constraints\StringMatchItsHash;
class SmokeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('smoke', 'hidden', array(
'data' => 'smoke'
)
)
->add('smoke_hash', 'hidden', array(
'data' => sha1('MYSUPERSECURESALT'.'smoke'),
'property_path' => false,
'constraints' => array(
new StringMatchItsHash('smoke'),
)
)
)
}
}
namespace Acme\DemoBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class StringMatchItsHash extends Constraint
{
public $message = 'Are you craking me?';
public $field;
/**
* {@inheritDoc}
*/
public function getDefaultOption()
{
return 'field';
}
/**
* {@inheritDoc}
*/
public function getRequiredOptions()
{
return array('field');
}
}
namespace Acme\DemoBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class StringMatchItsHashValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
$user = sha1('MYSUPERSECURESALT'.$this->context->getRoot()->get($constraint->field)->getData());
if ($value !== $user) {
$this->context->addViolation($constraint->message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment