Exemplo n.º 1
0
 /**
  * Salva os objetos vinculados a este que dependem deste 
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/lumine
  * @return void
  */
 protected function saveDependentObjects()
 {
     $schema = $this->_getConfiguration()->getOption('schema_name');
     if (!empty($schema)) {
         $schema .= '.';
     }
     foreach ($this->metadata()->getRelations() as $name => $def) {
         switch ($def['type']) {
             case Lumine_Metadata::ONE_TO_MANY:
                 $list = $this->fieldValue($name);
                 if (!empty($list) && is_array($list)) {
                     foreach ($list as $val) {
                         if ($val instanceof Lumine_Base) {
                             $relname = $this->metadata()->getClassname();
                             try {
                                 $field = $val->metadata()->getRelation($relname, Lumine_Metadata::MANY_TO_ONE);
                                 $val->setFieldValue($field['name'], $this->{$field}['linkOn']);
                                 $val->save();
                             } catch (Lumine_Exception $e) {
                                 Lumine_log::warning('nao foi possivel encontrar o campo ' . $relname . ' em ' . $val->metadata()->getClassname());
                             }
                         }
                     }
                 }
                 break;
             case Lumine_Metadata::MANY_TO_MANY:
                 $list = $this->{$name};
                 if (!empty($list) && is_array($list)) {
                     foreach ($list as $val) {
                         // se for uma instancia de Lumine_Base
                         if ($val instanceof Lumine_Base) {
                             // pega o valor da chave primaria
                             $f1 = $this->metadata()->getField($def['linkOn']);
                             $v1 = $this->fieldValue($def['linkOn']);
                             // salva o objeto
                             $val->save();
                             // valor do outro objeto
                             $rel = $val->metadata()->getRelation($this->metadata()->getClassname(), Lumine_Metadata::MANY_TO_MANY);
                             $f2 = $val->metadata()->getField($rel['linkOn']);
                             $v2 = $val->fieldValue($f2['name']);
                             // se ambos nao forem nulos
                             if (!is_null($v1) && !is_null($v2)) {
                                 // verifica se ja existe
                                 $sv1 = Lumine_Parser::getParsedValue($this, $v1, $f1['type']);
                                 $sv2 = Lumine_Parser::getParsedValue($val, $v2, $f2['type']);
                                 $sql = "SELECT * FROM " . $schema . $def['table'] . " WHERE ";
                                 $sql .= $def['column'] . '=' . $sv1;
                                 $sql .= ' AND ';
                                 $sql .= $rel['column'] . '=' . $sv2;
                                 $ref = new ReflectionClass(get_class($this));
                                 $ponte = $ref->newInstance();
                                 Lumine_Log::debug('Verificando existencia da referencia do objeto no banco: ' . $sql);
                                 $ponte->query($sql);
                                 // se nao existir
                                 if ($ponte->numrows() == 0) {
                                     // insert
                                     $sql = "INSERT INTO " . $schema . $def['table'] . "(%s, %s) VALUES (%s, %s)";
                                     $sql = sprintf($sql, $def['column'], $rel['column'], $sv1, $sv2);
                                     $ponte->query($sql);
                                 }
                                 $ponte->destroy();
                             }
                         } else {
                             // pega o valor do campo desta classe
                             $campo = $this->metadata()->getField($def['linkOn']);
                             $valor_pk = $this->fieldValue($campo['name']);
                             // se este objeto tem um valor no campo indicado
                             if (!is_null($valor_pk)) {
                                 // primeiro vemos se este valor ja nao existe
                                 $sql = "SELECT * FROM " . $schema . $def['table'] . " WHERE ";
                                 // pega o valor do campo desta entidade
                                 $valor_objeto = Lumine_Parser::getParsedValue($this, $valor_pk, $campo['type']);
                                 // instanciamos a classe estrangeira
                                 $this->_getConfiguration()->import($def['class']);
                                 $obj = new $def['class']();
                                 // pega o relacionamento com esta entidade
                                 $rel = $obj->metadata()->getRelation($this->metadata()->getClassname(), Lumine_Metadata::MANY_TO_MANY);
                                 $rel_def = $obj->metadata()->getField($rel['linkOn']);
                                 // ajusta o valor
                                 $valor_estrangeiro = Lumine_Parser::getParsedValue($obj, $val, $rel_def['type']);
                                 // termina a SQL
                                 $sql .= $def['column'] . '=' . $valor_objeto;
                                 $sql .= " AND ";
                                 $sql .= $rel['column'] . '=' . $valor_estrangeiro;
                                 $obj->query($sql);
                                 $res = $obj->numrows();
                                 // se nao encontrou
                                 if ($res == 0) {
                                     // insere
                                     $sql = "INSERT INTO %s (%s,%s) VALUES (%s,%s)";
                                     $sql = sprintf($sql, $schema . $def['table'], $def['column'], $rel['column'], $valor_objeto, $valor_estrangeiro);
                                     Lumine_Log::debug("Inserindo valor Many-To-Many: " . $sql);
                                     $obj->query($sql);
                                 }
                                 $obj->destroy();
                             } else {
                                 Lumine_Log::warning('A o campo "' . $pks[0]['name'] . ' da classe "' . $this->metadata()->getClassname() . '" nao possui um valor');
                             }
                         }
                     }
                 }
                 break;
         }
     }
 }
