예제 #1
0
 /**
  * Cria uma nova referencia de conexao com o banco
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param string $connectionName Nome da conexao
  * @param Lumine_Configuration $config Objeto de configuracao
  * @return void
  */
 public function create($connectionName, Lumine_Configuration $config)
 {
     if ($this->getConnection($connectionName) != false) {
         Lumine_Log::warning('Ja existe uma conexao com este nome: ' . $connectionName);
     } else {
         Lumine_Log::debug('Armazenando conexao: ' . $connectionName);
         $connObj = $this->getConnectionClass($config->options['dialect']);
         if ($connObj == false) {
             Lumine_Log::error('Dialeto nao implementado: ' . $config->options['dialect']);
             return;
         }
         $connObj->setDatabase($config->options['database']);
         $connObj->setHost($config->options['host']);
         $connObj->setPort($config->options['port']);
         $connObj->setUser($config->options['user']);
         $connObj->setPassword($config->options['password']);
         if (isset($config->options['options'])) {
             $connObj->setOptions($config->options['options']);
         }
         if ($config->getOption('charset') != '') {
             $connObj->setCharset($config->getOption('charset'));
         }
         $config->setConnection($connObj);
         $this->connections[$connectionName] = $config;
     }
 }
예제 #2
0
 public function getGeneratedFile()
 {
     $ds = DIRECTORY_SEPARATOR;
     $modelo = LUMINE_INCLUDE_PATH . "{$ds}lib{$ds}Templates{$ds}validator.xml";
     $props = array();
     $options = array();
     foreach ($this->conf as $key => $val) {
         if ($key == 'options') {
             foreach ($val as $k => $v) {
                 $options[] = $this->ident . $this->ident . "'{$k}' => '{$v}'";
             }
             continue;
         }
         $props[] = $this->ident . "'{$key}' => '{$val}'";
     }
     $str_props = implode(', ' . PHP_EOL, $props) . ', ' . PHP_EOL;
     $str_options = implode(', ' . PHP_EOL, $options);
     if (!file_exists($modelo)) {
         Lumine_Log::error('O arquivo ' . $modelo . ' não existe');
         exit;
     }
     $file = file_get_contents($modelo);
     $file = str_replace('{properties}', $str_props, $file);
     $file = str_replace('{options}', $str_options, $file);
     $file = preg_replace('@\\{(\\w+)\\}@e', '$this->$1', $file);
     return $file;
 }
예제 #3
0
 /**
  * @see Lumine_Connection_IConnection::connect()
  */
 public function connect()
 {
     if ($this->conn && $this->state == self::OPEN) {
         Lumine_Log::debug('Utilizando conexao cacheada com ' . $this->getDatabase());
         $this->conn->select_db($this->getDatabase());
         return true;
     }
     $this->dispatchEvent(new Lumine_Events_ConnectionEvent(Lumine_Event::PRE_CONNECT, $this));
     $hostString = $this->getHost();
     if ($this->getPort() != '') {
         $hostString .= ':' . $this->getPort();
     }
     if (isset($this->options['socket']) && $this->options['socket'] != '') {
         $hostString .= ':' . $this->options['socket'];
     }
     $flags = isset($this->options['flags']) ? $this->options['flags'] : null;
     if (isset($this->options['persistent']) && $this->options['persistent'] == true) {
         $hostString = 'p:' . $hostString;
     }
     Lumine_Log::debug('Criando conexao com ' . $this->getDatabase());
     $this->conn = new mysqli($this->getHost(), $this->getUser(), $this->getPassword(), $this->getDatabase());
     if ($this->conn->connect_error) {
         $this->state = self::CLOSED;
         $msg = 'nao foi possivel conectar no banco de dados: ' . $this->getDatabase() . ' - ' . $this->conn->connect_error;
         Lumine_Log::error($msg);
         $this->dispatchEvent(new Lumine_Events_ConnectionEvent(Lumine_Event::CONNECTION_ERROR, $this, $msg));
         throw new Exception($msg);
         return false;
     }
     // seleciona o banco
     $this->state = self::OPEN;
     $this->setCharset($this->getCharset());
     $this->dispatchEvent(new Lumine_Events_ConnectionEvent(Lumine_Event::POS_CONNECT, $this));
     return true;
 }
