Builds an aggregate from a provided Uuid and Aggregate class.

@param string   $uuid
@param string   $aggregateClass
@param int|null $max_version
@param int|null $user

@return AggregateInterface
546003
public function build(string $uuid, string $aggregateClass, int $max_version = null, int $user = null): AggregateInterface
    {
        try {
            /**
             * @var AggregateInterface $aggregate
             */
            $aggregate = new $aggregateClass($uuid);

            if ($aggregate instanceof AggregateInterface) {
                /**
                 * Get latest matching Snapshot.
                 *
                 * @var Snapshot $snapshot
                 */
                $snapshot = $this->snapshotStore->find($uuid, $max_version);
                $min_version = $snapshot ? ($snapshot->getVersion() + 1) : null;
                if ($snapshot) {
                    $aggregate = $this->loadFromSnapshot($aggregate, $snapshot);
                }

                /**
                 * Get Event Stream Objects.
                 *
                 * @var EventStreamObject[] $eventStreamObjects
                 */
                $eventStreamObjects = $this->eventStore->find($uuid, $max_version, $min_version);
                if ($eventStreamObjects) {
                    $aggregate = $this->loadFromHistory($aggregate, $eventStreamObjects);
                }

                // Set the current version that is recorded in the event stream.
                $aggregate->setStreamVersion($aggregate->getVersion());

                if (null !== $user) {
                    /**
                     * Get qeued Event Stream Objects.
                     *
                     * @var EventStreamObject[] $eventStreamObjects
                     */
                    $eventStreamObjects = $this->eventStore->findQeued($uuid, $max_version, $aggregate->getVersion() + 1, $user);
                    if ($eventStreamObjects) {
                        $aggregate = $this->loadFromHistory($aggregate, $eventStreamObjects);
                    }
                }
            } else {
                // Instantiate generic Aggregate to prevent Handler from failing.
                $aggregate = new Aggregate($uuid);
                throw new AggregateException($aggregateClass.' must implement '.AggregateInterface::class);
            }
        } catch (AggregateException $e) {
            $this->messageBus->dispatch(new Message(
                $e->getMessage(),
                $e->getCode(),
                null,
                $uuid,
                $e
            ));
        }

        return $aggregate;
    }
149816
public function getAggregation(
        ConnectionInterface $connection,
        $addedAggregateNames = []
    ) {
        if (!$this->annotations) {
            return [];
        }
        $hasLimit = ($this->offset || $this->limit);
        $hasExistingAnnotations = false;
        foreach ($this->annotations as $alias => $annotation) {
            $hasExistingAnnotations = ($hasExistingAnnotations ||
                !in_array($alias, $addedAggregateNames));
        }

        // we have of $hasExistingAnnotations  we need to make the core query a
        // subquery and aggregate over it.
        if ($hasExistingAnnotations || $hasLimit || $this->distinct ||
            is_array($this->groupBy)) {
            $outQuery = new AggregateQuery($this->model);
            $innerQuery = $this->deepClone();

            $innerQuery->selectRelected = false;

            if (!$hasLimit && !$this->distinctFields) {
                // Queries with distinct_fields need ordering and when a limit
                // is applied we must take the slice from the ordered query.
                // Otherwise no need for ordering, so clear.
                $innerQuery->clearOrdering(true);
            }

            if (!$innerQuery->distinct) {
                // if we are using default columns and we already have
                // aggregate annotations existing
                // then we must make sure the inner
                // query is grouped by the main model's primary key. However,
                // clearing the select clause can alter results if distinct is
                // used.
                if ($innerQuery->useDefaultCols && $hasExistingAnnotations) {
                    $innerQuery->groupBy = [
                        $this->getMeta()->primaryKey
                            ->getColExpression($innerQuery->getInitialAlias()),
                    ];
                }
                $innerQuery->useDefaultCols = false;
            }

            // add annotations to the outerquery todo
            foreach ($innerQuery->annotations as $alias => $annotation) {
                if ($annotation->isSummarize()) {
                    $outQuery->annotations[$alias] = $annotation;
                    unset($innerQuery->annotations[$alias]);
                }
            }

            if ($innerQuery->select == [] && !$innerQuery->useDefaultCols) {
                $innerQuery->select = [
                    $this->getMeta()->primaryKey->getColExpression(
                        $innerQuery->getInitialAlias()
                    ),
                ];
            }

            $outQuery->addSubQuery($innerQuery, $connection);
        } else {
            $outQuery = $this;
            $outQuery->select = [];
            $outQuery->useDefaultCols = false;
        }
        $outQuery->clearOrdering(true);
        $outQuery->clearLimits();
        $outQuery->selectRelected = false;

        $results = $outQuery->getSqlCompiler($connection)
            ->executeSql()->fetch();

        $result = [];
        foreach (array_combine(
                     array_keys($outQuery->annotations),
                     array_values($results)
                 ) as $key => $item) {
            $result[$key] = $item;
        }

        return $result;
    }
401160
private static function generate($uuidKey, array $arguments)
    {
        $classAndMethod = \explode('::', self::$uuidMap[$uuidKey]);

        return \call_user_func_array($classAndMethod, $arguments);
    }
