@param ManagerRegistry $registry
@param object          $entity
@param UniqueEntity    $constraint

@throws ConstraintDefinitionException

@return ObjectManager
541151
private static function findObjectManager(ManagerRegistry $registry, $entity, UniqueEntity $constraint)
    {
        if ($constraint->em) {
            $em = $registry->getManager($constraint->em);

            if (!$em) {
                throw new ConstraintDefinitionException(sprintf('Object manager "%s" does not exist.', $constraint->em));
            }
        } else {
            $em = ManagerUtils::getManager($registry, ClassUtils::getClass($entity));

            if (!$em) {
                throw new ConstraintDefinitionException(sprintf('Unable to find the object manager associated with an entity of class "%s".', \get_class($entity)));
            }
        }

        return $em;
    }
802766
protected function addRegistry(string $registryName)
    {
        $this->registries[] = $this->registryFactory->getRegistry($registryName, $this->getEntityName(), $this->entityManager);

        return $this;
    }
144993
private function resolveEntityManagerName(
        ContainerBuilder $container,
        string $entityManagerName
    ) {
        if (!$container->has('doctrine.orm.' . $entityManagerName . '_metadata_driver')) {
            throw new EntityManagerNotFoundException($entityManagerName);
        }
    }
570448
public <E extends Identifiable> E mergeEntity(EntityManager em, E entity) {
		requireArgument(em != null, "The entity manager cannot be null.");
		requireArgument(entity != null, "The entity cannot be null.");
		E ret = em.merge(entity);
		return ret;
	}
499804
public static function setApplicationDocumentManager(Application $application = null, $dmName)
    {
        if (is_null($application)) {
            throw new \InvalidArgumentException('Application instance needed!');
        }

        $helperSet = $application->getHelperSet();

        /** @var ManagerRegistry $doctrine */
        $doctrine = $helperSet->get('doctrine_mongodb');

        /** @var DocumentManager $dm */
        $dm = $doctrine->getManager($dmName);

        $helperSet->set(new DocumentManagerHelper($dm), 'dm');
    }
1061348
public static function objects(Registry $registry = null)
    {
        $manager = static::getManagerClass();
        $modelInstance = static::createObject(['registry' => $registry]);

        return new $manager($modelInstance);
    }
462378
protected function getEntityManager($entity)
    {
        if (!is_null($this->connection)) {
            return $this->registry->getManager($this->connection);
        }

        if (substr($entity, 0, 1) === '\\') {
            $entity = substr($entity, 1);
        }

        $em = $this->registry->getManagerForClass($entity);

        if ($em === null) {
            throw new InvalidArgumentException(sprintf("No Entity Manager could be found for [%s].", $entity));
        }

        return $em;
    }
1111800
private function createRepository(EntityManagerInterface $entityManager, $entityName)
    {
        /** @var ClassMetadata $metadata */
        $metadata            = $entityManager->getClassMetadata($entityName);
        $repositoryClassName = $metadata->getCustomRepositoryClassName()
            ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName();

        return new $repositoryClassName($entityManager, $metadata);
    }
815879
public static function run(I_Registry $registry, Manager $evtManager)
    {
        $instances = [];
        $methods = array_keys($registry->get('core/log', []));
        foreach ($methods as $method) {
            $levels = $registry->get(
                sprintf('core/log/%s', $method),
                []
            );
            foreach (array_keys($levels) as $level) {
                $methodRegistry = $registry->newFromKey(
                    sprintf('core/log/%s/%s', $method, $level)
                );
                $methodRegistry->set('name',  $method);
                $methodRegistry->set('level', $level);
                $methodRegistry->set('env',   $registry->get('core/env'));
                $class = $methodRegistry->get('class', null, false);
                if (is_null($class)) {
                    $class = sprintf(
                        "\\donbidon\\Core\\Log\\Method\\%s",
                        $method
                    );
                }
                $instance = new $class($methodRegistry, $evtManager);
                if (!($instance instanceof Method\A_Method)) {
                    throw new \RuntimeException(sprintf(
                        "Class '%s' has to be instance of %s",
                        $class,Method\A_Method::class
                    ));
                }
                $instances[] = $instance;
            }
        }

        return $instances;
    }