예제 #4
0
 /**
  * @see ILumine_Connection::connect()
  */
 public function connect()
 {
     if ($this->conn_id && $this->state == self::OPEN) {
         Lumine_Log::debug('Utilizando conexao cacheada com ' . $this->getDatabase());
         return true;
     }
     $this->dispatchEvent(new Lumine_ConnectionEvent(Lumine_Event::PRE_CONNECT, $this));
     $hostString = $this->getHost();
     if ($this->getPort() != '') {
         // nao colocamos a porta uma vez que a string de conexao
         // nao suporta a informacao da porta
         //$hostString .=  ':' . $this->getPort();
     }
     $hostString = empty($hostString) ? $this->getDatabase() : $hostString . ':' . $this->getDatabase();
     if (isset($this->options['socket']) && $this->options['socket'] != '') {
         $hostString .= ':' . $this->options['socket'];
     }
     $flags = isset($this->options['flags']) ? $this->options['flags'] : null;
     if (isset($this->options['persistent']) && $this->options['persistent'] == true) {
         Lumine_Log::debug('Criando conexao persistente com ' . $this->getDatabase());
         $this->conn_id = @ibase_pconnect($hostString, $this->getUser(), $this->getPassword());
     } else {
         Lumine_Log::debug('Criando conexao com ' . $this->getDatabase());
         $this->conn_id = @ibase_connect($hostString, $this->getUser(), $this->getPassword());
     }
     if (!$this->conn_id) {
         $this->state = self::CLOSED;
         $msg = 'Nao foi possivel conectar no banco de dados: ' . $this->getDatabase() . ' - ' . $this->getErrorMsg();
         Lumine_Log::error($msg);
         $this->dispatchEvent(new Lumine_ConnectionEvent(Lumine_Event::CONNECTION_ERROR, $this, $msg));
         throw new Exception($msg);
         return false;
     }
     if (function_exists('ibase_timefmt')) {
         ibase_timefmt($this->ibase_datefmt, IBASE_DATE);
         if ($this->dialect == 1) {
             ibase_timefmt($this->ibase_datefmt, IBASE_TIMESTAMP);
         } else {
             ibase_timefmt($this->ibase_timestampfmt, IBASE_TIMESTAMP);
         }
         ibase_timefmt($this->ibase_timefmt, IBASE_TIME);
     } else {
         ini_set("ibase.timestampformat", $this->ibase_timestampfmt);
         ini_set("ibase.dateformat", $this->ibase_datefmt);
         ini_set("ibase.timeformat", $this->ibase_timefmt);
     }
     $this->state = self::OPEN;
     $this->dispatchEvent(new Lumine_ConnectionEvent(Lumine_Event::POS_CONNECT, $this));
     $this->setCharset($this->getCharset());
     return true;
 }
