private function EntityGenerator($metadata) { $generator = new \Doctrine\ORM\Tools\EntityGenerator(); $generator->setUpdateEntityIfExists(true); $generator->setGenerateStubMethods(true); $generator->setGenerateAnnotations(true); $generator->generate($metadata, $this->entityFolder); }
/** * generate entity objects automatically from mysql db tables * @return none */ function generate_classes() { $this->em->getConfiguration()->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->em->getConnection()->getSchemaManager())); $platform = $this->em->getConnection()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('enum', 'string'); $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory(); $cmf->setEntityManager($this->em); $metadata = $cmf->getAllMetadata(); $generator = new \Doctrine\ORM\Tools\EntityGenerator(); $generator->setUpdateEntityIfExists(true); $generator->setGenerateStubMethods(true); $generator->setGenerateAnnotations(true); $generator->generate($metadata, APPPATH . "models/Entities"); }
private function generateUpdateEntity(&$em = null, $classes = array()) { $t = new \Doctrine\ORM\Tools\EntityGenerator($em); $t->setUpdateEntityIfExists(TRUE); $t->setGenerateAnnotations(TRUE); $t->setGenerateStubMethods(TRUE); $t->generate($classes, PATH_ROOT); }
include __DIR__ . '/vendor/autoload.php'; $classLoader = new \Doctrine\Common\ClassLoader('Entities', __DIR__); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Proxies', __DIR__); $classLoader->register(); // config $config = new \Doctrine\ORM\Configuration(); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(__DIR__ . '/app/src/Entity')); $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Proxies'); $connectionParams = array('driver' => 'pdo_mysql', 'host' => '127.0.0.1', 'port' => '3306', 'user' => 'root', 'password' => 'password', 'dbname' => 'project_directory', 'charset' => 'utf8mb4'); $em = \Doctrine\ORM\EntityManager::create($connectionParams, $config); // custom datatypes (not mapped for reverse engineering) $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string'); $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); // fetch metadata $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager()); $em->getConfiguration()->setMetadataDriverImpl($driver); $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($em); $cmf->setEntityManager($em); $classes = $driver->getAllClassNames(); $metadata = $cmf->getAllMetadata(); $generator = new Doctrine\ORM\Tools\EntityGenerator(); $generator->setUpdateEntityIfExists(true); $generator->setGenerateStubMethods(true); $generator->setGenerateAnnotations(true); $generator->generate($metadata, __DIR__ . '/app/src/Entity'); print '-------------------------------------------' . PHP_EOL; print ' Done! Generated models to `app\\src\\Entity`' . PHP_EOL; print '-------------------------------------------' . PHP_EOL;
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ require_once '../config.php'; //$tool = new \Doctrine\ORM\Tools\SchemaTool($em); //$classes = array( // $em->getClassMetadata('Entities\Pessoa'), // $em->getClassMetadata('Entities\Departamento') //); //$tool->updateSchema($classes); $em->getConfiguration()->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager())); $cmf = new Doctrine\ORM\Tools\DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); $metadata = $cmf->getAllMetadata(); $eg = new \Doctrine\ORM\Tools\EntityGenerator(); $eg->setGenerateStubMethods(true); $cme = new \Doctrine\ORM\Tools\Export\ClassMetadataExporter(); $exporter = $cme->getExporter('annotation', '../Entities'); $exporter->setMetadata($metadata); $exporter->setEntityGenerator($eg); $exporter->export();
/** * 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; }
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()); } }
function generateEntities($rootDir, $metadata) { $generator = new Doctrine\ORM\Tools\EntityGenerator(); $generator->setUpdateEntityIfExists(true); // only update if class already exists $generator->setRegenerateEntityIfExists(true); // this will overwrite the existing classes $generator->setGenerateStubMethods(true); //$generator->setGenerateAnnotations(true); $generator->generate($metadata, $rootDir); }
/** * Realiza a reversa do banco de dados * * @return [type] [description] */ public function reverseEntities() { $dsp = DIRECTORY_SEPARATOR; $bundleDir = $this->getDto()->query->get('bundleDir'); $bundleName = $this->getDto()->query->get('bundleName'); $bundleNameSpace = $this->getDto()->query->get('bundleNameSpace'); $schema = $this->getDto()->query->get('schema'); $tables = $this->getDto()->query->get('tables'); $path = explode('\\', $bundleDir); $path = implode($dsp, $path); $model_dir = str_replace($dsp . $dsp, $dsp, str_replace('\\', $dsp, str_replace('/', $dsp, $path . $dsp . 'Entity' . $dsp))); $repos_dir = str_replace($dsp . $dsp, $dsp, str_replace('\\', $dsp, str_replace('/', $dsp, $path . $dsp . 'Repository' . $dsp))); $nspEntity = $bundleNameSpace . '\\Entity'; $nspRepo = $bundleNameSpace . '\\Repository'; echo "Verificando a existencia dos diretorios de entidades e repositorios\n"; if (!file_exists($model_dir)) { echo "Criando diretorio de entidades\n"; mkdir($model_dir); } if (!file_exists($repos_dir)) { echo "Criando diretorio de repositorios\n"; mkdir($repos_dir); } echo "Configurando EntityManager para utilizacao correta com Oracle\n"; $this->driver->setNamespace($nspEntity . '\\'); if ($this->checkOracle()) { $this->scm->setSchema($schema); } $egn = new \Doctrine\ORM\Tools\EntityGenerator(); $egn->setGenerateAnnotations(true); $egn->setClassToExtend('\\SanSIS\\BizlayBundle\\Entity\\AbstractEntity'); $egn->setGenerateStubMethods(true); $egn->setUpdateEntityIfExists(true); $metadata = array(); if (!count($tables)) { echo "Obtendo \"Metadata\" para as tabelas do schema\n"; $metadata = $this->cmf->getAllMetadata(); } else { echo "Obtendo \"Metadata\" para as tabelas selecionadas do schema (" . implode(', ', $tables) . ")\n"; $class = array(); foreach ($tables as $key => $table) { $arr = explode('_', $table); foreach ($arr as $k => $v) { $arr[$k] = ucfirst(strtolower($v)); } $class[$key] = $nspEntity . '\\' . implode('', $arr); $metadata[$key] = $this->cmf->getMetadataFor($class[$key]); } } echo "Processando \"Metadata\" para cada tabela\n"; foreach ($metadata as $key => $entity) { echo "\nProcessando tabela {$metadata[$key]->table['name']}\n"; echo "Corrgindo nome da entidade {$entity->name}\n"; $currTable = $metadata[$key]->table['name']; $name = explode('\\', $entity->name); $pos = count($name) - 1; $class = explode('.', $name[$pos]); if (isset($class[1]) && $class[1]) { $name[$pos] = ucfirst($class[1]); } /** * @TODO AJUSTAR O NOME DA ENTIDADE! */ $name[$pos] = $this->filterTbPrefix($name[$pos]); $className = $name[$pos]; $entity->name = implode('\\', $name); $metadata[$key]->table = array('name' => $schema . '.' . $metadata[$key]->table['name']); echo "Nome corrigido da entidade: {$entity->name} \n"; /** * Corrige o nome das colunas retirando as duas primeiras letras referentes ao tipo e colocando uc_first para todas. */ foreach ($metadata[$key]->fieldMappings as $k => $v) { if (strpos(strtolower($v['columnName']), 'fl_') === 0) { $metadata[$key]->fieldMappings[$k]['fieldName'] = 'is' . substr($v['fieldName'], 2); } else { if (strpos($v['columnName'], '_') == 2) { $metadata[$key]->fieldMappings[$k]['fieldName'] = lcfirst(substr($v['fieldName'], 2)); } } } /** * Alterando o nome da PK da tabela para id no objeto. */ $id = $metadata[$key]->identifier[0]; $metadata[$key]->identifier[0] = 'id'; $metadata[$key]->fieldMappings[$id]['fieldName'] = 'id'; $bkp = $metadata[$key]->fieldMappings[$id]; if (!isset($bkp['columnName'])) { throw new \Exception('Não é possível criar o nome da Sequence. Verifique a modelagem da tabela ' . $schema . '.' . $currTable); } unset($metadata[$key]->fieldMappings[$id]); $metadata[$key]->fieldMappings['id'] = $bkp; /** * @TODO: colocar opção para sequence (se usa ou não um método externo para criar, etc) */ // $sequenceName = $this->generateSequenceName($schema, $currTable, $bkp['columnName']); // $metadata[$key]->idGenerator = new SequenceGenerator($sequenceName, 1); // $metadata[$key]->sequenceGeneratorDefinition['sequenceName'] = $sequenceName; // $metadata[$key]->idGenerator = new AssignedGenerator(); echo "Corrigindo o nome das entidades em relacionamentos\n"; foreach ($metadata[$key]->associationMappings as $assk => $ass) { if (strpos($ass['joinColumns'][0]['name'], '_') == 2) { $metadata[$key]->associationMappings[$assk]['fieldName'] = lcfirst(substr($ass['fieldName'], 2)); } $name = explode('\\', $metadata[$key]->associationMappings[$assk]['targetEntity']); $pos = count($name) - 1; $class = explode('.', $name[$pos]); if (isset($class[1]) && $class[1]) { $name[$pos] = $class[0] . ucfirst($class[1]); } $name[$pos] = $this->filterTbPrefix($name[$pos]); $metadata[$key]->associationMappings[$assk]['targetEntity'] = implode('\\', $name); $name = explode('\\', $metadata[$key]->associationMappings[$assk]['sourceEntity']); $pos = count($name) - 1; $class = explode('.', $name[$pos]); if (isset($class[1]) && $class[1]) { $name[$pos] = $class[0] . ucfirst($class[1]); } $name[$pos] = $this->filterTbPrefix($name[$pos]); $metadata[$key]->associationMappings[$assk]['sourceEntity'] = implode('\\', $name); } // echo "Corrigindo o nome dos atributos (remocao de nome do banco)\n"; echo "Gerando arquivo da entidade\n"; $egn->writeEntityClass($entity, str_replace(str_replace('\\', $dsp, $nspEntity), '', $model_dir)); //define o repository default da classe e ativa o lifecycles $entityCode = file_get_contents($model_dir . $className . ".php"); if (!strstr($entityCode, 'HasLifecycleCallbacks')) { $entityCode = str_replace("@ORM\\Entity", "@ORM\\Entity(repositoryClass=\"\\{$nspRepo}\\{$className}\")\n * @ORM\\HasLifecycleCallbacks()\n * @Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation(\"innerEntity\")", $entityCode); } /** * Adiciona o necessário para obter o json schema da entidade com o Knp\JsonSchemaBundle */ if (!strstr($entityCode, 'JsonSchemaBundle')) { echo "Adicionando JsonSchemaBundle para geração de json schemas das entidades\n"; $entityCode = str_replace("use Doctrine\\ORM\\Mapping as ORM;", "use Doctrine\\ORM\\Mapping as ORM;\nuse Knp\\JsonSchemaBundle\\Annotations as JSON;", $entityCode); $entityCode = str_replace("@Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation(\"innerEntity\")", "@Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation(\"innerEntity\")\n * @JSON\\Schema", $entityCode); } /** * Corrige a entidade gerada para sempre usar o método identity */ $seqStr = '* @ORM\\GeneratedValue(strategy="SEQUENCE")'; if (strstr($entityCode, $seqStr)) { echo "Corrigindo o a estratégia da sequence para IDENTITY\n"; $pos = strpos($entityCode, $seqStr); $begin = substr($entityCode, 0, $pos); $end = substr($entityCode, $pos + strlen($seqStr)); $pos = strpos($end, "*/"); $end = substr($end, $pos); $entityCode = $begin . "* @ORM\\GeneratedValue(strategy=\"IDENTITY\")\n " . $end; // die($begin); // $entityCode = str_replace( // "use Doctrine\\ORM\\Mapping as ORM;", // "use Doctrine\\ORM\\Mapping as ORM;\nuse Knp\\JsonSchemaBundle\\Annotations as JSON;", // $entityCode // ); // $entityCode = str_replace( // "@Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation(\"innerEntity\")", // "@Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation(\"innerEntity\")\n * @JSON\\Schema", // $entityCode // ); } echo "Definindo o repositorio padrao da Entidade e adicionando Lifecycle Callbacks\n"; $entityCode = str_replace('private', 'protected', $entityCode); file_put_contents($model_dir . $className . ".php", $entityCode); echo 'Criado arquivo ' . $model_dir . $className . ".php\n"; //cria o repository se já não existir echo "Criando o repositorio da Entidade, caso ja nao exista\n"; if (!file_exists($repos_dir . $className . '.php')) { $repo = $this->generateClassSkeleton($nspRepo, $className, '\\SanSIS\\BizlayBundle\\Repository\\AbstractRepository', null, array('\\Doctrine\\ORM\\Query')); file_put_contents($repos_dir . $className . '.php', $repo); echo 'Criado arquivo ' . $repos_dir . $className . ".php\n"; } } exec('php app' . $dsp . 'console doctrine:generate:entities ' . $bundleName); //Corrige a definição do isValid() foreach ($metadata as $key => $entity) { $name = explode('\\', $entity->name); $pos = count($name) - 1; $class = explode('.', $name[$pos]); if (isset($class[1]) && $class[1]) { $name[$pos] = ucfirst($class[1]); } $className = $name[$pos]; $entityCode = file_get_contents($model_dir . $className . ".php"); $entityCode = str_replace("isValid()\n {\n // Add your code here\n }", "isValid()\n {\n parent::isValid();\n }", $entityCode); file_put_contents($model_dir . $className . ".php", $entityCode); echo "isValid da entidade corrigido\n"; } }