Loads the Aggregate from a Snapshot.

@param AggregateInterface $aggregate
@param Snapshot           $snapshot

@return AggregateInterface
18057
public function loadFromSnapshot(AggregateInterface $aggregate, Snapshot $snapshot): AggregateInterface
    {
        $snapshotData = $snapshot->getPayload();

        $aggregate->setVersion($snapshot->getVersion());
        $aggregate->setSnapshotVersion($snapshot->getVersion());
        $aggregate->setCreated($snapshot->getAggregateCreated());
        $aggregate->setModified($snapshot->getAggregateModified());
        $aggregate->setUuid($snapshot->getUuid());
        $aggregate->setHistory($snapshot->getHistory());

        // Load data from other public properties.
        $properties = get_object_vars($aggregate);

        foreach ($properties as $property => $existingValue) {
            // Skip Modified and Created public properties.
            if ('created' === $property || 'modified' === $property) {
                continue;
            }
            // Todo: Convert json date to php DateTime.

            if (isset($snapshotData[$property])) {
                $aggregate->{$property} = $snapshotData[$property];
            }
        }

        return $aggregate;
    }
266739
public static function take(AggregateIdInterface $aggregateId, AggregateRootInterface $aggregate, $version)
    {
        $dateTime = \DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', microtime(true)));

        return new static($aggregateId, $aggregate, $version, $dateTime);
    }
337104
public function save(AggregateInterface $aggregate): void
    {
        $snapshot = new Snapshot();
        $snapshot->setUuid($aggregate->getUuid());
        $snapshot->setVersion($aggregate->getVersion());
        $snapshot->setAggregateCreated($aggregate->getCreated());
        $snapshot->setAggregateModified($aggregate->getModified());
        $snapshot->setAggregateClass(\get_class($aggregate));
        $snapshot->setHistory($aggregate->getHistory());
        $aggregateData = json_decode(json_encode($aggregate), true);
        $snapshot->setPayload($aggregateData);

        try {
            $this->em->persist($snapshot);
            $this->em->flush();
        } catch (OptimisticLockException $e) {
            $this->messageBus->dispatch(new Message(
                $e->getMessage(),
                $e->getCode(),
                null,
                $aggregate->getUuid(),
                $e
            ));
        } catch (UniqueConstraintViolationException $e) {
            $this->messageBus->dispatch(new Message(
                $e->getMessage(),
                $e->getCode(),
                null,
                $aggregate->getUuid(),
                $e
            ));
        }
    }
98704
def aggregate!(ts = Time.now.floor)
      unless self.ancestors.include?MongoMapper::Document
        raise NoMethodError, "aggregate! not defined for this counter"
      end

      aggr = aggregate(ts)
      aggr.each do |_ts, counterVals|
        counterVals.each do |obj, count|
          args = gen_args_for_instance obj, count, _ts, TYPE_MINUTE
          counter = self.new args
          counter.save!
        end
      end
      call_completion_hook(TYPE_MINUTE, ts)
    end
228743
public function executeHandler(CommandInterface $command, AggregateInterface $aggregate): AggregateInterface
    {
        /* Execute method is implemented in final class */
        return $this->execute($command, $aggregate);
    }
913994
public function append(Contract $aggregateRootType, EventStream $eventStream)
    {
        $statement = $this->insertQuery->prepare();

        try {
            while ($eventStream->hasNext()) {
                $event = $eventStream->next();

                $statement->bindValue(':aggregate_id', $event->aggregateRootIdentifier()->toString());
                $statement->bindValue(':aggregate_type', $aggregateRootType->toString());
                $statement->bindValue(':aggregate_version', $event->sequenceNumber());
                $statement->bindValue(':event_id', $event->identifier()->toString());
                $statement->bindValue(':event_payload', $this->eventSerializer->serializePayload($event));
                $statement->bindValue(':event_payload_type', $event->payloadType()->toString());
                $statement->bindValue(':event_metadata', $this->eventSerializer->serializeMetadata($event));
                $statement->bindValue(':event_metadata_type', $event->metadataType()->toString());

                $statement->execute();
                $statement->closeCursor();
            }
        } catch (\PDOException $exception) {
            // 23000 being the primary key duplicate entry error code.
            if ($exception->errorInfo[0] === '23000') {
                throw new ConcurrencyException('Concurrent modification detected.');
            }

            throw $exception;
        }
    }