예제 #5
0
 /**
  * Une uma classe com outra para efetuar uma consulta (inner|left|right) join
  *
  * <code>
  * $car = new Carro;
  * $pes = new Pessoa;
  * $car->join($car);
  * // SELECT pessoa.nome, pessoa.idpessoa, carro.modelo FROM pessoa inner join carro on(carro.idpessoa=pessoa.idpessoa)
  * </code>
  * @param Lumine_Base $obj Objeto para uniao
  * @param string $type Tipo de uniao (LEFT|INNER|RIGHT)
  * @param string $alias Alias para a tabela de uniao
  * @param string $linkName Nome especifico do link desta entidade
  * @param string $linkTo Nome da propriedade que se deseja linkar na outra entidade
  * @param string $extraCondition Condicao extra para adicionar a clausula ON da uniao
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/lumine
  * @return Lumine_Base O proprio objeto
  */
 public function join(Lumine_Base $obj, $type = 'INNER', $alias = '', $linkName = null, $linkTo = null, $extraCondition = null)
 {
     if (!preg_match('@^(INNER|LEFT|CROSS|RIGHT)$@i', $type)) {
         Lumine_Log::error('Tipo de uniao nao permitida: ' . $type);
         return $this;
     }
     $type = strtoupper($type);
     // verifica as chaves daqui pra la
     $name = $obj->metadata()->getClassname();
     if (is_null($linkName)) {
         Lumine_Log::debug('Nome do link nao especificado. Tentando recuperar automaticamente de ' . $name);
         $opt = $this->metadata()->getRelation($name);
     } else {
         Lumine_Log::debug('Nome de link especificado: ' . $linkName);
         $opt = $this->metadata()->getField($linkName);
     }
     if (!empty($alias)) {
         Lumine_Log::debug('Alterando o alias de ' . $name . ' para ' . $alias);
         $obj->alias($alias);
     }
     $dest = null;
     // link de destino
     if (!empty($linkTo)) {
         // se foi especificado um link de destino
         Lumine_Log::debug('Link de destino especificado: ' . $linkTo);
         $dest = $obj->metadata()->getField($linkTo);
         // pega o link de destino
     }
     if (!is_null($extraCondition)) {
         // se a pessoa definiu uma condicao extra
         $args = func_get_args();
         if (count($args) > 6) {
             $args = array_slice($args, 6);
         } else {
             $args = null;
         }
         $extraCondition = trim($extraCondition);
         // remove espacos em branco
         try {
             $extraCondition = Lumine_Parser::parsePart($obj, $extraCondition, $args);
             // faz o parser para certificacao que os campos existem certinho
             $extraCondition = Lumine_Parser::parseEntityNames($obj, $extraCondition);
         } catch (Exception $e) {
             try {
                 $extraCondition = Lumine_Parser::parsePart($this, $extraCondition, $args);
                 // faz o parser para certificacao que os campos existem certinho
                 $extraCondition = Lumine_Parser::parseEntityNames($this, $extraCondition);
             } catch (Exception $e) {
                 Lumine_Log::warning('Houve um erro na analise da condicao extra');
             }
         }
         if (!preg_match('@^(ON|AND|OR)@i', $extraCondition)) {
             // se nao definiu o tipo de logica inicial
             $extraCondition = " AND " . $extraCondition;
             // o padrao e AND
         } else {
             $extraCondition = " " . $extraCondition;
         }
         $extraCondition .= " ";
         // adiciona um espaco em branco para ficar certinho
     }
     $schema = '';
     // schema das tabelas
     $cfg = $this->_getConfiguration();
     // pega o objeto de configuracao
     if ($cfg->getOption('schema_name') != null) {
         // se especificou um schema
         $schema = $cfg->getOption('schema_name') . '.';
         // coloca o nome do schema mais um ponto
     }
     // se a pessoa especificou um linkTo e linkName e ambos existem
     if ($opt != null && $dest != null) {
         Lumine_Log::debug('Ambos links especificados, fazendo uniao...');
         // se for uma uniao many-to-many e ambas tabelas forem iguais
         if ($opt['type'] == Lumine_Metadata::MANY_TO_MANY && $dest['type'] == Lumine_Metadata::MANY_TO_MANY && $opt['table'] == $dest['table']) {
             Lumine_Log::debug('Link do tipo N-N');
             $joinString = "%s JOIN %s ON %s.%s = %s.%s " . PHP_EOL;
             // prepara a string de uniao
             $joinString .= " %s JOIN %s %s ON %s.%s = %s.%s ";
             $this_link = $this->metadata()->getField($opt['linkOn']);
             // pega o campo referente a uniao desta entidade
             $dest_link = $obj->metadata()->getField($dest['linkOn']);
             // pega o campo referente a uniao da entidade que esta sendo unida
             $joinString = sprintf($joinString, $type, $schema . $opt['table'], $opt['table'], $opt['column'], $this->alias(), $this_link['column'], $type, $schema . $obj->metadata()->getTablename(), $obj->alias(), $obj->alias(), $dest_link['column'], $dest['table'], $dest['column']);
             $this->_join[] = $joinString . $extraCondition;
             // coloca a string de uniao na lista
         } else {
             Lumine_Log::debug('Link do tipo 1-N');
             $this_alias = $this->alias() == '' ? $this->metadata()->getTablename() : $this->alias();
             $obj_alias = $obj->alias() == '' ? $obj->metadata()->getTablename() : $obj->alias();
             $joinString = "%s JOIN %s %s ON %s.%s = %s.%s";
             // inicia a string do join
             $joinString = sprintf($joinString, $type, $schema . $obj->metadata()->getTablename(), $obj_alias, $this_alias, $opt['column'], $obj_alias, $dest['column']);
             $this->_join[] = $joinString . $extraCondition;
             // adiciona a string montada na lista
         }
     } else {
         // mas se nao especificou o linkName e linkTo
         // achou o relacionamento na outra entidade
         // significa que la tem a chave que liga aqui ou vice-e-versa
         if ($opt != null) {
             Lumine_Log::debug('Join de ' . $obj->metadata()->getClassname() . ' com ' . $this->metadata()->getClassname() . ' do tipo ' . $opt['type'], __FILE__, __LINE__);
             switch ($opt['type']) {
                 case Lumine_Metadata::MANY_TO_ONE:
                     $res = $obj->metadata()->getField($opt['linkOn']);
                     $this_alias = $this->alias();
                     if (empty($this_alias)) {
                         $this_alias = $this->metadata()->getTablename();
                     }
                     $ent_alias = $obj->alias();
                     $field = $this->metadata()->getField($opt['name']);
                     $joinStr = $type . " JOIN " . $schema . $obj->metadata()->getTablename() . " " . $ent_alias . " ON ";
                     if (empty($ent_alias)) {
                         $ent_alias = $obj->metadata()->getTablename();
                     }
                     $joinStr .= $ent_alias . '.' . $res['column'] . ' = ';
                     $joinStr .= $this_alias . '.' . $field['column'];
                     $this->_join[] = $joinStr . $extraCondition;
                     break;
                 case Lumine_Metadata::ONE_TO_MANY:
                     $res = $obj->metadata()->getField($opt['linkOn']);
                     $this_ref = $this->metadata()->getField($res['options']['linkOn']);
                     $obj_alias = $obj->alias();
                     $this_alias = $this->alias();
                     if (empty($obj_alias)) {
                         $obj_alias = $obj->metadata()->getTablename();
                     }
                     if (empty($this_alias)) {
                         $this_alias = $this->metadata()->getTablename();
                     }
                     $joinStr = $type . " JOIN " . $schema . $obj->metadata()->getTablename() . ' ' . $obj_alias . ' ON ';
                     $joinStr .= sprintf('%s.%s = %s.%s', $obj_alias, $res['column'], $this_alias, $this_ref['column']);
                     $this->_join[] = $joinStr . $extraCondition;
                     break;
                 case Lumine_Metadata::MANY_TO_MANY:
                     $lnk = $obj->metadata()->getRelation($this->metadata()->getClassname());
                     $this_table = $opt['table'];
                     $obj_table = $lnk['table'];
                     if ($this_table != $obj_table) {
                         throw new Lumine_Exception('As tabelas de relacionamento devem ser iguais em ' . $obj->metadata()->getClassname() . ' e ' . $this->metadata()->getClassname(), Lumine_Exception::ERROR);
                     }
                     $schema = $this->_getConfiguration()->getOption('schema_name');
                     if (!empty($schema)) {
                         $schema .= '.';
                     }
                     $this_res = $this->metadata()->getField($opt['linkOn']);
                     $obj_res = $obj->metadata()->getField($lnk['linkOn']);
                     if (empty($opt['column'])) {
                         $mtm_column = $this_res['column'];
                     } else {
                         $mtm_column = $opt['column'];
                     }
                     if (empty($lnk['column'])) {
                         $mtm_column_2 = $obj_res['column'];
                     } else {
                         $mtm_column_2 = $lnk['column'];
                     }
                     $alias_1 = $this->alias();
                     $alias_2 = $obj->alias();
                     if (empty($alias_1)) {
                         $alias_1 = $this->metadata()->getTablename();
                     }
                     if (empty($alias_2)) {
                         $alias_2 = $obj->metadata()->getTablename();
                     }
                     $joinStr = sprintf('%s JOIN %s ON %s.%s = %s.%s', $type, $schema . $this_table, $this_table, $mtm_column, $alias_1, $this_res['column']);
                     $this->_join[] = $joinStr;
                     $joinStr = sprintf('%s JOIN %s %s ON %s.%s = %s.%s', $type, $schema . $obj->metadata()->getTablename(), $alias_2, $obj_table, $mtm_column_2, $alias_2, $obj_res['column']);
                     $this->_join[] = $joinStr . $extraCondition;
                     break;
                 default:
                     throw new Lumine_Exception('Tipo de uniao nao encontrada: ' . $opt['type'], Lumine_Exception::ERROR);
             }
         }
     }
     $list = $obj->_getObjectPart('_join_list');
     reset($this->_join_list);
     foreach ($list as $ent) {
         $add = true;
         foreach ($this->_join_list as $this_ent) {
             if ($ent->metadata()->getClassname() == $this_ent->metadata()->getClassname() && $ent->alias() == $this_ent->alias()) {
                 $add = false;
                 break;
             }
         }
         if (!$add) {
             continue;
         }
         // ok pode adicionar
         $this->_join_list[] = $ent;
         $this->_join = array_merge($this->_join, $ent->_getStrJoinList());
         $where = $ent->_makeWhereFromFields();
         if (!empty($where)) {
             $this->where($where);
         }
     }
     $this->_join = array_unique($this->_join);
     return $this;
 }
