3 namespace Doctrine\Tests\ORM\Functional;
5 use Doctrine\Tests\Models\CMS\CmsUser;
6 use Doctrine\Tests\Models\CMS\CmsPhonenumber;
7 use Doctrine\ORM\Event\OnFlushEventArgs;
8 use Doctrine\ORM\Events;
10 require_once __DIR__ . '/../../TestInit.php';
17 class FlushEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
19 protected function setUp() {
20 $this->useModelSet('cms');
24 public function testPersistNewEntitiesOnPreFlush()
26 //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
27 $this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener);
30 $user->username = 'romanb';
31 $user->name = 'Roman';
32 $user->status = 'Dev';
34 $this->_em->persist($user);
36 $this->assertEquals(0, $user->phonenumbers->count());
40 $this->assertEquals(1, $user->phonenumbers->count());
41 $this->assertTrue($this->_em->contains($user->phonenumbers->get(0)));
42 $this->assertTrue($user->phonenumbers->get(0)->getUser() === $user);
44 $this->assertFalse($user->phonenumbers->isDirty());
46 // Can be used together with SQL Logging to check that a subsequent flush has
47 // nothing to do. This proofs the correctness of the changes that happened in onFlush.
48 //echo "SECOND FLUSH";
49 //$this->_em->flush();
55 public function onFlush(OnFlushEventArgs $args)
57 //echo "---preFlush".PHP_EOL;
59 $em = $args->getEntityManager();
60 $uow = $em->getUnitOfWork();
62 foreach ($uow->getScheduledEntityInsertions() as $entity) {
64 if ($entity instanceof CmsUser) {
65 // Adds a phonenumber to every newly persisted CmsUser ...
67 $phone = new CmsPhonenumber;
68 $phone->phonenumber = 12345;
69 // Update object model
70 $entity->addPhonenumber($phone);
71 // Invoke regular persist call
73 // Explicitly calculate the changeset since onFlush is raised
74 // after changeset calculation!
75 $uow->computeChangeSet($em->getClassMetadata(get_class($phone)), $phone);
77 // Take a snapshot because the UoW wont do this for us, because
78 // the UoW did not visit this collection.
79 // Alternatively we could provide an ->addVisitedCollection() method
81 $entity->getPhonenumbers()->takeSnapshot();
84 /*foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
85 list ($old, $new) = $change;