922056
public static function retrieve($uuid, ClientInterface $client = null)
    {
        return (new RequestService($client))
            ->setResourceClass(static::class)
            ->get($uuid);
    }
956871
public function byUuid(AggregateUuid $uuid, $returnType = self::RETURN_AS_ARRAY)
    {
        return (isset($this->events[(string) $uuid])) ? $this->buildEventAggregate($uuid, $returnType) : null;
    }
455805
private function createAttributesQuery(User $user)
    {
        $query = $this->getEntityManager()
            ->createQuery('
                SELECT ua
                FROM UserBundle:UserAttribute ua
                LEFT JOIN ua.groups ug
                INDEX BY ua.id
                WHERE ug.id IN (:groupIds)
            ')
        ->setParameters([
            ':groupIds' => $user->getGroupIds(),
        ]);

        return $query;
    }
902312
public static Aggregation translateAggregateCall(
      final PlannerContext plannerContext,
      final DruidQuerySignature querySignature,
      final RexBuilder rexBuilder,
      final Project project,
      final List<Aggregation> existingAggregations,
      final String name,
      final AggregateCall call,
      final boolean finalizeAggregations
  )
  {
    final DimFilter filter;

    if (call.filterArg >= 0) {
      // AGG(xxx) FILTER(WHERE yyy)
      if (project == null) {
        // We need some kind of projection to support filtered aggregations.
        return null;
      }

      final RexNode expression = project.getChildExps().get(call.filterArg);
      final DimFilter nonOptimizedFilter = Expressions.toFilter(plannerContext, querySignature, expression);
      if (nonOptimizedFilter == null) {
        return null;
      } else {
        filter = Filtration.create(nonOptimizedFilter).optimizeFilterOnly(querySignature).getDimFilter();
      }
    } else {
      filter = null;
    }

    final SqlAggregator sqlAggregator = plannerContext.getOperatorTable()
                                                      .lookupAggregator(call.getAggregation());

    if (sqlAggregator == null) {
      return null;
    }

    // Compute existingAggregations for SqlAggregator impls that want it.
    final List<Aggregation> existingAggregationsWithSameFilter = new ArrayList<>();
    for (Aggregation existingAggregation : existingAggregations) {
      if (filter == null) {
        final boolean doesMatch = existingAggregation.getAggregatorFactories().stream().noneMatch(
            factory -> factory instanceof FilteredAggregatorFactory
        );

        if (doesMatch) {
          existingAggregationsWithSameFilter.add(existingAggregation);
        }
      } else {
        final boolean doesMatch = existingAggregation.getAggregatorFactories().stream().allMatch(
            factory -> factory instanceof FilteredAggregatorFactory &&
                       ((FilteredAggregatorFactory) factory).getFilter().equals(filter)
        );

        if (doesMatch) {
          existingAggregationsWithSameFilter.add(
              Aggregation.create(
                  existingAggregation.getVirtualColumns(),
                  existingAggregation.getAggregatorFactories().stream()
                                     .map(factory -> ((FilteredAggregatorFactory) factory).getAggregator())
                                     .collect(Collectors.toList()),
                  existingAggregation.getPostAggregator()
              )
          );
        }
      }
    }

    final Aggregation retVal = sqlAggregator.toDruidAggregation(
        plannerContext,
        querySignature,
        rexBuilder,
        name, call, project, existingAggregationsWithSameFilter,
        finalizeAggregations
    );

    if (retVal == null) {
      return null;
    } else {
      // Check if this refers to the existingAggregationsWithSameFilter. If so, no need to apply the filter.
      if (isUsingExistingAggregation(retVal, existingAggregationsWithSameFilter)) {
        return retVal;
      } else {
        return retVal.filter(querySignature, filter);
      }
    }
  }
782732
public function serialize(VisitorInterface $visitor, ?UuidInterface $uuid, Type $type, Context $context): ?string
    {
        if (null === $uuid) {
            return $visitor->visitNull(null, Type::null(), $context);
        }

        return $visitor->visitString($uuid->toString(), $type, $context);
    }
214257
public function load(AggregateId $aggregateId) : AggregateRoot
    {
        return $this->getProperRepository($aggregateId->aggregateClass())->load($aggregateId);
    }
228743
public function executeHandler(CommandInterface $command, AggregateInterface $aggregate): AggregateInterface
    {
        /* Execute method is implemented in final class */
        return $this->execute($command, $aggregate);
    }
1121069
public function getSubresource(string $resourceClass, array $identifiers, array $context, string $operationName = null)
    {
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
        if (!$manager instanceof DocumentManager) {
            throw new ResourceClassNotSupportedException(sprintf('The manager for "%s" must be an instance of "%s".', $resourceClass, DocumentManager::class));
        }

        $repository = $manager->getRepository($resourceClass);
        if (!$repository instanceof DocumentRepository) {
            throw new RuntimeException(sprintf('The repository for "%s" must be an instance of "%s".', $resourceClass, DocumentRepository::class));
        }

        if (!isset($context['identifiers'], $context['property'])) {
            throw new ResourceClassNotSupportedException('The given resource class is not a subresource.');
        }

        $aggregationBuilder = $this->buildAggregation($identifiers, $context, $repository->createAggregationBuilder(), \count($context['identifiers']));

        if (true === $context['collection']) {
            foreach ($this->collectionExtensions as $extension) {
                $extension->applyToCollection($aggregationBuilder, $resourceClass, $operationName, $context);
                if ($extension instanceof AggregationResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName, $context)) {
                    return $extension->getResult($aggregationBuilder, $resourceClass, $operationName, $context);
                }
            }
        } else {
            foreach ($this->itemExtensions as $extension) {
                $extension->applyToItem($aggregationBuilder, $resourceClass, $identifiers, $operationName, $context);
                if ($extension instanceof AggregationResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName, $context)) {
                    return $extension->getResult($aggregationBuilder, $resourceClass, $operationName, $context);
                }
            }
        }

        $iterator = $aggregationBuilder->hydrate($resourceClass)->execute();

        return $context['collection'] ? $iterator->toArray() : ($iterator->current() ?: null);
    }
