Example #1
0
 public function generate_entities()
 {
     // custom datatypes (not mapped for reverse engineering)
     $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
     $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
     $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('blob', 'string');
     // fetch metadata
     $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->em->getConnection()->getSchemaManager());
     $driver->setNamespace('models\\Entities\\');
     //set driver implementation
     $this->em->getConfiguration()->setMetadataDriverImpl($driver);
     $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($this->em);
     $cmf->setEntityManager($this->em);
     $classes = $driver->getAllClassNames();
     //get class metadata
     $metadata = $cmf->getAllMetadata();
     $generator = new \Doctrine\ORM\Tools\EntityGenerator();
     $generator->setGenerateAnnotations(TRUE);
     $generator->setGenerateStubMethods(TRUE);
     $generator->setRegenerateEntityIfExists(TRUE);
     $generator->setUpdateEntityIfExists(TRUE);
     $generator->setBackupExisting(FALSE);
     try {
         $generator->generate($metadata, APPPATH . 'models/Entities');
         print 'Done!';
     } catch (exception $ex) {
         die($ex->getMessage());
     }
 }
 /**
  *
  * @param  string $className
  * @return ClassMetadata
  */
 protected function extractClassMetadata($className)
 {
     $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->_sm);
     foreach ($driver->getAllClassNames() as $dbClassName) {
         $class = new ClassMetadataInfo($dbClassName);
         $driver->loadMetadataForClass($dbClassName, $class);
         if (strtolower($class->name) == strtolower($className)) {
             return $class;
         }
     }
     $this->fail("No class matching the name '" . $className . "' was found!");
 }
 /**
  * @param  string $className
  * @return ClassMetadata
  */
 protected function extractClassMetadata(array $classNames)
 {
     $classNames = array_map('strtolower', $classNames);
     $metadatas = array();
     $sm = $this->_em->getConnection()->getSchemaManager();
     $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($sm);
     foreach ($driver->getAllClassNames() as $className) {
         if (!in_array(strtolower($className), $classNames)) {
             continue;
         }
         $class = new ClassMetadataInfo($className);
         $driver->loadMetadataForClass($className, $class);
         $metadatas[$className] = $class;
     }
     if (count($metadatas) != count($classNames)) {
         $this->fail("Have not found all classes matching the names '" . implode(", ", $classNames) . "' only tables " . implode(", ", array_keys($metadatas)));
     }
     return $metadatas;
 }
