Created
September 23, 2012 08:12
-
-
Save hakisa-jerome/3769317 to your computer and use it in GitHub Desktop.
Prevent invalid entities from being updated
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 Acme\DemoBundle\EventListener; | |
use Symfony\Component\Validator\Validator; | |
use Doctrine\ORM\Event\LifecycleEventArgs; | |
/** | |
* Prevent invalid entities from being updated | |
* | |
* Here is an example on how to define your listener in yaml format: | |
* cognard_user.listener.validator_listener: | |
* class: Acme\DemoBundle\EventListener\ValidatorListener | |
* arguments: | |
* - @validator | |
* tags: | |
* - { name: doctrine.event_listener, event: preUpdate } | |
* public: false | |
* | |
* @author Jérôme Cognard <jerome.cognard@gmail.com> | |
*/ | |
class ValidatorListener | |
{ | |
/** | |
* @var \Symfony\Component\Validator\Validator | |
*/ | |
private $validator; | |
/** | |
* @param \Symfony\Component\Validator\Validator $validator | |
*/ | |
public function __construct(Validator $validator) | |
{ | |
$this->validator = $validator; | |
} | |
/** | |
* @param \Doctrine\ORM\Event\LifecycleEventArgs $args | |
*/ | |
public function preUpdate(LifecycleEventArgs $args) | |
{ | |
$entity = $args->getEntity(); | |
$errors = $this->validator->validate($entity); | |
// If entity is invalid | |
if (count($errors) > 0) { | |
$em = $args->getEntityManager(); | |
$uw = $em->getUnitOfWork(); | |
// Clear changes | |
$uw->clearEntityChangeSet(spl_object_hash($entity)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment