Resolve repository lookup.

@param LoadEntity $annotation
@param string     $entityClass
@param array      $mapping

@return object|null
505188
private function resolveRepositoryLookup(
        LoadEntity $annotation,
        string $entityClass,
        array $mapping
    ) {
        $annotationRepository = $annotation->getRepository();
        $annotationHasRepository = !is_null($annotationRepository) && is_array($annotationRepository);
        if ($annotationHasRepository) {
            $class = $annotation->getRepository()['class'];
            $repository = $this
                    ->container
                    ->has($class)
                ? $this
                    ->container
                    ->get($class)
                : new $class();
        } else {
            $repository = $this
                ->doctrine
                ->getManagerForClass($entityClass)
                ->getRepository($entityClass);
        }

        $method = $annotationHasRepository && isset($annotationRepository['method'])
            ? $annotationRepository['method']
            : 'findOneBy';

        return $repository->$method($mapping);
    }
733576
public static ResultMap getResultMap(Configuration configuration,Class<?> entityClass) {
        List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
        
        Set<ColumnMapper> entityClassColumns = EntityHelper.getEntityMapper(entityClass).getColumnsMapper();
        for (ColumnMapper entityColumn : entityClassColumns) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), entityColumn.getColumn(), entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }

            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            builder.lazy(false);
            resultMappings.add(builder.build());
        }
        ResultMap.Builder builder = new ResultMap.Builder(configuration, "BaseResultMap", entityClass, resultMappings, true);
        return builder.build();
    }
201322
public function getClassAnnotation($class)
    {
        $reflClass = new \ReflectionClass($class);
        $mappedDocumentClass = static::ANNOTATION_CLASS_CLASS;

        foreach ($this->annotationReader->getClassAnnotations($reflClass) as $annotation) {
            if ($annotation instanceof $mappedDocumentClass) {
                return $annotation;
            }
        }

        return null;
    }
1007416
private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) {
		MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup;

		Class<? extends MetaDataObject> metaClass = mapped ? MetaJsonObject.class : MetaJpaDataObject.class;
		MetaDataObject meta = metaLookup.getMeta(resourceClass, metaClass);

		for (MetaAttribute attr : meta.getAttributes()) {
			if (!attr.isAssociation()) {
				continue;
			}
			MetaType attrType = attr.getType().getElementType();

			if (attrType instanceof MetaEntity) {
				// normal entity association
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);

				// only include relations that are exposed as repositories
				if (attrConfig != null) {
					RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(attrImplClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
					context.addRepository(relationshipRepository);
				}
			} else if (attrType instanceof MetaResource) {
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);
				if (attrConfig == null || attrConfig.getMapper() == null) {
					throw new IllegalStateException("no mapped entity for " + attrType.getName() + " reference by " + attr.getId() + " registered");
				}
				JpaRepositoryConfig<?> targetConfig = getRepositoryConfig(attrImplClass);
				Class<?> targetResourceClass = targetConfig.getResourceClass();

				RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(targetResourceClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
				context.addRepository(relationshipRepository);
			} else {
				throw new IllegalStateException("unable to process relation: " + attr.getId() + ", neither a entity nor a mapped entity is referenced");
			}
		}
	}
