@param array  $referenceModels
@param string $originManager
@param array  $fields          List of fields prime (optional)

@return array
198082
public function buildAll(array $referenceModels, $originManager, array $fields = array())
    {
        $this->getManagersPerCollection($referenceModels, $fields);
        $result = $this->getResult($referenceModels, $originManager);

        // pre-init data
        $models = array();
        foreach ($referenceModels as $referenceModel) {
            $data = array();

            if (isset($result[$this->class->getIdentifierValue($referenceModel)])) {
                $data = $result[$this->class->getIdentifierValue($referenceModel)];
            }

            $data[$originManager] = $referenceModel;

            $models[] = $this->createModel($this->class->getName(), $data);
        }

        return $models;
    }
177834
protected static function executeFieldsSerially(ExecutionContext $context, ObjectType $parent, $source, $fields)
    {
        $results = [];
        foreach ($fields as $response => $asts) {
            $result = self::resolveField($context, $parent, $source, $asts);

            if ($result !== self::$UNDEFINED) {
                // Undefined means that field is not defined in schema.
                $results[$response] = $result;
            }
        }

        return $results;
    }
418026
protected function getListBuilder($entityName, $fieldDescriptors)
    {
        /** @var RestHelperInterface $restHelper */
        $restHelper = $this->get('sulu_core.doctrine_rest_helper');

        /** @var DoctrineListBuilderFactory $factory */
        $factory = $this->get('sulu_core.doctrine_list_builder_factory');

        $listBuilder = $factory->create($entityName);

        $restHelper->initializeListBuilder(
            $listBuilder,
            $fieldDescriptors
        );

        return $listBuilder;
    }
886810
private function lexFragment(LexerInterface $referenceLexer, string $valueFragment): array
    {
        foreach (self::PATTERNS as $pattern => $tokenTypeConstant) {
            if (1 === preg_match($pattern, $valueFragment, $matches)) {
                if (null === $tokenTypeConstant) {
                    throw InvalidArgumentExceptionFactory::createForInvalidExpressionLanguageToken($valueFragment);
                }

                $match = $matches[1];
                if (self::REFERENCE_LEXER === $tokenTypeConstant) {
                    return $referenceLexer->lex($match);
                }

                return [new Token($match, new TokenType($tokenTypeConstant))];
            }
        }

        return [new Token($valueFragment, new TokenType(TokenType::STRING_TYPE))];
    }
1335833
public static function createReferenceMany(
        string $name,
        string $idName = 'id'
    ): NormalizationFieldMappingBuilderInterface {
        $self = new self($name);
        $self->fieldNormalizer = new ReferenceManyFieldNormalizer(
            new PropertyAccessor($idName),
            new PropertyAccessor($name)
        );

        return $self;
    }
1181159
private function setArrayToFilterValues($entryArray, $referenceTable = '')
    {
        $filters  = [];
        $refTable = $this->correctTableWithQuotesAsFieldPrefix($referenceTable);
        foreach ($entryArray as $key => $value) {
            if (is_array($value)) {
                $filters[] = $this->setArrayLineArrayToFilter($key, $value, $refTable);
            } elseif (!in_array($value, ['', '%%'])) {
                $filters[] = $this->setArrayLineToFilter($key, $value);
            }
        }
        return implode(' AND ', array_diff($filters, ['']));
    }
1067550
private static function parseManyToManyQueryFields($middleModel, $rightModel, &$middleFields, &$rightFields)
    {
        $middleFields = [];
        $rightFields = [];

        $middleTable = ModelManager::getTable($middleModel);
        $rightTable = ModelManager::getTable($rightModel);

        foreach(ModelManager::getFieldNames($middleModel) as $name)
        {
            $middleFields[$middleTable . '_' . $name] = $name;
        }

        foreach(ModelManager::getFieldNames($rightModel) as $name)
        {
            $rightFields[$rightTable . '_' . $name] = $name;
        }
    }
1039748
private function getAggregatorsFromEntities(ObjectManager $objectManager, array $entities)
    {
        $aggregators = [];

        foreach ($entities as $entity) {
            $entityClassName = ClassUtils::getClass($entity);
            if (array_key_exists($entityClassName, $this->entitiesAggregators)) {
                foreach ($this->entitiesAggregators[$entityClassName] as $aggregator) {
                    $aggregators[] = new $aggregator($entity, $objectManager->getClassMetadata($entityClassName)->getIdentifierValues($entity));
                }
            }
        }

        return $aggregators;
    }
1310411
protected function assignFields($fields)
    {
        foreach ($fields as $field) {
            if (!$field instanceof FieldInterface) {
                throw new ModelException(sprintf('Field must be an instance of FieldInterface, got "%s"', $this->getType($field)));
            }

            $field->table($this->table);
            $this->fields[$field->name()] = $field;
        }
    }
1265978
protected function getManagersPerCollection(array $referenceModels, array $fields = array())
    {
        $this->collections->clean();

        if (empty($fields)) {
            return;
        }

        foreach ($this->class->getAssociationDefinitions() as $assoc) {
            $compatible = $assoc->getCompatible();

            if (!empty($compatible) && !in_array($this->class->getManagerIdentifier(), $compatible)) {
                continue;
            }

            foreach ($referenceModels as $referenceModel) {
                $property = $assoc->getReferenceField($this->class->getManagerIdentifier());

                if (!in_array($property, $fields)) {
                    continue;
                }

                /** @var null|object|ArrayCollection $coll */
                $coll = call_user_func(array($referenceModel, 'get' . ucfirst($property)));

                if (null === $coll || $assoc->isMany() && $coll->isEmpty()) {
                    continue;
                }

                $this->collections->append(new CollectionCenter($assoc, $this->manager->getClassMetadata($assoc->getTargetMultiModel()), $coll, $this->class->getIdentifierValue($referenceModel)));
            }
        }
    }