Exemplo n.º 2
0
 /**
  * @see Lumine_Dialect_IDialect::num_rows()
  */
 public function num_rows()
 {
     if (empty($this->resultList[$this->getObjectId()])) {
         Lumine_Log::warning('A consulta deve primeiro ser executada');
         return 0;
     }
     return $this->getConnection()->num_rows($this->resultList[$this->getObjectId()]);
 }
Exemplo n.º 3
0
 /**
  * 
  * @see Lumine_Dialect_IDialect::execute()
  */
 public function execute($sql)
 {
     $cn = $this->getConnection();
     if ($cn == null) {
         throw new Lumine_Dialect_Exception('Conexao nao setada');
     }
     $cn->connect();
     $this->setConnection($cn);
     try {
         Lumine_Log::debug('Executando consulta: ' . $sql);
         $mode = $this->getFetchMode();
         $rs = $cn->executeSQL($sql);
         //$this->pointer = 0;
         if (is_resource($rs)) {
             // limpa o resultado anterior
             $this->freeResult($this->getObjectId());
             Lumine_Log::debug('Armazenando resultset');
             $this->setResultset($rs);
             $data = array();
             Lumine_Log::debug('Iterando pelos resultados');
             while ($row = ibase_fetch_assoc($this->getResultset(), IBASE_FETCH_BLOBS)) {
                 $data[] = $row;
             }
             Lumine_Log::debug('Alterando o dataset');
             $this->setDataset($data);
             Lumine_Log::debug('Gravando pointer list');
             $this->pointerList[$this->getObjectId()] = 0;
             return true;
         } else {
             return $rs;
         }
     } catch (Exception $e) {
         Lumine_Log::warning('Falha na consulta: ' . $cn->getErrorMsg());
         throw new Lumine_SQLException($cn, $sql, $cn->getErrorMsg());
         return false;
     }
 }
Exemplo n.º 4
0
 /**
  * altera as colunas
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param array $arrayColumns
  * @return void
  */
 function setColumns($arrayColumns)
 {
     $old = $this->columns;
     try {
         $this->columns = array();
         foreach ($arrayColumns as $column) {
             $this->addColumn($column);
         }
     } catch (Exception $e) {
         Lumine_Log::warning('Formato de coluna invalido, restaurando anterior...');
         $this->columns = $old;
     }
 }
Exemplo n.º 5
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;
         }
     }
 }
Exemplo n.º 6
0
 /**
  * Exibe uma mensagem no log dizendo que este metodo nao pode ser feito para esta instancia
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @return void
  */
 private function negado()
 {
     $x = debug_backtrace();
     $str = 'Rotina "' . $x[1]['function'] . '" negada nesta classe';
     Lumine_Log::warning($str);
 }