예제 #6
0
 /**
  * Gera os arquivos
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param boolean $overwrite Forca a sobrescrita nos arquivos
  * @return void
  */
 private function generateFiles($overwrite)
 {
     Lumine_Log::debug('Gerando arquivos direto na pasta');
     $fullpath = $this->cfg->getProperty('class_path') . DIRECTORY_SEPARATOR . str_replace('.', DIRECTORY_SEPARATOR, $this->cfg->getProperty('package'));
     $sufix = $this->cfg->getOption('class_sufix');
     if (!empty($sufix)) {
         $sufix = '.' . $sufix;
     }
     $dummy = new Lumine_Reverse_ClassTemplate();
     $end = $dummy->getEndDelim();
     if (!file_exists($fullpath) && $this->cfg->getOption('create_paths') == 1) {
         mkdir($fullpath, 0777, true) or die('Não foi possivel criar o diretorio: ' . $fullpath);
     }
     reset($this->files);
     foreach ($this->files as $classname => $content) {
         $filename = $fullpath . DIRECTORY_SEPARATOR . $classname . $sufix . '.php';
         if (file_exists($filename) && empty($overwrite)) {
             $fp = fopen($filename, 'r');
             $old_content = fread($fp, filesize($filename));
             fclose($fp);
             $start = strpos($old_content, $end) + strlen($end);
             $customized = substr($old_content, $start);
             $top = substr($content, 0, strpos($content, $end));
             $content = $top . $end . $customized;
         }
         $fp = @fopen($filename, 'w');
         if ($fp) {
             fwrite($fp, $content);
             fclose($fp);
             chmod($filename, 0777);
             Lumine_Log::debug('Arquivo para a classe ' . $classname . ' gerado com sucesso');
         } else {
             Lumine_Log::error('O PHP nao tem direito de escrita na pasta "' . $fullpath . '". Verifique se o diretario existe e se o PHP tem direito de escrita.');
             exit;
         }
     }
     //// cria os dtos
     if ($this->cfg->getOption('create_dtos')) {
         reset($this->dtos);
         // pasta raiz dos DTO's
         $path = $this->cfg->getProperty('class_path') . DIRECTORY_SEPARATOR . str_replace('.', DIRECTORY_SEPARATOR, $this->cfg->getProperty('package')) . DIRECTORY_SEPARATOR . 'dto';
         // para cada DTO
         foreach ($this->dtos as $obj) {
             $fullpath = $path . DIRECTORY_SEPARATOR . str_replace('.', DIRECTORY_SEPARATOR, $obj->getPackage());
             // se o diretorio nao existe, tenta criar
             if (!is_dir($fullpath) && $this->cfg->getOption('create_paths') == 1) {
                 mkdir($fullpath, 0777, true) or die('Não foi possivel criar o diretorio: ' . $fullpath);
             }
             $filename = $fullpath . DIRECTORY_SEPARATOR . $obj->getClassname() . $sufix . '.php';
             file_put_contents($filename, $obj->getContent());
         }
     }
     // models
     foreach ($this->models as $item) {
         Lumine_Log::debug('Criando Model ' . $item->getClassname());
         $filename = $item->getFullFileName();
         if (!is_dir(dirname($filename)) && $this->cfg->getOption('create_paths') == 1) {
             $path = dirname($filename);
             mkdir($path, 0777, true) or die('Não foi possivel criar o diretorio: ' . $path);
         } else {
             if (!is_dir(dirname($filename))) {
                 $path = dirname($filename);
                 Lumine_Log::error('Nao eh possivel gravar em ' . $path . '. Verifique se a pasta existe e se ha permissao de gravacao');
             }
         }
         $content = $item->getContent();
         file_put_contents($filename, $content);
         chmod($filename, 0777);
     }
     // copia o arquivo de contexto
     if ($this->cfg->getOption('model_context') == 1) {
         $contextFile = LUMINE_INCLUDE_PATH . '/lib/Templates/ApplicationContext.php';
         if (file_exists($contextFile)) {
             $path = $this->cfg->getProperty('class_path') . DIRECTORY_SEPARATOR . $this->cfg->getOption('model_context_path') . DIRECTORY_SEPARATOR;
             if (!is_dir($path)) {
                 if ($this->cfg->getOption('create_paths') == 1) {
                     mkdir($path, 0777, true) or die('Não foi possivel criar o diretorio ' . $path);
                 } else {
                     Lumine_Log::error('Nao foi possivel gravar o contexto na pasta ' . $path . '. Verifique se a pasta existe.');
                 }
             }
             $destino = $path . 'Lumine_ApplicationContext.php';
             // so copiamos se o arquivo nao existir
             if (!file_exists($destino)) {
                 Lumine_Log::debug('Copiando arquivo de contexto: ' . $destino);
                 copy($contextFile, $destino);
                 chmod($path . 'Lumine_ApplicationContext.php', 0777);
                 // ja existe, nao copaimos mas avisamos
             } else {
                 Lumine_Log::debug('O arquivo "' . $destino . '" ja existe');
             }
         }
     }
     // escreve os controles
     $path = $this->cfg->getProperty('class_path');
     $path .= DIRECTORY_SEPARATOR . 'controls' . DIRECTORY_SEPARATOR;
     if (!file_exists($path) && $this->cfg->getOption('create_paths') == 1) {
         mkdir($path, 0777, true) or die('Nao foi possivel criar o diretorio: ' . $path);
     }
     foreach ($this->controls as $classname => $content) {
         $filename = $path . $classname . '.php';
         $fp = @fopen($filename, 'w');
         if (!$fp) {
             Lumine_Log::error('O PHP nao tem direito de escrita para gerar o arquivo "' . $filename . '". Verifique se o diretorio existe e se o PHP tem direito de escrita.');
             exit;
         } else {
             fwrite($fp, $content);
             fclose($fp);
             Lumine_Log::debug('Arquivo de controle "' . $filename . '" gerado com sucesso.');
         }
     }
     // copia os demais arquivos
     if (!empty($this->controls) && $this->cfg->getOption('create_controls') != '') {
         $class = 'Lumine_Form_' . $this->cfg->getOption('create_controls');
         $ref = new ReflectionClass($class);
         $instance = $ref->newInstance(null);
         $instance->copyFiles($path);
     }
     // escreve o arquivo de configuracao
     $filename = $this->cfg->getProperty('class_path') . DIRECTORY_SEPARATOR . 'lumine-conf.php';
     $fp = @fopen($filename, 'w');
     if (!$fp) {
         Lumine_Log::error('O PHP nao tem direito de escrita para gerar o arquivo "' . $filename . '". Verifique se o diretorio existe e se o PHP tem direito de escrita.');
         exit;
     }
     fwrite($fp, $this->config);
     fclose($fp);
     Lumine_Log::debug('Arquivo "' . $filename . '" gerado com sucesso.');
 }
