/** * @param TakeSnapshot $command * @throws Exception\RuntimeException */ public function __invoke(TakeSnapshot $command) { $aggregateType = $command->aggregateType(); if (!isset($this->aggregateRepositories[$aggregateType])) { throw new Exception\RuntimeException(sprintf('No repository for aggregate type %s configured', $command->aggregateType())); } $repository = $this->aggregateRepositories[$aggregateType]; $aggregateRoot = $repository->getAggregateRoot($command->aggregateId()); if (null === $aggregateRoot) { throw new RuntimeException(sprintf('Could not find aggregate root %s with id %s', $aggregateType, $command->aggregateId())); } $this->snapshotStore->save(new Snapshot(AggregateType::fromAggregateRootClass($aggregateType), $command->aggregateId(), $aggregateRoot, $repository->extractAggregateVersion($aggregateRoot), $command->createdAt())); }
/** * @test */ public function it_uses_snapshot_store_and_applies_pending_events() { $this->prepareSnapshotStoreAggregateRepository(); $this->eventStore->beginTransaction(); $user = User::create('John Doe', '*****@*****.**'); $this->repository->addAggregateRoot($user); $this->eventStore->commit(); $snapshot = new Snapshot(AggregateType::fromAggregateRootClass('ProophTest\\EventStore\\Mock\\User'), $user->getId()->toString(), $user, 1, new \DateTimeImmutable('now', new \DateTimeZone('UTC'))); $this->snapshotStore->save($snapshot); $this->eventStore->beginTransaction(); $fetchedUser = $this->repository->getAggregateRoot($user->getId()->toString()); $fetchedUser->changeName('Max Mustermann'); $this->eventStore->commit(); $loadedEvents = []; $this->eventStore->getActionEventEmitter()->attachListener('loadEventsByMetadataFrom.post', function (ActionEvent $event) use(&$loadedEvents) { foreach ($event->getParam('streamEvents', []) as $streamEvent) { $loadedEvents[] = $streamEvent; } $event->getParam('streamEvents')->rewind(); }); $this->repository->getAggregateRoot($user->getId()->toString()); $this->assertCount(1, $loadedEvents); $this->assertInstanceOf(UsernameChanged::class, $loadedEvents[0]); $this->assertEquals(2, $this->repository->extractAggregateVersion($fetchedUser)); }