Creates the Doctrine entity manager instance.

@param ConfigRepository $config

@return EntityManager
@throws Exception
@throws \Doctrine\ORM\ORMException
969268
protected function createEntityManager(ConfigRepository $config)
    {
        if (!isset($config['doctrine'])) {
            throw new Exception('Doctrine configuration not registered.');
        }

        if (!isset($config['database'])) {
            throw new Exception('Database configuration not registered.');
        }

        $doctrineConfig = $config['doctrine'];
        $databaseConfig = $config['database'];

        $connectionConfig = $this->createConnectionConfig($doctrineConfig, $databaseConfig);

        $type              = array_get($doctrineConfig, 'mapping', self::METADATA_ANNOTATIONS);
        $paths             = array_get($doctrineConfig, 'paths', [base_path('app/Entities')]);
        $debug             = $config['app.debug'];
        $proxyDir          = array_get($doctrineConfig, 'proxy.directory');
        $simpleAnnotations = array_get($doctrineConfig, 'simple_annotations', false);

        $metadataConfiguration = $this->createMetadataConfiguration($type, $paths, $debug, $proxyDir, null,
            $simpleAnnotations);

        $this->configureMetadataConfiguration($metadataConfiguration, $doctrineConfig);

        $eventManager = new EventManager;

        $this->configureEventManager($doctrineConfig, $eventManager);

        $entityManager = EntityManager::create($connectionConfig, $metadataConfiguration, $eventManager);

        $this->configureEntityManager($doctrineConfig, $entityManager);

        return $entityManager;
    }
466372
protected function createPdoResolverWithHosts( array $config )
	{
		return function () use ( $config ) {

			foreach( Arr::shuffle( $hosts = $this->parseHosts( $config ) ) as $key => $host )
			{
				$config['host'] = $host;
				try
				{
					return $this->createConnector( $config )->connect( $config );
				}
				catch( PDOException $e )
				{
					if( count( $hosts ) - 1 === $key )
					{
						App::Log($e);
					}
				}
			}

			if(!isset($e)) {
				$e = new PDOException("Empty connection");
			}

			throw $e;
		};
	}
118766
private function createRepository(DocumentManager $documentManager, $documentName)
    {
        /* @var $metadata \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */
        $metadata = $documentManager->getClassMetadata($documentName);
        $repositoryClassName = $metadata->customRepositoryClassName
            ?: $documentManager->getDefaultRepositoryClassName();

        return new $repositoryClassName($documentManager, $metadata);
    }
713569
protected function loadDoctrine(array $config, ContainerBuilder $container)
    {
        foreach ($config['doctrine'] as $name => $cache) {
            $pool = new Reference(sprintf('memcache.%s', $cache['pool']));
            foreach ($cache['entity_managers'] as $em) {
                $def = new Definition($container->getParameter('memcache.doctrine_cache.class'));
                if (method_exists($def, 'setShared')) { // Symfony 2.8+
                    $def->setShared(true);
                } else { // For Symfony <2.8 compatibility
                    $def->setScope(ContainerInterface::SCOPE_CONTAINER);
                }
                $def->addMethodCall('setMemcache', array($pool));
                if ($cache['prefix']) {
                    $def->addMethodCall('setPrefix', array($cache['prefix']));
                }
                $container->setDefinition(sprintf('doctrine.orm.%s_%s', $em, $name), $def);
            }
            foreach ($cache['document_managers'] as $dm) {
                $def = new Definition($container->getParameter('memcache.doctrine_cache.class'));
                if (method_exists($def, 'setShared')) { // Symfony 2.8+
                    $def->setShared(true);
                } else { // For Symfony <2.8 compatibility
                    $def->setScope(ContainerInterface::SCOPE_CONTAINER);
                }
                $def->addMethodCall('setMemcache', array($pool));
                if ($cache['prefix']) {
                    $def->addMethodCall('setPrefix', array($cache['prefix']));
                }
                $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_%s', $dm, $name), $def);
            }
        }
    }
1159810
protected function createConnectionConfig(array $doctrineConfig, array $databaseConfig)
    {
        $connectionName   = array_get($doctrineConfig, 'connection', $databaseConfig['default']);
        $connectionConfig = array_get($databaseConfig['connections'], $connectionName);

        if ($connectionConfig === null) {
            throw new Exception("Configuration for connection '$connectionName' not found.");
        }

        return $this->normalizeConnectionConfig($connectionConfig);
    }
1308751
private static function addCustomFunctions(Configuration $config, array $options = array())
    {
        if (null !== $strFcts = Collection::get($options, 'orm:entity_managers:default:dql:string_functions')) {
            foreach ($strFcts as $name => $class) {
                if (class_exists($class)) {
                    $config->addCustomStringFunction($name, $class);
                }
            }
        }

        if (null !== $numFcts = Collection::get($options, 'orm:entity_managers:default:dql:numeric_functions')) {
            foreach ($numFcts as $name => $class) {
                if (class_exists($class)) {
                    $config->addCustomNumericFunction($name, $class);
                }
            }
        }

        if (null !== $datetimeFcts = Collection::get($options, 'orm:entity_managers:default:dql:datetime_functions')) {
            foreach ($datetimeFcts as $name => $class) {
                if (class_exists($class)) {
                    $config->addCustomDatetimeFunction($name, $class);
                }
            }
        }

        return $config;
    }