예제 #7
0
 /**
  * @see Lumine_Connection_IConnection::getForeignKeys()
  */
 public function getForeignKeys($tablename)
 {
     if (!$this->connect()) {
         return false;
     }
     $sql = "SELECT pg_catalog.pg_get_constraintdef(r.oid, true) as condef\n\t\t\t\tFROM pg_catalog.pg_constraint r, pg_catalog.pg_class c\n\t\t\t\tWHERE r.conrelid = c.oid AND r.contype = 'f'\n\t\t\t\tAND c.relname = '" . $tablename . "'";
     $fks = array();
     $rs = $this->executeSQL($sql);
     while ($row = pg_fetch_row($rs)) {
         // Exemplo:
         // FOREIGN KEY (idusuario) REFERENCES usuario(idusuario) ON UPDATE CASCADE ON DELETE CASCADE
         //preg_match('@FOREIGN KEY \((\w+)\) REFERENCES (\w+)\((\w+)\)(.*?)$@i', str_replace('"', '', $row[0]), $matches);
         //preg_match('@FOREIGN KEY \((\w+(.*?)?)\) REFERENCES (\w+)\((\w+(.*?))\)(.*?)$@i', str_replace('"', '', $row[0]), $matches);
         preg_match('@FOREIGN KEY \\((?<from>\\w+(.*?)?)\\) REFERENCES (?<target_table>\\w+\\.?\\w+)\\((?<target_column>\\w+\\.?\\w+(.*?))\\)(.*?)$@i', str_replace('"', '', $row[0]), $matches);
         $listFrom = explode(',', str_replace(' ', '', $matches['from']));
         $listTo = explode(',', str_replace(' ', '', $matches['target_column']));
         if (count($listFrom) != count($listTo)) {
             Lumine_Log::error('O numero de itens de origem nao e igual ao numero de itens de destino');
             exit;
         }
         for ($i = 0; $i < count($listFrom); $i++) {
             // removemos o nome do schema
             // 22/03/2011 - encontrado por Thiago Marsiglia
             $targetTable = end(explode('.', $matches['target_table']));
             // nome da fk
             $name = $targetTable;
             $fieldFrom = $listFrom[$i];
             $fieldTo = $listTo[$i];
             if (isset($fks[$name])) {
                 $name = $name . '_' . $fieldTo;
             }
             $fks[$name]['from'] = $fieldFrom;
             $fks[$name]['to'] = $targetTable;
             $fks[$name]['to_column'] = $fieldTo;
             $reg = array();
             if (preg_match('@(.*?)ON UPDATE (RESTRICT|CASCADE)@i', $matches[5], $reg)) {
                 $fks[$name]['update'] = strtoupper($reg[2]);
             } else {
                 $fks[$name]['update'] = 'RESTRICT';
             }
             if (preg_match('@(.*?)ON DELETE (RESTRICT|CASCADE)@i', $matches[5], $reg)) {
                 $fks[$name]['delete'] = strtoupper($reg[2]);
             } else {
                 $fks[$name]['delete'] = 'RESTRICT';
             }
         }
     }
     return $fks;
 }
