FlushEventTest.php 3.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Doctrine\Tests\ORM\Functional;
  3. use Doctrine\Tests\Models\CMS\CmsUser;
  4. use Doctrine\Tests\Models\CMS\CmsPhonenumber;
  5. use Doctrine\ORM\Event\OnFlushEventArgs;
  6. use Doctrine\ORM\Events;
  7. require_once __DIR__ . '/../../TestInit.php';
  8. /**
  9. * FlushEventTest
  10. *
  11. * @author robo
  12. */
  13. class FlushEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
  14. {
  15. protected function setUp() {
  16. $this->useModelSet('cms');
  17. parent::setUp();
  18. }
  19. public function testPersistNewEntitiesOnPreFlush()
  20. {
  21. //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
  22. $this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener);
  23. $user = new CmsUser;
  24. $user->username = 'romanb';
  25. $user->name = 'Roman';
  26. $user->status = 'Dev';
  27. $this->_em->persist($user);
  28. $this->assertEquals(0, $user->phonenumbers->count());
  29. $this->_em->flush();
  30. $this->assertEquals(1, $user->phonenumbers->count());
  31. $this->assertTrue($this->_em->contains($user->phonenumbers->get(0)));
  32. $this->assertTrue($user->phonenumbers->get(0)->getUser() === $user);
  33. $this->assertFalse($user->phonenumbers->isDirty());
  34. // Can be used together with SQL Logging to check that a subsequent flush has
  35. // nothing to do. This proofs the correctness of the changes that happened in onFlush.
  36. //echo "SECOND FLUSH";
  37. //$this->_em->flush();
  38. }
  39. }
  40. class OnFlushListener
  41. {
  42. public function onFlush(OnFlushEventArgs $args)
  43. {
  44. //echo "---preFlush".PHP_EOL;
  45. $em = $args->getEntityManager();
  46. $uow = $em->getUnitOfWork();
  47. foreach ($uow->getScheduledEntityInsertions() as $entity) {
  48. if ($entity instanceof CmsUser) {
  49. // Adds a phonenumber to every newly persisted CmsUser ...
  50. $phone = new CmsPhonenumber;
  51. $phone->phonenumber = 12345;
  52. // Update object model
  53. $entity->addPhonenumber($phone);
  54. // Invoke regular persist call
  55. $em->persist($phone);
  56. // Explicitly calculate the changeset since onFlush is raised
  57. // after changeset calculation!
  58. $uow->computeChangeSet($em->getClassMetadata(get_class($phone)), $phone);
  59. // Take a snapshot because the UoW wont do this for us, because
  60. // the UoW did not visit this collection.
  61. // Alternatively we could provide an ->addVisitedCollection() method
  62. // on the UoW.
  63. $entity->getPhonenumbers()->takeSnapshot();
  64. }
  65. /*foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
  66. list ($old, $new) = $change;
  67. var_dump($old);
  68. }*/
  69. }
  70. }
  71. }