267863
public function setEntityManager(EntityManager $entityManager)
	{
		$this->entityManager = $entityManager;
		$this->connection = $entityManager->getConnection();
		$bar = Debugger::getBar();
		$bar->addPanel($this);

		$config = $this->connection->getConfiguration();
		$logger = $config->getSQLLogger();

		if ($logger instanceof Doctrine\DBAL\Logging\LoggerChain) {
			$logger->addLogger($this);
		} else {
			$config->setSQLLogger($this);
		}
	}
63790
protected function createRepository(DocumentManagerInterface $dm, $documentName)
    {
        $metadata = $dm->getClassMetadata($documentName);
        $repositoryClassName = $metadata->customRepositoryClassName;

        if ($repositoryClassName === null) {
            $configuration = $dm->getConfiguration();
            $repositoryClassName = $configuration->getDefaultRepositoryClassName();
        }

        return new $repositoryClassName($dm, $metadata);
    }
207086
protected function registerBindings(Container $container, ConfigRepository $config)
    {
        $container->singleton('Doctrine\ORM\EntityManager', function () use ($config) {
            return $this->createEntityManager($config);
        });

        $container->alias('Doctrine\ORM\EntityManager', 'Doctrine\ORM\EntityManagerInterface');
    }
311523
protected function createTokenRepository(array $config)
    {
        return new DatabaseTokenRepository(
            $this->app['db']->connection(),
            $config['table'],
            $this->app['config']['app.key'],
            $config['expire']
        );
    }
157147
protected static function getRepositoryByConfig($config, $name)
    {
        if (!is_array($config)) {
            if (class_exists($config)) {
                return new $config;
            }

            throw new Exception('Cannot create repository from string');
        } elseif ($config['driver'] == 'faker') {
            return new Faker(Factory::create());
        } elseif ($config['driver'] == 'middleware') {
            return resolve($config['middleware'])->execute(function() {
            }
            );
        }

        return static::initPdoDatabase($config, $name);
    }
1207877
public function createFromEntityManager(EntityManagerInterface $entityManager): \mysqli
    {
        $params = $entityManager->getConnection()->getParams();

        $conn = new \mysqli($params['host'], $params['user'], $params['password'], $params['dbname']);
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

        return $conn;
    }
492132
public static function create($config)
    {

        $clientBuilder = ClientBuilder::create();

        if (!empty($config['handler'])) {
            $clientBuilder->setHandler($config['handler']);
        }

        $clientBuilder->setHosts($config["servers"]);

        $clientBuilder = self::configureLogging($clientBuilder,$config);

        $query = new Query($clientBuilder->build());

        if (array_key_exists("index", $config) and $config["index"] != "") {
            $query->index($config["index"]);
        }

        return $query;
    }
851323
protected function createEmptyObjectStructure($config)
  {
    try
    {
      $configurator = new EnmConfigurator($this->converter->convertTo($config, 'array'), $this->dispatcher);

      return $this->createPartOfStructure($configurator->getConfig());
    }
    catch (\Exception $e)
    {
      $this->dispatcher->dispatch(TransformerEvents::ON_EXCEPTION, new ExceptionEvent($e));
      throw new TransformerException($e->getMessage());
    }
  }
64311
protected function registerRepositories(Repository $config)
    {
        $this->app->afterResolving('registry', function (ManagerRegistry $registry, Container $container) use ($config) {
            foreach ($config->get('doctrine_repositories.repositories', []) as $details) {
                if (!isset($details['repository']) && !isset($details['entity'])) {
                    throw new \InvalidArgumentException(
                        sprintf('Failed to process repository data: missing repository/entity from definition')
                    );
                }

                $this->app->singleton($details['repository'], function ($app) use ($details, $registry) {
                    $class = $details['repository'];
                    $em    = isset($details['em']) ? $registry->getManager($details['em']) : $registry->getManager();

                    return new $class($em, $em->getClassMetaData($details['entity']));
                });

                if (isset($details['alias'])) {
                    $this->app->alias($details['repository'], $details['alias']);
                }
                if (isset($details['tags'])) {
                    $this->app->tag($details['repository'], $details['tags']);
                }
            }
        });
    }
322809
public static function getInstance(DriverConfig $config)
    {
        $pdoDriver = PdoDriverFactory::getInstance();

        return new PostgreSQLMetaDataDAO(
            $pdoDriver->getConnection($config),
            $config,
            new SqlManager()
        );
    }
887878
private function createModelManagerService($adminName, Definition $ormModelManager, Definition $proxyRepository)
    {
        $serviceName = sprintf('sonata.%s.model_manager', $adminName);
        $service = new Definition($serviceName);
        $service->setClass('Marmelab\SonataElasticaBundle\Model\ElasticaModelManager');
        $service->setArguments(array(
            $ormModelManager,
            $proxyRepository
        ));

        return $service;
    }