예제 #8
0
 private function validateByClass($val, $fieldname, $classname, $method)
 {
     if (empty($classname)) {
         Lumine_Log::warning('Classe para validacao nao informada no XML. Use "classname" para informar o nome da classe');
         return false;
     }
     $ds = DIRECTORY_SEPARATOR;
     $cfg = $this->obj->_getConfiguration();
     $classpath = $cfg->getProperty('class_path');
     $classespath = $classpath . $ds . str_replace('.', '/', $cfg->getProperty('package')) . $ds . 'validators' . $ds;
     $classfile = str_replace('.', '/', $classname) . '.php';
     $classdef = array_pop(explode('.', $classname));
     $php_validator_path = $cfg->getOption('php_validator_path');
     $possibilidades = array();
     if (!empty($php_validator_path)) {
         $possibilidades[] = $php_validator_path . $ds . $classfile;
     }
     $possibilidades[] = LUMINE_INCLUDE_PATH . $ds . 'lib' . $ds . 'Validator' . $ds . 'Custom' . $ds . $classfile;
     $possibilidades[] = $classpath . $ds . $classfile;
     $possibilidades[] = $classespath . $classfile;
     $use = '';
     foreach ($possibilidades as $file) {
         if (file_exists($file)) {
             $use = $file;
         }
     }
     if (empty($use)) {
         Lumine_Log::error('Classe para validacao "' . $classname . '" nao encontrada');
         return false;
     }
     require_once $use;
     if (!class_exists($classdef)) {
         Lumine_Log::error('Definicao para a classe de validacao "' . $classdef . '" nao encontrada');
         return false;
     }
     $tester = new $classdef();
     if (method_exists($tester, $method) && $method != '') {
         return $tester->{$method}($val);
     } else {
         if (method_exists($tester, 'execute')) {
             return $tester->execute($val);
         } else {
             Lumine_Log::error('Metodo "' . $method . '" nao encontrado na classe "' . $classdef . '" e a classe nao possui o metodo "execute"');
             return false;
         }
     }
 }
