Created
November 22, 2012 23:08
-
-
Save anonymous/4133261 to your computer and use it in GitHub Desktop.
Symfony2 Validation comapring string with its Hash
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
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'), | |
) | |
) | |
) | |
} | |
} |
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
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'); | |
} | |
} |
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
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