736649
public function loadFromHistory(AggregateInterface $aggregate, array $eventStreamObjects): AggregateInterface
    {
        // Arrays start at zero ;)
        $count = \count($eventStreamObjects) - 1;

        /**
         * Get events and replay them.
         *
         * @var EventStreamObject $eventStreamObject
         */
        foreach ($eventStreamObjects as $key => $eventStreamObject) {
            $uuid = $eventStreamObject->getUuid();

            // Check if the uuid of the provided Event Stream Object matches.
            if ($uuid !== $aggregate->getUuid()) {
                continue;
            }

            if (0 === $key && null === $aggregate->getCreated()) {
                // Set Created from first EventStreamObject.
                $aggregate->setCreated($eventStreamObject->getCreated());
            }

            if ($key === $count) {
                // Set Modified from last EventStreamObject.
                $aggregate->setModified($eventStreamObject->getCreated());
            }

            $event = EventStore::buildEventFromEventStreamObject($eventStreamObject);

            $aggregate = $this->apply($aggregate, $event);

            // Update the Aggregate history.
            $aggregate->addToHistory([
                'version' => $eventStreamObject->getVersion(),
                'message' => $eventStreamObject->getMessage(),
                'created' => $eventStreamObject->getCreated(),
                'payload' => $eventStreamObject->getPayload(),
            ]);
        }

        return $this->applyChanges($aggregate);
    }
539431
public function aggregate(Criteria $criteria, Context $context): AggregatorResult
    {
        return $this->innerRepo->aggregate($criteria, $context);
    }
731101
public function aggregate($aggregation = [])
    {
        if ($aggregation instanceof Closure) {
            // Store the callback
            $callback = $aggregation;

            // Create a new pipeline
            $aggregation = new Query\Aggregation();

            // Fire the callback
            $callback($aggregation);
        }

        if ($aggregation instanceof Query\Aggregation) {
            // Retrieve the pipeline
            $aggregation = $aggregation->getPipeline();
        }

        // Execute the aggregation.
        return $this->collection->aggregate($aggregation);
    }
928843
public function saveSnapshot(AggregateRoot $aggregate)
    {
        if (is_null($this->snapshotStore)) {
            throw new \Exception('Unable to create snapshot; No store attached');
        }

        if ($aggregate->hasChanges()) {
            $aggregate = $aggregate::reconstituteFrom(
                new CommittedEvents(
                    $aggregate->getIdentity(),
                    $aggregate->getChanges()->getEvents()
                )
            );
        }

        return $this->snapshotStore->save($aggregate);
    }
742254
public static function snapshotName($project, $instance, $cluster, $snapshot)
    {
        return self::getSnapshotNameTemplate()->render([
            'project' => $project,
            'instance' => $instance,
            'cluster' => $cluster,
            'snapshot' => $snapshot,
        ]);
    }