Exemplo n.º 7
0
 /**
  * Carrega models para serem utilizadas com projetos em MVC
  *
  * <code>
  * $cfg = new Lumine_Configuration($lumineConf);
  * $cfg->loadModel('PessoaModel','CarroModel','BicicletaModel');
  *
  * // agora as classes ja podem ser usadas
  * $obj = new PessoaModel;
  * $car = new CarroModel;
  * </code>
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @return void
  */
 public function loadModel()
 {
     $list = func_get_args();
     $notfound = array();
     foreach ($list as $className) {
         $ps = DIRECTORY_SEPARATOR;
         $path = $this->getProperty('class_path') . $ps . $this->getOption('model_path') . $ps;
         $sufix = $this->getOption('class_sufix');
         if ($sufix != null) {
             $sufix = '.' . $sufix;
         }
         $sufix = $sufix . '.php';
         $filename = $path . $className . $sufix;
         if (class_exists($className)) {
             Lumine_Log::debug('Model ja existente: ' . $className);
             return;
         }
         if (file_exists($filename)) {
             require_once $filename;
             if (!class_exists($className)) {
                 throw new Lumine_Exception('A model ' . $className . ' nao existe no arquivo ' . $filename);
             }
             Lumine_Log::debug('Model carregada: ' . $className);
         } else {
             Lumine_Log::warning('Arquivo nao encontrado: ' . $filename);
             $notfound[] = $className;
         }
     }
 }
Exemplo n.º 8
0
 /**
  * Trunca os valores de string conforme o comprimento do campo
  * 
  * @author Hugo Ferreira da Silva
  * @param array $prop Propriedades do campo
  * @param string $value String a ser truncada
  * @return stirng String truncada
  */
 public static function truncateValue($prop, $value)
 {
     if (!isset($prop['length'])) {
         return $value;
     }
     switch (strtolower($prop['type'])) {
         case 'text':
         case 'longtext':
         case 'tinytext':
         case 'blob':
         case 'longblob':
         case 'tinyblob':
         case 'varchar':
         case 'varbinary':
         case 'char':
             if (strlen($value) > $prop['length']) {
                 Lumine_Log::warning('Truncando valor do campo ' . (isset($prop['name']) ? $prop['name'] : $prop['column']) . ' (' . $prop['length'] . ')');
                 $value = substr($value, 0, $prop['length']);
             }
             break;
     }
     return $value;
 }
Exemplo n.º 9
0
 /**
  * Recupera uma conexao com o nome informado
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param string $connectionName Nome da conexao desejada
  * @return Lumine_Configuration Configuracao / conexao encontrada ou false se nao recuperar
  */
 public function getConnection($connectionName)
 {
     if (!isset($this->connections[$connectionName])) {
         Lumine_Log::warning('Conexao inexistente: ' . $connectionName);
         return false;
     }
     return $this->connections[$connectionName]->getConnection();
 }
Exemplo n.º 10
0
 /**
  * Exibe os resultados de uma consulta em uma tabela HTML
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param Lumine_Base $obj
  * @return void
  */
 public static function showResult(Lumine_Base $obj)
 {
     $sql = $obj->_getSQL();
     $resultset = $obj->allToArray();
     if (!empty($resultset)) {
         $header = $resultset[0];
         $style = ' style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:9px" ';
         echo '<table cellpadding="2" cellspacing="1" width="100%">';
         echo '<tr>';
         echo '<tr>' . PHP_EOL;
         echo '<td ' . $style . ' colspan="' . count($header) . '">' . $sql . '</td>' . PHP_EOL;
         echo '</tr>' . PHP_EOL;
         foreach ($header as $key => $value) {
             echo '<td' . $style . ' bgcolor="#CCCCCC">' . $key . '</td>' . PHP_EOL;
         }
         echo '</tr>';
         for ($i = 0; $i < count($resultset); $i++) {
             $row = $resultset[$i];
             $cor = $i % 2 != 0 ? '#EFEFEF' : '#FFFFFF';
             echo '<tr>';
             foreach ($row as $value) {
                 echo '<td' . $style . ' bgcolor="' . $cor . '">' . $value . '</td>' . PHP_EOL;
             }
             echo '</tr>';
         }
         echo '</table>';
     } else {
         Lumine_Log::warning('Nenhum resultado encontrado no objeto passado: ' . get_class($obj));
     }
 }