817333
protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container)
    {
        $ormConfigDef = $container->setDefinition(sprintf('doctrine.orm.%s_configuration', $entityManager['name']), new ChildDefinition('doctrine.orm.configuration'));

        $this->loadOrmEntityManagerMappingInformation($entityManager, $ormConfigDef, $container);
        $this->loadOrmCacheDrivers($entityManager, $container);

        if (isset($entityManager['entity_listener_resolver']) && $entityManager['entity_listener_resolver']) {
            $container->setAlias(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $entityManager['entity_listener_resolver']);
        } else {
            $definition = new Definition('%doctrine.orm.entity_listener_resolver.class%');
            $definition->addArgument(new Reference('service_container'));
            $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $definition);
        }

        $methods = [
            'setMetadataCacheImpl' => new Reference(sprintf('doctrine.orm.%s_metadata_cache', $entityManager['name'])),
            'setQueryCacheImpl' => new Reference(sprintf('doctrine.orm.%s_query_cache', $entityManager['name'])),
            'setResultCacheImpl' => new Reference(sprintf('doctrine.orm.%s_result_cache', $entityManager['name'])),
            'setMetadataDriverImpl' => new Reference('doctrine.orm.' . $entityManager['name'] . '_metadata_driver'),
            'setProxyDir' => '%doctrine.orm.proxy_dir%',
            'setProxyNamespace' => '%doctrine.orm.proxy_namespace%',
            'setAutoGenerateProxyClasses' => '%doctrine.orm.auto_generate_proxy_classes%',
            'setClassMetadataFactoryName' => $entityManager['class_metadata_factory_name'],
            'setDefaultRepositoryClassName' => $entityManager['default_repository_class'],
            'setNamingStrategy' => new Reference($entityManager['naming_strategy']),
            'setQuoteStrategy' => new Reference($entityManager['quote_strategy']),
            'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name'])),
        ];

        $listenerId        = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $entityManager['name']);
        $listenerDef       = $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%'));
        $listenerTagParams = ['event' => 'loadClassMetadata'];
        if (isset($entityManager['connection'])) {
            $listenerTagParams['connection'] = $entityManager['connection'];
        }
        $listenerDef->addTag('doctrine.event_listener', $listenerTagParams);

        if (isset($entityManager['second_level_cache'])) {
            $this->loadOrmSecondLevelCache($entityManager, $ormConfigDef, $container);
        }

        if ($entityManager['repository_factory']) {
            $methods['setRepositoryFactory'] = new Reference($entityManager['repository_factory']);
        }

        foreach ($methods as $method => $arg) {
            $ormConfigDef->addMethodCall($method, [$arg]);
        }

        foreach ($entityManager['hydrators'] as $name => $class) {
            $ormConfigDef->addMethodCall('addCustomHydrationMode', [$name, $class]);
        }

        if (! empty($entityManager['dql'])) {
            foreach ($entityManager['dql']['string_functions'] as $name => $function) {
                $ormConfigDef->addMethodCall('addCustomStringFunction', [$name, $function]);
            }
            foreach ($entityManager['dql']['numeric_functions'] as $name => $function) {
                $ormConfigDef->addMethodCall('addCustomNumericFunction', [$name, $function]);
            }
            foreach ($entityManager['dql']['datetime_functions'] as $name => $function) {
                $ormConfigDef->addMethodCall('addCustomDatetimeFunction', [$name, $function]);
            }
        }

        $enabledFilters    = [];
        $filtersParameters = [];
        foreach ($entityManager['filters'] as $name => $filter) {
            $ormConfigDef->addMethodCall('addFilter', [$name, $filter['class']]);
            if ($filter['enabled']) {
                $enabledFilters[] = $name;
            }
            if (! $filter['parameters']) {
                continue;
            }

            $filtersParameters[$name] = $filter['parameters'];
        }

        $managerConfiguratorName = sprintf('doctrine.orm.%s_manager_configurator', $entityManager['name']);
        $container
            ->setDefinition($managerConfiguratorName, new ChildDefinition('doctrine.orm.manager_configurator.abstract'))
            ->replaceArgument(0, $enabledFilters)
            ->replaceArgument(1, $filtersParameters);

        if (! isset($entityManager['connection'])) {
            $entityManager['connection'] = $this->defaultConnection;
        }

        $container
            ->setDefinition(sprintf('doctrine.orm.%s_entity_manager', $entityManager['name']), new ChildDefinition('doctrine.orm.entity_manager.abstract'))
            ->setPublic(true)
            ->setArguments([
                new Reference(sprintf('doctrine.dbal.%s_connection', $entityManager['connection'])),
                new Reference(sprintf('doctrine.orm.%s_configuration', $entityManager['name'])),
            ])
            ->setConfigurator([new Reference($managerConfiguratorName), 'configure']);

        $container->setAlias(
            sprintf('doctrine.orm.%s_entity_manager.event_manager', $entityManager['name']),
            new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $entityManager['connection']), false)
        );

        if (! isset($entityManager['entity_listeners'])) {
            return;
        }

        if (! isset($listenerDef)) {
            throw new InvalidArgumentException('Entity listeners configuration requires doctrine-orm 2.5.0 or newer');
        }

        $entities = $entityManager['entity_listeners']['entities'];

        foreach ($entities as $entityListenerClass => $entity) {
            foreach ($entity['listeners'] as $listenerClass => $listener) {
                foreach ($listener['events'] as $listenerEvent) {
                    $listenerEventName = $listenerEvent['type'];
                    $listenerMethod    = $listenerEvent['method'];

                    $listenerDef->addMethodCall('addEntityListener', [
                        $entityListenerClass,
                        $listenerClass,
                        $listenerEventName,
                        $listenerMethod,
                    ]);
                }
            }
        }
    }
