Created
May 29, 2014 15:19
-
-
Save jmikola/7dff669cddf96cea3f30 to your computer and use it in GitHub Desktop.
Functional test for http://stackoverflow.com/q/23927996/162228
This file contains hidden or 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 Doctrine\ODM\MongoDB\Tests; | |
use Doctrine\Common\EventSubscriber; | |
use Doctrine\ODM\MongoDB\Events; | |
use Doctrine\ODM\MongoDB\Event\PreUpdateEventArgs; | |
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; | |
class SO23927996Test extends BaseTest | |
{ | |
public function testFoo() | |
{ | |
$this->dm->getEventManager()->addEventSubscriber(new SO23927996Listener()); | |
$foo = new SO23927996Foo(); | |
$foo->name = 'foo'; | |
$this->dm->persist($foo); | |
$this->dm->flush(); | |
$this->dm->clear(); | |
$foo = $this->findSingleDocument(__NAMESPACE__ . '\SO23927996Foo'); | |
$bar = $this->findSingleDocument(__NAMESPACE__ . '\SO23927996Bar'); | |
$this->assertEquals('foo', $foo->name); | |
$this->assertNull($bar); | |
$foo->name = 'foo-modified'; | |
$this->dm->flush(); | |
$this->dm->clear(); | |
$foo = $this->findSingleDocument(__NAMESPACE__ . '\SO23927996Foo'); | |
$bar = $this->findSingleDocument(__NAMESPACE__ . '\SO23927996Bar'); | |
$this->assertEquals('foo-modified', $foo->name); | |
$this->assertEquals('bar', $bar->name); | |
$this->assertSame($foo, $bar->refOne); | |
} | |
private function findSingleDocument($class) | |
{ | |
return $this->dm->createQueryBuilder($class)->getQuery()->getSingleResult(); | |
} | |
} | |
/** @ODM\Document */ | |
class SO23927996Foo | |
{ | |
/** @ODM\Id */ | |
public $id; | |
/** @ODM\String */ | |
public $name; | |
} | |
/** @ODM\Document */ | |
class SO23927996Bar | |
{ | |
/** @ODM\Id */ | |
public $id; | |
/** @ODM\String */ | |
public $name; | |
/** @ODM\ReferenceOne(targetDocument="SO23927996Foo") */ | |
public $refOne; | |
} | |
class SO23927996Listener implements EventSubscriber | |
{ | |
public function getSubscribedEvents() | |
{ | |
return array(Events::preUpdate); | |
} | |
public function preUpdate(PreUpdateEventArgs $args) | |
{ | |
$document = $args->getDocument(); | |
if ($document instanceOf SO23927996Foo) { | |
$bar = new SO23927996Bar(); | |
$bar->name = 'bar'; | |
$bar->refOne = $document; | |
$dm = $args->getDocumentManager(); | |
$dm->persist($bar); | |
$class = $dm->getClassMetadata(get_class($bar)); | |
$dm->getUnitOfWork()->recomputeSingleDocumentChangeSet($class, $bar); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment