Config the Entity Manager of Doctrine

@author Edson B S Monteiro <bruno.monteirodg@gmail.com>
@since 1.0
178268
private static function configEntityManager()
    {
        if (self::$entityManager) {
            return;
        }

        $isDevMode = cfg::htrFileConfigs()->devmode ?? false;
        $paths = [cfg::baseDir() . cfg::PATH_ENTITIES];

        // the connection configuration
        if ($isDevMode) {
            $dbParams = cfg::DATABASE_CONFIGS_DEV;
        } else {
            $dbParams = cfg::DATABASE_CONFIGS_PRD;
        }

        $cache = new ArrayCache();
        $reader = new AnnotationReader();
        $driver = new AnnotationDriver($reader, $paths);

        $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);
        $config->setMetadataDriverImpl($driver);

        self::$entityManager = EntityManager::create($dbParams, $config);
    }
1333284
public function setupEntities()
    {
        if ($this->registeredEntities->Count() > 0) {
            return;
        }

        if (Config::inst()->get('DocumentationManifest', 'automatic_registration')) {
            $this->populateEntitiesFromInstall();
        }

        $registered = Config::inst()->get('DocumentationManifest', 'register_entities');

        foreach ($registered as $details) {
            // validate the details provided through the YAML configuration
            $required = array('Path', 'Title');

            foreach ($required as $require) {
                if (!isset($details[$require])) {
                    throw new Exception("$require is a required key in DocumentationManifest.register_entities");
                }
            }

            // if path is not an absolute value then assume it is relative from
            // the BASE_PATH.
            $path = $this->getRealPath($details['Path']);

            $key = (isset($details['Key'])) ? $details['Key'] : $details['Title'];

            if (!$path || !is_dir($path)) {
                trigger_error($details['Path'] . ' is not a valid documentation directory', E_USER_WARNING);
                continue;
            }

            $version = (isset($details['Version'])) ? $details['Version'] : '';

            $versionTitle = isset($details['VersionTitle'])
                ? $details['VersionTitle']
                : $version;

            $archived = !empty($details['Archived']);

            $branch = (isset($details['Branch'])) ? $details['Branch'] : '';

            $langs = scandir($path);

            if ($langs) {
                $possible = i18n::get_common_languages(true);

                foreach ($langs as $k => $lang) {
                    if (isset($possible[$lang])) {
                        /**
                         * @var DocumentationEntity $entity
                         */
                        $entity = Injector::inst()->create(
                            'DocumentationEntity',
                            $key
                        );

                        $entity->setPath(DocumentationHelper::normalizePath(Controller::join_links($path, $lang, '/')));
                        $entity->setTitle($details['Title']);
                        $entity->setLanguage($lang);
                        $entity->setVersion($version);
                        $entity->setVersionTitle($versionTitle);
                        $entity->setBranch($branch);
                        $entity->setIsArchived($archived);

                        if (isset($details['Stable'])) {
                            $entity->setIsStable($details['Stable']);
                        }

                        if (isset($details['DefaultEntity'])) {
                            $entity->setIsDefaultEntity($details['DefaultEntity']);
                            if ($entity->getIsDefaultEntity()) {
                                $this->has_default_entity = true;
                            }
                        }

                        $this->registeredEntities->push($entity);
                    }
                }
            }
        }
    }
1051371
public function addDsmParamsToConfig(Configuration $doctrineConfig, ConfigInterface $config): void
    {
        $paths          = $this->getPathInformation($config);
        $namingStrategy = $config->get(ConfigInterface::PARAM_DOCTRINE_NAMING_STRATEGY);
        $driver         = new StaticPHPDriver($paths);
        $doctrineConfig->setMetadataDriverImpl($driver);
        $doctrineConfig->setNamingStrategy($namingStrategy);
    }
511505
public static function persist() {
		if(self::$entity_manager == null)
			self::initialize();

		return call_user_func_array(array(self::$entity_manager, "persist"), func_get_args());
	}
1023673
protected static function createDatabaseConfiguration()
    {
        $config          = new JConfig();
        $dsn             = $config->dbtype . '://' . $config->user . ':' . $config->password . '@' . $config->host . '/' . $config->db;
        $dataMapperClass = PrefixedDoctrineDataMapper::class;

        $ini = <<<INI
databaseUrl="$dsn"
definitionPath="entities"
dataMapper="$dataMapperClass"
INI;
        file_put_contents(JPATH_ROOT . '/config/database.ini', $ini);
    }
