/** * @param EventStream $stream */ public function reconstituteFromEventStream(EventStream $stream) { if ($this->events) { throw new RuntimeException('AggregateRoot is already reconstituted from event stream.'); } $this->setId($stream->getAggregateId()); /** @var EventInterface $event */ foreach ($stream as $event) { $this->executeEvent($event); } }
/** * Persist new AR events * @param EventStream $stream * @return void * @throws \Exception */ public function commit(EventStream $stream) { $newEvents = $stream->getNewEvents(); $newEventsQuantity = count($newEvents); if (!$newEventsQuantity) { return; } $aggregateRootId = $stream->getAggregateId(); $aggregateName = $stream->getAggregateName(); $currentVersion = $stream->getVersion(); $newVersion = $currentVersion + $newEventsQuantity; $eventData = []; /** @var EventInterface $event */ foreach ($newEvents as $event) { $eventData[] = $this->serializer->serialize($event); } $currentStoredVersion = $this->storage->getCurrentVersion($aggregateRootId); if ($currentVersion !== $currentStoredVersion) { throw new ConcurrencyException('Aggregate root versions mismatch'); } $this->storage->write($aggregateRootId, $aggregateName, $eventData, $newVersion); $stream->markAllApplied($newVersion); return; }