40247
public function deployDatabases(
        string $snapshotPath,
        string $snapshotName,
        array $databases
    ): void {

        if (!$databases) {
            throw new Exception\RuntimeException('No database given for deployment.');
        }

        $application = $this->applicationConfig;
        $this->logger->info('Installing databases');
        foreach ($databases as $databaseName => $database) {
            $adapterName = $database['adapter'] ?? $application->getDefaultDatabaseAdapter();
            $databaseAdapter = $this->databaseAdapterManager->getAdapter($adapterName);
            $adapterName = $database['importexport_adapter'] ??
                $application->getDefaultDatabaseImportExportAdapter();
            $databaseImportExportAdapter = $this->databaseImportAdapterManager->getAdapter($adapterName);

            $filename = "$databaseName." . $databaseImportExportAdapter::getFileExtension();
            $localDatabaseName = $database['local_database_name'] ?? $databaseName;

            if (!$databaseAdapter->databaseExists($localDatabaseName)) {
                $this->logger->debug("Creating database \"$localDatabaseName\".");
                $databaseAdapter->createDatabase($localDatabaseName);
            }

            $workingDir = getcwd() . '/' . DatabaseImportExportAdapterInterface::DEFAULT_WORKING_DIR;
            $this->logger->debug("Downloading database script \"$filename\".");
            $this->mountManager->sync(
                "$snapshotPath/$snapshotName/databases/$filename",
                "local://$workingDir/$filename"
            );

            $databaseImportExportAdapter->importFromFile(
                "$workingDir/$filename",
                $localDatabaseName,
                [] // This command does not yet support any options
            );


            // @todo Deal with running environment scripts
            if (!empty($database['post_import_scripts'])) {
                foreach ($database['post_import_scripts'] as $scriptFilename) {
                    $scriptFilename = $this->findScript($scriptFilename);
                    $scriptFilename = $this->applyStringReplacements(
                        $scriptFilename
                    );

                    $this->logger->debug("Running post import script \"$scriptFilename\".");
                    $databaseAdapter->run(
                        file_get_contents($scriptFilename),
                        $localDatabaseName
                    );
                }
            }
        }
    }
98551
function(obj, callback) {
    if (obj.streamId && !obj.aggregateId) {
      obj.aggregateId = obj.streamId;
    }

    if (!obj.aggregateId) {
      var err = new Error('An aggregateId should be passed!');
      debug(err);
      if (callback) callback(err);
      return;
    }

    obj.streamId = obj.aggregateId;

    var self = this;

    async.waterfall([
        function getNewIdFromStorage(callback) {
          self.getNewId(callback);
        },
        function commit(id, callback) {
          try {
            var snap = new Snapshot(id, obj);
            snap.commitStamp = new Date();
          } catch (err) {
            return callback(err);
          }

          self.store.addSnapshot(snap, function(error) {
            if (self.options.maxSnapshotsCount) {
              self.store.cleanSnapshots(_.pick(obj, 'aggregateId', 'aggregate', 'context'), callback);
            } else {
              callback(error);
            }
          });
        }],
      callback
    );
  }
1237407
public function save(AggregateRoot $root)
    {
        $snapshot = new Snapshot(
            $root,
            $root->getVersion(),
            new \DateTime
        );

        $this->snapshots[(string) $root->getIdentity()][] = $snapshot;
    }
1071459
final public function addAggregateColumn(Aggregate $aggregate)
    {
        $parts = explode(".", $aggregate->getAggregateColumnName());

        if (count($parts) > 1) {
            $columnName = $parts[count($parts) - 1];

            $relationships = array_slice($parts, 0, count($parts) - 1);

            $aggregate->setAliasDerivedColumn(str_replace(".", "", $aggregate->getAggregateColumnName()));
            $aggregate->setAggregateColumnName($columnName);

            $collection = $this->createIntersectionForRelationships($relationships, [$aggregate->getAlias()]);
            $collection->addAggregateColumn($aggregate);
            return $this;
        }

        $this->aggregateColumns[$aggregate->getAlias()] = $aggregate;
        $this->invalidate();

        return $this;
    }
93296
private function executeAggregate(Server $server)
    {
        /* If we've already captured an operation time or the server does not
         * support returning an operation time (e.g. MongoDB 3.6), execute the
         * aggregation directly and return its cursor. */
        if ($this->operationTime !== null || ! \MongoDB\server_supports_feature($server, self::$wireVersionForOperationTime)) {
            return $this->aggregate->execute($server);
        }

        /* Otherwise, execute the aggregation using command monitoring so that
         * we can capture its operation time with commandSucceeded(). */
        \MongoDB\Driver\Monitoring\addSubscriber($this);

        try {
            return $this->aggregate->execute($server);
        } finally {
            \MongoDB\Driver\Monitoring\removeSubscriber($this);
        }
    }
3833
public function load(AggregateId $aggregateId)
    {
        $result = $this->getEntityManager()->find($aggregateId->aggregateClass(), $aggregateId->value());
        Preconditions::checkArgument($result !== null, 'Aggregate with ID [%s] does not exist', $aggregateId);
        return $result;
    }