776091
public static function getEntityManager($db = null, $context = 'shared')
    {
        // Get db config info from file
        $dbConfig = \erdiko\core\Helper::getConfig("database", $context);
        if($db == null)
            $db = $dbConfig['default'];
        $dbParams = $dbConfig['connections'][$db];
        $dbParams['dbname'] = $dbParams['database'];
        $dbParams['user'] = $dbParams['username'];

        $paths = array(ERDIKO_ROOT.$dbConfig['entities']);
        $isDevMode = isset($dbConfig['is_dev_mode']) ? (bool)$dbConfig['is_dev_mode'] : false;
        $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
        
        // Create and return the entity manager
        return \Doctrine\ORM\EntityManager::create($dbParams, $config);
    }
247429
public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('stof_doctrine_extensions');
        if (\method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $treeBuilder->root('stof_doctrine_extensions');
        }

        $rootNode
            ->append($this->getVendorNode('orm'))
            ->append($this->getVendorNode('mongodb'))
            ->append($this->getClassNode())
            ->append($this->getUploadableNode())
            ->children()
                ->scalarNode('default_locale')
                    ->cannotBeEmpty()
                    ->defaultValue('en')
                ->end()
                ->booleanNode('translation_fallback')->defaultFalse()->end()
                ->booleanNode('persist_default_translation')->defaultFalse()->end()
                ->booleanNode('skip_translation_on_load')->defaultFalse()->end()
            ->end()
        ;

        return $treeBuilder;
    }
943290
protected function getEntityConf($entity)
    {
        $entityClass = get_class($entity);
        if($this->init === false){
            $this->boot();
        }
        if(preg_match('/'. \Doctrine\Common\Persistence\Proxy::MARKER .'/',$entityClass)){
            $entityClass = \Doctrine\Common\Util\ClassUtils::getRealClass($entityClass);
        }
        if(!isset($this->configsObjects[$entityClass])){
            $itemClassLoaded = [];
            foreach ($this->linkGeneratorItems as $linkGeneratorItem){
                $itemClassLoaded[] = get_class($linkGeneratorItem);
            }
            throw new Exception(sprintf('The config for entity "%s", not defined. Please define in LinkGeneratorItem already load (%s)',$entityClass,  implode(",",$itemClassLoaded)));
        }
        return $this->configsObjects[$entityClass];
    }
344462
public function getEntityManager()
    {
        if ($this->em === null) {
            $this->setEntityManager($this->container->get('doctrine')->getManager($this->emName));
        }

        return $this->em;
    }
564620
public function ensureMetaDataIsSet(EntityManagerInterface $entityManager): void
    {
        self::getDoctrineStaticMeta()->setMetaData($entityManager->getClassMetadata(self::class));
    }
707780
private function buildEntityClass()
    {
        foreach ($this->registries as $registry) {
            if ($registry->getKey() === 'identifier') {
                $this->entity->setObjectIdentifier($registry->getValue());
            } else {
                $this->entity->setObjectProperty($registry->getKey(), $registry->getValue());
            }
        }
    }
548838
protected function setUpEntityManagers()
    {
        $managers    = [];
        $connections = [];

        foreach ($this->config['managers'] as $manager => $settings) {
            $managerName    = IlluminateRegistry::getManagerNamePrefix() . $manager;
            $connectionName = IlluminateRegistry::getConnectionNamePrefix() . $manager;

            // Bind manager
            $this->app->singleton($managerName, function () use ($settings) {

                $manager = EntityManager::create(
                    ConnectionManager::resolve(array_get($settings, 'connection')),
                    MetaDataManager::resolve(array_get($settings, 'meta'))
                );

                $configuration = $manager->getConfiguration();

                // Listeners
                if (isset($settings['events']['listeners'])) {
                    foreach ($settings['events']['listeners'] as $event => $listener) {
                        $manager->getEventManager()->addEventListener($event, $listener);
                    }
                }

                // Subscribers
                if (isset($settings['events']['subscribers'])) {
                    foreach ($settings['events']['subscribers'] as $subscriber) {
                        $manager->getEventManager()->addEventSubscriber($subscriber);
                    }
                }

                // Filters
                if (isset($settings['filters'])) {
                    foreach ($settings['filters'] as $name => $filter) {
                        $configuration->getMetadataDriverImpl()->addFilter($name, $filter);
                        $manager->getFilters()->enable($name);
                    }
                }

                // Paths
                $configuration->getMetadataDriverImpl()->addPaths(
                    array_get($settings, 'paths', [])
                );

                // Repository
                $configuration->setDefaultRepositoryClassName(
                    array_get($settings, 'repository', \Doctrine\ORM\EntityRepository::class)
                );

                $configuration->setAutoGenerateProxyClasses(
                    array_get($settings, 'proxies.auto_generate', false)
                );

                if ($namespace = array_get($settings, 'proxies.namespace', false)) {
                    $configuration->setProxyNamespace($namespace);
                }

                return $manager;
            });

            // Bind connection
            $this->app->singleton($connectionName, function ($app) use ($manager) {
                $app->make(IlluminateRegistry::getManagerNamePrefix() . $manager)->getConnection();
            });

            $managers[$manager]    = $manager;
            $connections[$manager] = $manager;
        }

        return [$managers, $connections];
    }