294291
public function createSchemaUniqueConstraint($label, $property, $transformIndexInConstraint = false, $conn = null)
    {
        $q = 'CREATE CONSTRAINT ON (n:'.$label.') ASSERT n.'.$property.' IS UNIQUE';
        try {
            $this->sendCypherQuery($q);

            return new UniqueConstraint($label, $property);
        } catch (Neo4jException $e) {
            if (true === $transformIndexInConstraint && 8000 === $e->getCode()) {
                // do remove constraint
            }

            throw $e;
        }
    }
743165
public function getRegistry(string $registryName, $entityClass = null, EntityManager $entityManager = null)
    {
        if (!array_key_exists($registryName, self::$registries)) {
            throw new InvalidRegistryName($registryName);
        }

        $reflectionClass = new \ReflectionClass(self::$registries[$registryName]);

        /** @var RegistryInterface $instance */
        $instance = $reflectionClass->newInstance();

        $this->injectDependencies($instance, $entityClass, $entityManager);

        return $instance;
    }
1001399
private function getResult($entity, Constraint $constraint, array $criteria, ObjectManager $em)
    {
        /** @var UniqueEntity $constraint */
        $filters = SqlFilterUtil::findFilters($em, (array) $constraint->filters, $constraint->allFilters);

        SqlFilterUtil::disableFilters($em, $filters);
        $repository = $em->getRepository(ClassUtils::getClass($entity));
        $result = $repository->{$constraint->repositoryMethod}($criteria);
        SqlFilterUtil::enableFilters($em, $filters);

        if (\is_array($result)) {
            reset($result);
        }

        return $result;
    }
523869
public function registerManaged($entity, array $id, array $data)
    {
        $oid = spl_object_hash($entity);

        $this->entityIdentifiers[$oid]  = $id;
        $this->entityStates[$oid]       = self::STATE_MANAGED;
        $this->originalEntityData[$oid] = $data;

        $this->addToIdentityMap($entity);

        if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) {
            $entity->addPropertyChangedListener($this);
        }
    }
1232975
public function setEntityManager(EntityManager $em)
    {
        if ($this->em !== null) {
            throw new \LogicException('Entity manager can only be set before any results are fetched');
        }

        $this->em = $em;
    }
921207
public function generate(EntityManager $em, $entity)
    {
        $class      = $em->getClassMetadata(get_class($entity));
        $idFields   = $class->getIdentifierFieldNames();
        $identifier = array();

        foreach ($idFields as $idField) {
            $value = $class->getFieldValue($entity, $idField);

            if ( ! isset($value)) {
                throw ORMException::entityMissingAssignedIdForField($entity, $idField);
            }

            if (isset($class->associationMappings[$idField])) {
                // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
                $value = $em->getUnitOfWork()->getSingleIdentifierValue($value);
            }

            $identifier[$idField] = $value;
        }

        return $identifier;
    }
572674
protected function registerManagerRegistry()
    {
        $this->app->singleton('registry', function ($app) {
            $registry = new IlluminateRegistry($app, $app->make(EntityManagerFactory::class));

            // Add all managers into the registry
            foreach ($app->make('config')->get('doctrine.managers', []) as $manager => $settings) {
                $registry->addManager($manager, $settings);
            }

            return $registry;
        });

        // Once the registry get's resolved, we will call the resolve callbacks which were waiting for the registry
        $this->app->afterResolving('registry', function (ManagerRegistry $registry, Container $container) {
            $this->bootExtensionManager();

            BootChain::boot($registry);
        });

        $this->app->alias('registry', ManagerRegistry::class);
        $this->app->alias('registry', IlluminateRegistry::class);
    }