862028
private function convertClassAnnotationsToEntityClassMetadata(
        array $classAnnotations,
        ReflectionClass $reflectionClass,
        Mapping\ClassMetadata $parent
    ) {
        /** @var Annotation\Entity $entityAnnot */
        $entityAnnot   = $classAnnotations[Annotation\Entity::class];
        $classMetadata = new Mapping\ClassMetadata($reflectionClass->getName(), $parent);

        if ($entityAnnot->repositoryClass !== null) {
            $classMetadata->setCustomRepositoryClassName($entityAnnot->repositoryClass);
        }

        if ($entityAnnot->readOnly) {
            $classMetadata->asReadOnly();
        }

        // Evaluate @Table annotation
        if (isset($classAnnotations[Annotation\Table::class])) {
            /** @var Annotation\Table $tableAnnot */
            $tableAnnot = $classAnnotations[Annotation\Table::class];
            $table      = $this->convertTableAnnotationToTableMetadata($tableAnnot);

            $classMetadata->setTable($table);
        }

        // Evaluate @ChangeTrackingPolicy annotation
        if (isset($classAnnotations[Annotation\ChangeTrackingPolicy::class])) {
            /** @var Annotation\ChangeTrackingPolicy $changeTrackingAnnot */
            $changeTrackingAnnot = $classAnnotations[Annotation\ChangeTrackingPolicy::class];

            $classMetadata->setChangeTrackingPolicy(
                constant(sprintf('%s::%s', Mapping\ChangeTrackingPolicy::class, $changeTrackingAnnot->value))
            );
        }

        // Evaluate @EntityListeners annotation
        if (isset($classAnnotations[Annotation\EntityListeners::class])) {
            /** @var Annotation\EntityListeners $entityListenersAnnot */
            $entityListenersAnnot = $classAnnotations[Annotation\EntityListeners::class];

            foreach ($entityListenersAnnot->value as $listenerClassName) {
                if (! class_exists($listenerClassName)) {
                    throw Mapping\MappingException::entityListenerClassNotFound(
                        $listenerClassName,
                        $reflectionClass->getName()
                    );
                }

                $listenerClass = new ReflectionClass($listenerClassName);

                /** @var ReflectionMethod $method */
                foreach ($listenerClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                    foreach ($this->getMethodCallbacks($method) as $callback) {
                        $classMetadata->addEntityListener($callback, $listenerClassName, $method->getName());
                    }
                }
            }
        }

        // Evaluate @HasLifecycleCallbacks annotation
        if (isset($classAnnotations[Annotation\HasLifecycleCallbacks::class])) {
            /** @var ReflectionMethod $method */
            foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                foreach ($this->getMethodCallbacks($method) as $callback) {
                    $classMetadata->addLifecycleCallback($method->getName(), $callback);
                }
            }
        }

        // Evaluate @InheritanceType annotation
        if (isset($classAnnotations[Annotation\InheritanceType::class])) {
            /** @var Annotation\InheritanceType $inheritanceTypeAnnot */
            $inheritanceTypeAnnot = $classAnnotations[Annotation\InheritanceType::class];

            $classMetadata->setInheritanceType(
                constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceTypeAnnot->value))
            );

            if ($classMetadata->inheritanceType !== Mapping\InheritanceType::NONE) {
                $discriminatorColumn = new Mapping\DiscriminatorColumnMetadata();

                // Evaluate @DiscriminatorColumn annotation
                if (isset($classAnnotations[Annotation\DiscriminatorColumn::class])) {
                    /** @var Annotation\DiscriminatorColumn $discriminatorColumnAnnot */
                    $discriminatorColumnAnnot = $classAnnotations[Annotation\DiscriminatorColumn::class];

                    $discriminatorColumn->setColumnName($discriminatorColumnAnnot->name);

                    if (! empty($discriminatorColumnAnnot->columnDefinition)) {
                        $discriminatorColumn->setColumnDefinition($discriminatorColumnAnnot->columnDefinition);
                    }

                    if (! empty($discriminatorColumnAnnot->type)) {
                        $discriminatorColumn->setType(Type::getType($discriminatorColumnAnnot->type));
                    }

                    if (! empty($discriminatorColumnAnnot->length)) {
                        $discriminatorColumn->setLength($discriminatorColumnAnnot->length);
                    }
                }

                if (empty($discriminatorColumn->getColumnName())) {
                    throw Mapping\MappingException::nameIsMandatoryForDiscriminatorColumns($reflectionClass->getName());
                }

                $classMetadata->setDiscriminatorColumn($discriminatorColumn);

                // Evaluate @DiscriminatorMap annotation
                if (isset($classAnnotations[Annotation\DiscriminatorMap::class])) {
                    /** @var Annotation\DiscriminatorMap $discriminatorMapAnnotation */
                    $discriminatorMapAnnotation = $classAnnotations[Annotation\DiscriminatorMap::class];
                    $discriminatorMap           = $discriminatorMapAnnotation->value;

                    $classMetadata->setDiscriminatorMap($discriminatorMap);
                }
            }
        }

        return $classMetadata;
    }
1004778
public function getRepository(Entity $entity)
    {
        $repo = $this->getRepositories()[get_class($entity)];

        return $this->$repo;
    }
1182493
private function setEntityRepository()
    {
        try {
            $this->_repository = $this->_em->getRepository(self::ENTITY_CLASSNAME);
        } catch (\Exception $e) {
            throw new CacheException('Enable to load the cache entity repository', null, $e);
        }

        return $this;
    }
987251
protected function resolveType(RelationshipAnnotation $annotation): int
    {
        if ($annotation->type === RelationshipAnnotation::TYPE_ONE) {
            return Relationship::TYPE_X_TO_ONE;
        }

        if ($annotation->type === RelationshipAnnotation::TYPE_MANY) {
            return Relationship::TYPE_X_TO_MANY;
        }

        throw new \LogicException(sprintf('Invalid type of relation "%s" defined.', $annotation->type));
    }
814947
public function getByEntityBuilder($entityClass, $entityId, array $properties = [])
    {
        $qb = $this->createDefaultBuilder()
            ->andWhere('o.objectClass = :entity_class')
            ->setParameter('entity_class', $entityClass)
            ->andWhere('o.objectId = :entity_id')
            ->setParameter('entity_id', $entityId);

        return !empty($properties) ? $qb->andWhere($qb->expr()->in('o.property', $properties)) : $qb;
    }