예제 #9
0
 /**
  * 
  * @see Lumine_Form_IForm::getControlTemplate()
  */
 public function getControlTemplate(Lumine_Configuration $cfg, $className)
 {
     $file = LUMINE_INCLUDE_PATH . $this->template . 'control.txt';
     if (!file_exists($file)) {
         Lumine_Log::error('O arquivo "' . $file . '" nao existe!');
         exit;
     }
     $content = file_get_contents($file);
     $content = str_replace('{class_path}', str_replace('\\', '/', $cfg->getProperty('class_path')), $content);
     $content = str_replace('{entity_name}', $className, $content);
     $content = str_replace('{LUMINE_PATH}', LUMINE_INCLUDE_PATH, $content);
     return $content;
 }
예제 #10
0
 /**
  * @see IConnection::connect()
  */
 public function connect()
 {
     if ($this->conn_id && self::$state == self::OPEN) {
         Lumine_Log::debug('Utilizando conexao cacheada com ' . $this->getDatabase());
         return true;
     }
     $this->dispatchEvent(new Lumine_ConnectionEvent(Lumine_Event::PRE_CONNECT, $this));
     $hostString = 'host=' . $this->getHost();
     $hostString .= ' dbname=' . $this->getDatabase();
     if ($this->getPort() != '') {
         $hostString .= ' port=' . $this->getPort();
     }
     if ($this->getUser() != '') {
         $hostString .= ' user='******'') {
         $hostString .= ' password='******'socket']) && $this->options['socket'] != '') {
         $hostString .= ' socket=' . $this->options['socket'];
     }
     $flags = isset($this->options['flags']) ? $this->options['flags'] : null;
     if (isset($this->options['persistent']) && $this->options['persistent'] == true) {
         Lumine_Log::debug('Criando conexao persistente com ' . $this->getDatabase());
         $this->conn_id = pg_pconnect($hostString);
     } else {
         Lumine_Log::debug('Criando conexao com ' . $this->getDatabase());
         $this->conn_id = pg_connect($hostString);
     }
     if (!$this->conn_id) {
         self::$state = self::CLOSED;
         $msg = 'nao foi possivel conectar no banco de dados: ' . $this->getDatabase() . ' - ' . $this->getErrorMsg();
         Lumine_Log::error($msg);
         $this->dispatchEvent(new Lumine_ConnectionEvent(Lumine_Event::CONNECTION_ERROR, $this, $msg));
         throw new Exception($msg);
         return false;
     }
     self::$state = self::OPEN;
     $this->dispatchEvent(new Lumine_ConnectionEvent(Lumine_Event::POS_CONNECT, $this));
     return true;
 }