493511
public function resolveMany(array $references)
    {
        $convertedParameters = array();

        foreach ($references as $reference) {
            $convertedValue = $this->resolve($reference);
            $convertedParameters[] = $convertedValue;
        }

        return $convertedParameters;
    }
704893
public function getReferencedFiles(array $fieldIds, $versionNo)
    {
        if (empty($fieldIds)) {
            return array();
        }

        $connection = $this->getConnection();

        $selectQuery = $connection->createSelectQuery();
        $selectQuery->select(
            $connection->quoteColumn('filename'),
            $connection->quoteColumn('mime_type')
        )->from(
            $connection->quoteTable($this->getStorageTable())
        )->where(
            $selectQuery->expr->lAnd(
                $selectQuery->expr->in(
                    $connection->quoteColumn('contentobject_attribute_id'),
                    $fieldIds
                ),
                $selectQuery->expr->eq(
                    $connection->quoteColumn('version'),
                    $selectQuery->bindValue($versionNo, null, \PDO::PARAM_INT)
                )
            )
        );

        $statement = $selectQuery->prepare();
        $statement->execute();

        $gateway = $this;

        return array_map(
            function ($row) use ($gateway) {
                return $gateway->prependMimeToPath($row['filename'], $row['mime_type']);
            },
            $statement->fetchAll(\PDO::FETCH_ASSOC)
        );
    }
763045
public function resolveReferences(ReferenceContext $context = null)
    {
        foreach ($this->_properties as $property => $value) {
            if ($value instanceof Reference) {
                $this->_properties[$property] = $value->resolve($context);
            } elseif ($value instanceof SpecObjectInterface) {
                $value->resolveReferences($context);
            } elseif (is_array($value)) {
                foreach ($value as $k => $item) {
                    if ($item instanceof Reference) {
                        $this->_properties[$property][$k] = $item->resolve($context);
                    } elseif ($item instanceof SpecObjectInterface) {
                        $item->resolveReferences($context);
                    }
                }
            }
        }
    }
282841
protected function getReferencesForModelKeys(array $keys, $targetModel = null)
    {
        $keys = array_filter($keys);

        if ( ! count($keys)) {
            return [];
        }

        $referenceData = $this->getReferenceDataProvider()->getForModelClassByType(
            $this->model,
            'form.field',
            $this->field->key(),
            $targetModel
        );

        if ( ! $referenceData) {
            return [];
        }

        $references = [];

        foreach ($keys as $key) {
            $references[ $key ] = $this->getReferenceRepository()
                ->getReferenceForModelMetaReferenceByKey($referenceData, $key);
        }

        return $references;
    }
1111336
public function loaderModels(ClassMetadata $class, $manager, array $ids, \Closure $stacker)
    {
        $classOfManagerName = $class->getFieldMapping($manager);

        $pool       = $this->manager->getPool();
        $methodFind = $classOfManagerName->getRepositoryMethod();

        $repository = $pool->getManager($manager)->getRepository($classOfManagerName->getName());

        if ($methodFind && method_exists($repository, $methodFind)) {
            foreach ($repository->$methodFind($ids) as $object) {
                $id = $class->getIdentifierValue($object);

                $stacker($id, $object);
            }
        } else {
            trigger_error(sprintf('findOneBy in ModelPersister::loadAll context is depreciate. Define repository-method for "%s" manager model, see mapping for "%s".', $manager, $class->getName()), E_USER_DEPRECATED);

            $repository = $pool->getManager($manager)->getRepository($classOfManagerName->getName());
            $field      = $class->getIdentifierReference($manager)->field;

            foreach ($ids as $id) {
                $object = $repository->findOneBy(array($field => $id));

                if (!$object) {
                    continue;
                }

                $id = $class->getIdentifierValue($object, $manager);

                $stacker($id, $object);
            }
        }
    }
656594
protected function _inferReferenceField($primaryModel, $model)
    {
        /** @var \ManaPHP\ModelInterface $model */
        $modelTail = ($pos = strrpos($model, '\\')) !== false ? substr($model, $pos + 1) : $model;
        $tryField = lcfirst($modelTail) . '_id';
        $fields = $primaryModel->getFields();
        if (in_array($tryField, $fields, true)) {
            return $tryField;
        } elseif (preg_match('#([A-Z][a-z]*)$#', $modelTail, $match) === 1) {
            $tryField = $match[1] . '_id';
            /** @noinspection NotOptimalIfConditionsInspection */
            if (in_array($tryField, $fields, true)) {
                return $tryField;
            }
        }

        throw new NotSupportedException(['infer referenceField from `:model` failed.', 'model' => $model]);
    }
75466
public static function resolveDiscriminatorsForClass(
        ClassMetadata $rootClassMetadata,
        EntityManagerInterface $entityManager
    ) : array {
        $hierarchyClasses   = $rootClassMetadata->getSubClasses();
        $hierarchyClasses[] = $rootClassMetadata->getClassName();

        $discriminators = [];

        foreach ($hierarchyClasses as $class) {
            $currentMetadata      = $entityManager->getClassMetadata($class);
            $currentDiscriminator = $currentMetadata->discriminatorValue;

            if ($currentDiscriminator !== null) {
                $discriminators[$currentDiscriminator] = null;
            }
        }

        return $discriminators;
    }