218395
protected function wrapCommand($entityManagerName)
    {
        if (! $this->isVersionCompatible()) {
            throw new RuntimeException(sprintf('"%s" requires doctrine-orm "%s" or newer', $this->getName(), $this->getMinimalVersion()));
        }

        DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $entityManagerName);
        $this->command->setApplication($this->getApplication());

        return $this->command;
    }
699202
protected function registerEntityManager()
    {
        // Bind the default Entity Manager
        $this->app->singleton('em', function ($app) {
            return $app->make(ManagerRegistry::class)->getManager();
        });

        $this->app->alias('em', EntityManager::class);
        $this->app->alias('em', EntityManagerInterface::class);
    }
1173044
public function configure()
    {
        parent::configure();

        /** @var \Symfony\Component\HttpFoundation\Session\Session $session */
        $session = $this->get('session');

        switch (strtolower($this->container->getParameter('networking_init_cms.db_driver'))) {
            case 'monodb':
                $lastEditedSubscriber = new ODMLastEditedListener($session);
                break;
            case 'orm':
                $lastEditedSubscriber = new ORMLastEditedListener($session);
                break;
            default:
                $lastEditedSubscriber = false;
                break;
        }

        if ($lastEditedSubscriber) {
            $this->dispatcher->addSubscriber($lastEditedSubscriber);
        }
    }
436895
protected function createConfiguration()
    {

        // load the persistence unit configuration
        $persistenceUnitNode = $this->getPersistenceUnitNode();

        // load the metadata configuration
        $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration();

        // prepare the setup properties
        $absolutePaths = $metadataConfiguration->getDirectoriesAsArray();
        $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_DIR);
        $proxyNamespace = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_NAMESPACE);
        $autoGenerateProxyClasses = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_AUTO_GENERATE_PROXY_CLASSES);
        $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_USE_SIMPLE_ANNOTATION_READER);

        // load the metadata driver factory class name
        $metadataDriverFactory = $metadataConfiguration->getFactory();

        // initialize the params to be passed to the factory
        $metadataDriverParams = array(DriverKeys::USE_SIMPLE_ANNOTATION_READER => $useSimpleAnnotationReader);

        // create the Doctrine ORM configuration
        $configuration = new Configuration();
        $configuration->setMetadataDriverImpl($metadataDriverFactory::get($configuration, $absolutePaths, $metadataDriverParams));

        // initialize the metadata cache configuration
        $metadataCacheConfiguration = $persistenceUnitNode->getMetadataCacheConfiguration();
        $configuration->setMetadataCacheImpl($this->getCacheImpl($metadataCacheConfiguration));

        // initialize the query cache configuration
        $queryCacheConfiguration = $persistenceUnitNode->getQueryCacheConfiguration();
        $configuration->setQueryCacheImpl($this->getCacheImpl($queryCacheConfiguration));

        // initialize the result cache configuration
        $resultCacheConfiguration = $persistenceUnitNode->getResultCacheConfiguration();
        $configuration->setResultCacheImpl($this->getCacheImpl($resultCacheConfiguration));

        // proxy configuration
        $configuration->setProxyDir($proxyDir = $proxyDir ?: sys_get_temp_dir());
        $configuration->setProxyNamespace($proxyNamespace = $proxyNamespace ?: 'Doctrine\Proxy');
        $configuration->setAutoGenerateProxyClasses($autoGenerateProxyClasses = $autoGenerateProxyClasses ?: true);

        // repository configuration
        $configuration->setDefaultRepositoryClassName($persistenceUnitNode->getDefaultRepositoryClassName());
        $configuration->setRepositoryFactory($this->getApplication()->search($persistenceUnitNode->getRepositoryFactory()));

        // return the configuration instance
        return $configuration;
    }
642615
protected function buildManager()
    {
        $config = new Configuration;

        $this->setUpGeneralConfigurations($config);
        $this->setUpSpecificConfigurations($config);

        $documentManager = DocumentManager::create($this->getOption('connection'), $config, $this->getEventManager());

        if ($this->getRepositoryFactory() !== null) {
            $documentManager->setRepositoryFactory($this->getRepositoryFactory());
        }

        if ($this->getDefaultRepositoryClass() !== null) {
            $documentManager->setDefaultRepositoryClassName($this->getDefaultRepositoryClass());
        }

        return $documentManager;
    }