1336998
@Override
  public <T> T findOne(String jxQuery, Class<T> entityClass) {
    return findOne(jxQuery, Util.determineCollectionName(entityClass));
  }
446829
@Override
  protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    Class<?> clazz = findLoadedClass(name);
    if (clazz == null) {
      if (inExceptedPackage(name)) {
        clazz = super.loadClass(name, false);
      } else {
        try {
          clazz = findClass(name);          
        } catch (ClassNotFoundException e) {
          clazz = super.loadClass(name, false);
          if (!clazz.isAnnotation()) { // Annotations are always safe to load
            logger.log(Type.WARN, String.format(
                "Class %s is used in Gin, but not available in GWT client code.", name));
          }
        }
      }
    }

    if (resolve) {
      resolveClass(clazz);
    }

    return clazz;
  }
1208255
private function getClassMetadata($entityName, EntityManagerInterface $entityManager)
    {
        try {
            return $entityManager->getClassMetadata($entityName);
        } catch (MappingException $e) {
        }

        $matches = array_filter(
            $this->getMappedEntities($entityManager),
            static function ($mappedEntity) use ($entityName) {
                return preg_match('{' . preg_quote($entityName) . '}', $mappedEntity);
            }
        );

        if (! $matches) {
            throw new InvalidArgumentException(sprintf(
                'Could not find any mapped Entity classes matching "%s"',
                $entityName
            ));
        }

        if (count($matches) > 1) {
            throw new InvalidArgumentException(sprintf(
                'Entity name "%s" is ambiguous, possible matches: "%s"',
                $entityName,
                implode(', ', $matches)
            ));
        }

        return $entityManager->getClassMetadata(current($matches));
    }
790783
public function getRepositoryFor($entityClass)
    {
        if (!is_subclass_of($entityClass, EntityInterface::class)) {
            throw new InvalidArgumentException(
                'Cannot create ORM repository for a class that does not '.
                'implement EntityInterface.'
            );
        }

        return $this->repositories->containsKey($entityClass)
            ? $this->repositories->get($entityClass)
            : $this->createRepository($entityClass);
    }
645964
private static function getFirstAnnotationMatching(array $annotations, $annotationClass)
    {
        if (\is_string($annotationClass)) {
            $annotationClass = [$annotationClass];
        }

        foreach ($annotations as $annotation) {
            foreach ($annotationClass as $class) {
                if ($annotation instanceof $class) {
                    return $annotation;
                }
            }
        }

        return false;
    }
1207323
public function get(string $class, string $identity)
    {
        if (!$this->has($class, $identity)) {
            return null;
        }

        return $this->entities["{$class}:{$identity}"];
    }
176726
public function castToEntity($matches, $entityClass)
    {
        $entityRegistry = $this->repositoryFactory->getEntityRegistry();

        $result = [];

        $meta        = $this->getMeta($entityClass);
        $entityClass = $meta->class;
        $reflection  = new \ReflectionClass($entityClass);

        foreach ($matches as $match) {
            $entity = new $entityClass;

            foreach ($meta->fields as $key => $definition) {
                /** @var Element $definition */
                $varName = $definition->propertyName($key);
                $colName = $definition->columnName($key);

                $value = isset($definition->default) ? $definition->default : null;

                if (array_key_exists($colName, $match)) {
                    // @todo Apply validation according to definition
                    $value = $match[$colName];

                    if ($definition instanceof Field) {
                        switch ($definition->type) {
                            case 'int':
                            case 'integer':
                                $value = (integer)$value;
                                break;

                            case 'json':
                                $value = json_decode($value);
                                break;

                            default:
                                // Leave the value alone
                                break;
                        }
                    }
                }

                if ($reflection->hasProperty($varName)) {
                    $property = $reflection->getProperty($varName);
                    $property->setAccessible(true);
                    $property->setValue($entity, is_null($value) ? $entity->{$varName} : $value);
                } else {
                    /** @noinspection PhpVariableVariableInspection */
                    $entity->{$varName} = $value;
                }
            }

            $entityRegistry->stashEntity($entity);
            $this->resolveRelations($entity, $meta);
            $entityRegistry->registerEntity($entity);

            $result[] = $entity;

            unset($entity);
        }

        return $result;
    }
144993
private function resolveEntityManagerName(
        ContainerBuilder $container,
        string $entityManagerName
    ) {
        if (!$container->has('doctrine.orm.' . $entityManagerName . '_metadata_driver')) {
            throw new EntityManagerNotFoundException($entityManagerName);
        }
    }