1352141
protected function createRegistrationRecord(UserInterface $user)
    {
        $entityClass = $this->getOptions()->getRegistrationEntityClass();
        $entity = new $entityClass($user);
        $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'record' => $entity));
        $entity->generateToken();
        $this->getUserRegistrationMapper()->insert($entity);
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user, 'record' => $entity));

        return $entity;
    }
239979
public function byUuid(AggregateUuid $uuid, $returnType = self::RETURN_AS_ARRAY)
    {
        $uuid = (string) $uuid;
        $query = 'SELECT
                  `uuid`,
                  `version`,
                  `payload`,
                  `type`,
                  `body`,
                  `occurred_on`
                FROM `'.PdoDriver::EVENTSTORE_TABLE_NAME.'` 
                WHERE `uuid` = :uuid
                ORDER BY `occurred_on` ASC';
        $stmt = $this->pdo->prepare($query);
        $stmt->bindParam(':uuid', $uuid);
        $stmt->execute();

        $row = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        if (!empty($row)) {
            return $this->buildEventAggregate($row, $returnType);
        }

        return null;
    }
614814
private function createBatch($userId)
    {
        $entity = new EBatch();
        $entity->setUserRef($userId);
        $result = $this->daoBatch->create($entity);
        return $result;
    }
941668
public function createUser($login_name, $organization, $userClassName, $userId)
    {
        $now = new \MUtil_Db_Expr_CurrentTimestamp();;

        $values['gul_user_class'] = $userClassName;
        $values['gul_can_login']  = 1;
        $values['gul_changed']    = $now;
        $values['gul_changed_by'] = $userId;

        $select = $this->db->select();
        $select->from('gems__user_logins', array('gul_id_user'))
                ->where('gul_login = ?', $login_name)
                ->where('gul_id_organization = ?', $organization)
                ->limit(1);

        // Update class definition if it already exists
        if ($login_id = $this->db->fetchOne($select)) {
            $where = implode(' ', $select->getPart(\Zend_Db_Select::WHERE));
            $this->db->update('gems__user_logins', $values, $where);

        } else {
            $values['gul_login']           = $login_name;
            $values['gul_id_organization'] = $organization;
            $values['gul_created']         = $now;
            $values['gul_created_by']      = $userId;

            $this->db->insert('gems__user_logins', $values);
        }

        return $this->getUser($login_name, $organization);
    }
1315012
public function load(AggregateRootIdentifier $aggregateRootIdentifier, $expectedVersion = null)
    {
        $eventStream = $this->eventStore->read($this->aggregateRootType, $aggregateRootIdentifier);
        if ($eventStream->isEmpty()) {
            throw new AggregateNotFoundException($aggregateRootIdentifier);
        }

        $className = $this->aggregateRootType->className();
        $aggregateRoot = $className::loadFromHistory($eventStream);

        $actualVersion = $aggregateRoot->lastCommittedEventSequenceNumber();
        if (null !== $expectedVersion && $actualVersion !== $expectedVersion) {
            throw new ConflictingAggregateVersionException($aggregateRootIdentifier, $actualVersion, $expectedVersion);
        }

        return $this->unitOfWork->registerAggregate(
            $aggregateRoot,
            $this->eventBus,
            $this->createSaveAggregateCallback()
        );
    }
1075344
private function initialize(string $aggregateClassName, string $methodName, bool $isCommandHandler, bool $isAggregateBased): void
    {
        if (!$isAggregateBased) {
            $this->registerRequiredReference($aggregateClassName);

            return;
        }

        $interfaceToCall = InterfaceToCall::create($aggregateClassName, $methodName);

        if ($interfaceToCall->hasReturnValue() && !$interfaceToCall->isStaticallyCalled() && $isCommandHandler) {
            throw InvalidArgumentException::create("{$aggregateClassName} with method {$methodName} must not return value for command handling");
        }

        if (!$interfaceToCall->hasReturnValue() && !$isCommandHandler) {
            throw InvalidArgumentException::create("{$aggregateClassName} with method {$methodName} must return value for query handling");
        }
    }