Example #4
0
 /**
  * Tenta estabelecer a conexão ao banco relacional ou de documentos.
  * 
  * @return \Doctrine\ORM\EntityManager | \Doctrine\ODM\MongoDB\DocumentManager
  */
 private function estabelecerConexao()
 {
     $tipo = explode(':', $this->_configuracao->get($this->_servidor . '.persistencia_uri'));
     $tipo = $tipo[0];
     if (!empty($tipo)) {
         if ($tipo === 'mongodb') {
             \Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver::registerAnnotationClasses();
         }
         $classLoader = new ClassLoader('Domain\\Entity', implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models']));
         $classLoader->register();
         $doctrine_models_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models']);
         $doctrine_entities_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models', 'Domain', 'Entity']);
         $doctrine_proxies_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'tmp', 'models', 'Domain', 'Entity', 'Proxies']);
         $doctrine_hydrators_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'tmp', 'models', 'Domain', 'Entity', 'Hydrators']);
         // cria os diretórios dos proxys e hydrators, caso não haja (necessários
         // para o Doctrine)
         if (!PROJECT_STAGE) {
             Arquivo::criarDiretorio($doctrine_proxies_dir);
             Arquivo::criarDiretorio($doctrine_hydrators_dir);
         }
         // verifica se não é MongoDB
         if ($tipo !== 'mongodb') {
             // provê algumas informações iniciais do banco de dados
             switch ($tipo) {
                 case 'sqlite':
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'path' => $this->_configuracao->get($this->_servidor . '.persistencia_banco')];
                     break;
                 case 'mysql':
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'user' => $this->_configuracao->get($this->_servidor . '.persistencia_usuario'), 'password' => $this->_configuracao->get($this->_servidor . '.persistencia_senha'), 'host' => $this->_configuracao->get($this->_servidor . '.persistencia_servidor'), 'dbname' => $this->_configuracao->get($this->_servidor . '.persistencia_banco'), \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET CHARACTER SET \'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_connection=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_client=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_results=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\';'];
                     break;
                     // em teste funciona para quase todos os tipos de PDO
                 // em teste funciona para quase todos os tipos de PDO
                 default:
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'user' => $this->_configuracao->get($this->_servidor . '.persistencia_usuario'), 'password' => $this->_configuracao->get($this->_servidor . '.persistencia_senha'), 'host' => $this->_configuracao->get($this->_servidor . '.persistencia_servidor'), 'dbname' => $this->_configuracao->get($this->_servidor . '.persistencia_banco')];
                     break;
             }
             // cria os mapeamentos das entidades do banco de dados, caso não existam
             if (count(glob($doctrine_entities_dir . '/*.php')) === 0) {
                 $configuracao = new \Doctrine\ORM\Configuration();
                 $configuracao->setMetadataDriverImpl($configuracao->newDefaultAnnotationDriver($doctrine_entities_dir, FALSE));
                 $configuracao->setProxyDir($doctrine_proxies_dir);
                 $configuracao->setProxyNamespace('Proxies');
                 $entityManager = \Doctrine\ORM\EntityManager::create($parametrosConexao, $configuracao);
                 // custom datatypes (not mapped for reverse engineering)
                 $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
                 $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
                 // define namespace
                 $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($entityManager->getConnection()->getSchemaManager());
                 $driver->setNamespace('Domain\\Entity\\');
                 // define driver with namespace
                 $entityManager->getConfiguration()->setMetadataDriverImpl($driver);
                 $disconnectedClassMetadataFactory = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
                 $disconnectedClassMetadataFactory->setEntityManager($entityManager);
                 $entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator();
                 $entityGenerator->setUpdateEntityIfExists(true);
                 $entityGenerator->setGenerateStubMethods(true);
                 $entityGenerator->setGenerateAnnotations(true);
                 $entityGenerator->generate($disconnectedClassMetadataFactory->getAllMetadata(), $doctrine_models_dir);
             }
             // carrega as entidades
             \Pudim\Arquivo::requererDiretorio($doctrine_entities_dir);
             $configuracao = \Doctrine\ORM\Tools\Setup::createConfiguration(!(bool) PROJECT_STAGE);
             $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(new \Doctrine\Common\Annotations\AnnotationReader(), $doctrine_entities_dir);
             // registering noop annotation autoloader - allow all annotations by default
             \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists');
             $configuracao->setMetadataDriverImpl($driver);
             $configuracao->setAutoGenerateProxyClasses(!(bool) PROJECT_STAGE);
             $configuracao->setProxyDir($doctrine_proxies_dir);
             $configuracao->setProxyNamespace('Proxies');
             if (PROJECT_STAGE) {
                 $cache = new \Doctrine\Common\Cache\ArrayCache();
             } else {
                 $cache = new \Doctrine\Common\Cache\ApcCache();
             }
             $configuracao->setMetadataCacheImpl($cache);
             $configuracao->setQueryCacheImpl($cache);
             // obtaining the entity manager (7)
             $eventManager = new \Doctrine\Common\EventManager();
             $conexao = \Doctrine\ORM\EntityManager::create($parametrosConexao, $configuracao, $eventManager);
         } else {
             $configuracao = new \Doctrine\ODM\MongoDB\Configuration();
             $metadata = AnnotationDriver::create($doctrine_entities_dir);
             $configuracao->setMetadataDriverImpl($metadata);
             $configuracao->setAutoGenerateProxyClasses(!(bool) PROJECT_STAGE);
             $configuracao->setProxyDir($doctrine_proxies_dir);
             $configuracao->setProxyNamespace('Proxies');
             $configuracao->setAutoGenerateHydratorClasses(!(bool) PROJECT_STAGE);
             $configuracao->setHydratorDir($doctrine_hydrators_dir);
             $configuracao->setHydratorNamespace('Hydrators');
             $configuracao->setDefaultDB($this->_configuracao->get($this->_servidor . '.persistencia_banco'));
             //$configuracao->setLoggerCallable(function (array $log) { print_r($log); });
             $cache_uri = $this->_configuracao->get($this->_servidor . '.cache_uri');
             if (PROJECT_STAGE && class_exists('Redis') && $cache_uri) {
                 // trata o $cache_uri pois somente precisamos do servidor e a porta
                 if (strpos($cache_uri, '//')) {
                     $cache_uri_parts = explode('//', $cache_uri);
                     if (strpos($cache_uri_parts[1], ':')) {
                         list($cache_server, $cache_port) = explode(':', $cache_uri_parts[1]);
                     } else {
                         $cache_server = $cache_uri_parts[1];
                         $cache_port = '6379';
                     }
                     unset($cache_uri_parts);
                 } else {
                     $cache_server = $cache_uri;
                     $cache_port = '6379';
                 }
                 $redis = new \Redis();
                 $redis->pconnect($cache_server, $cache_port);
                 $metadataCache = new \Doctrine\Common\Cache\RedisCache();
                 $metadataCache->setRedis($redis);
                 $configuracao->setMetadataCacheImpl($metadataCache);
                 unset($cache_server, $cache_port, $redis, $metadataCache);
             }
             $conexao = new \Doctrine\MongoDB\Connection($this->_configuracao->get($this->_servidor . '.persistencia_uri'));
             $conexao = \Doctrine\ODM\MongoDB\DocumentManager::create($conexao, $configuracao);
             // FIX: Muito importante pois força a criação dos índices no aplicativo
             $conexao->getSchemaManager()->ensureIndexes();
         }
     }
     return $conexao;
 }