コード例 #1
0
ファイル: Sequence.php プロジェクト: rrmoura1/Abstergo
 /**
  * Recupera uma sequencia para um campo
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param array $field
  * @return string
  */
 public function getSequence($field)
 {
     $st = null;
     $con_st = $this->obj->_getConnection()->getOption('sequence_type');
     if (empty($field['sequence_type'])) {
         $st = $con_st;
     } else {
         $st = $field['sequence_type'];
     }
     $dialect = $this->obj->_getConfiguration()->getProperty('dialect');
     switch ($st) {
         case self::SEQUENCE:
             $class = $dialect . "_Sequence";
             Lumine::load('Sequence_' . $class);
             $this->seq_obj = new $class($obj, $field);
             break;
         case self::COUNT_TABLE:
             $class = $dialect . "_Count";
             Lumine::load('Sequence_' . $class);
             $this->seq_obj = new $class($obj, $field);
             break;
         case self::NATURAL:
         default:
             $class = $dialect . "_Natural";
             Lumine::load('Sequence_' . $class);
             $this->seq_obj = new $class($obj, $field);
     }
     $this->seq_obj->createSequence();
     return $this->seq_obj;
 }
コード例 #2
0
 /**
  * Recupera os metadados do campo
  * 
  * @param Lumine_Base $target
  * @author Hugo Ferreira da Silva
  */
 public function getFieldMetadata(Lumine_Base $target)
 {
     $result = null;
     try {
         $result = $target->metadata()->getField($this->getField());
     } catch (Exception $e) {
     }
     return $result;
 }
コード例 #3
0
ファイル: Factory.php プロジェクト: rrmoura1/Abstergo
 /**
  * Recupera o dialeto para o objeto
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param Lumine_Base $obj
  * @return ILumine_Dialect
  */
 public static function get(Lumine_Base $obj)
 {
     $dialect = $obj->_getConfiguration()->getProperty('dialect');
     $id = $obj->_getObjectPart('_objectID');
     if (!array_key_exists($dialect, self::$createdItems)) {
         Lumine::load('Lumine_Dialect_' . $dialect);
         $ref = new ReflectionClass('Lumine_Dialect_' . $dialect);
         self::$createdItems[$dialect] = $ref->newInstance();
     }
     self::$createdItems[$dialect]->setConnection($obj->_getConnection());
     self::$createdItems[$dialect]->setObjectId($id);
     self::$createdItems[$dialect]->setTablename($obj->tablename());
     return self::$createdItems[$dialect];
 }
コード例 #4
0
ファイル: Factory.php プロジェクト: bladerangel/aplicacao
 /**
  * Construtor da classe
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br
  * @param string $package Nome do pacote
  * @param string $tablename nome da tabela que ela representa
  * @return Lumine_Factory
  */
 function __construct($package, $tablename)
 {
     $this->_metadata = new Lumine_Metadata($this);
     $this->metadata()->setPackage($package);
     $this->metadata()->setTablename($tablename);
     parent::__construct();
 }
コード例 #5
0
ファイル: Union.php プロジェクト: rrmoura1/Abstergo
 /**
  * Construtor
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param Lumine_Configuration $cfg
  * @return Lumine_Union
  */
 function __construct(Lumine_Configuration $cfg)
 {
     $clname = 'Lumine_Dialect_' . $cfg->getProperty('dialect');
     $this->_package = $cfg->getProperty('package');
     $this->_tablename = 'union';
     parent::__construct();
     // $this->_bridge = new $clname( $this );
 }
コード例 #6
0
ファイル: Tokenizer.php プロジェクト: rrmoura1/Abstergo
 /**
  * Faz o parse do dataselect de uma instancia
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param string $dataStr
  * @param Lumine_Base $obj
  * @return string
  */
 public static function dataSelect($dataStr, Lumine_Base $obj)
 {
     $idx = 0;
     $total = strlen($dataStr);
     $d = ',';
     $tokens = array();
     $inStr = false;
     $inFunction = 0;
     $inStrStart = '';
     for ($i = 0; $i < $total; $i++) {
         $c = substr($dataStr, $i, 1);
         if ($c == '(' && !$inStr) {
             $inFunction++;
         }
         if ($c == ')' && !$inStr) {
             $inFunction--;
         }
         if (!$inStr && ($c == '"' || $c == "'") && substr($dataStr, $i - 1, 1) != '\\' && $c != '\\') {
             $inStr = true;
             $inStrStart = $c;
         }
         if ($inStr == true && $c == $inStrStart) {
             if (!empty($tokens)) {
                 $tmp_test = str_replace($obj->_getConnection()->getEscapeChar() . $inStrStart, '', $c . $tokens[$idx] . $c);
                 if (substr_count($tmp_test, "'") % 2 == 0) {
                     $inStr = false;
                     $tmp = '';
                     $inStrStart = '';
                 }
             }
         }
         if ($inFunction == 0 && !$inStr && $c == $d) {
             $idx++;
             continue;
         }
         if (!isset($tokens[$idx])) {
             $tokens[$idx] = '';
         }
         $tokens[$idx] .= $c;
     }
     foreach ($tokens as $id => $token) {
         $tokens[$id] = trim($token);
     }
     return $tokens;
 }
コード例 #7
0
ファイル: Union.php プロジェクト: bladerangel/aplicacao
 /**
  * Construtor
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param Lumine_Configuration $cfg
  * @return Lumine_Union
  */
 function __construct(Lumine_Configuration $cfg)
 {
     $this->_metadata = new Lumine_Metadata($this);
     $clname = 'Lumine_Dialect_' . $cfg->getProperty('dialect');
     $this->metadata()->setPackage($cfg->getProperty('package'));
     $this->metadata()->setTablename('union');
     parent::__construct();
     // $this->_bridge = new $clname( $this );
 }
コード例 #8
0
ファイル: Node.php プロジェクト: bladerangel/aplicacao
 /**
  * Retorna a representacao do node como objeto
  * 
  * @author Hugo Ferreira da Silva
  * @param boolean $withChilds Indica se tambem e para pegar os nos filhos ou nao
  * @return array
  */
 public function toObject($withChilds = true)
 {
     $node = $this->obj->toObject();
     $node->childNodes = array();
     if ($withChilds) {
         $list = $this->getChildNodes();
         $list->reset();
         while ($child = $list->nextSibling()) {
             $node->childNodes[] = $child->toObject($withChilds);
         }
     }
     return $node;
 }
コード例 #9
0
ファイル: XMLValidator.php プロジェクト: rrmoura1/Abstergo
 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;
         }
     }
 }
コード例 #10
0
ファイル: White.php プロジェクト: bladerangel/aplicacao
 /**
  * Insere o registro enviado no banco de dados
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param array $values valores do formulario
  * @return array resultado da validacao
  */
 private function insert($values)
 {
     $def = $this->obj->metadata()->getFields();
     foreach ($def as $name => $prop) {
         if (!empty($prop['options']['foreign']) && empty($values[$name])) {
             $this->obj->setFieldValue($name, null);
         } else {
             if ($this->strip_slashes) {
                 $this->obj->setFieldValue($name, stripslashes(@$values[$name]));
             } else {
                 $this->obj->setFieldValue($name, @$values[$name]);
             }
         }
     }
     // limpamos as pk's que sao auto-incrementaveis
     $obj =& $this->obj;
     $pks = $obj->metadata()->getPrimaryKeys();
     foreach ($pks as $name => $item) {
         if (!empty($item['options']['autoincrement'])) {
             $obj->{$item}['name'] = null;
         }
     }
     // atualiza as referencias MTM
     $def = $obj->metadata()->getRelations(FALSE);
     foreach ($def as $name => $prop) {
         if ($prop['type'] == Lumine_Metadata::MANY_TO_MANY) {
             $obj->removeAll($name);
             if (!empty($values[$name])) {
                 foreach ($values[$name] as $id) {
                     $obj->{$name}[] = $id;
                 }
             }
         }
     }
     // $this->obj->populateFrom($values);
     $res = $this->obj->validate();
     if ($res === true) {
         $this->obj->insert();
         return true;
     }
     return $res;
 }
コード例 #11
0
ファイル: Validator.php プロジェクト: bladerangel/aplicacao
 /**
  * Efetua a validacao
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param Lumine_Base $obj Objeto a ser validado
  * @return array Lista de erros encontrados
  */
 public static function validate(Lumine_Base $obj)
 {
     ############################################################################
     ## Aqui vamos checar todos os tipos padrao de validacao
     ## e armazenar os resultados em um array
     ## para que o objeto passe na validacao, todos os retornos devem ser TRUE
     ## para isto, utilizaremos a interface de reflexao
     ############################################################################
     // aqui armazenamos o resultado das validacoes
     $erros = array();
     $lista = $obj->listValidators();
     /* @var $item Lumine_Validator_AbstractValidator */
     foreach ($lista as $item) {
         if (array_key_exists($item->getField(), $erros)) {
             continue;
         }
         $result = $item->execute($obj);
         if (!$result) {
             $erros[$item->getField()] = $item->getErrorMessage();
         }
     }
     return $erros;
 }
コード例 #12
0
ファイル: Tree.php プロジェクト: bladerangel/aplicacao
 /**
  * Tenta recuperar dinamicamente os campos de identificacao
  * 
  * Para trabalhar com uma estrutura de arvore,
  * e necessario que a tabela tenha:
  * - Uma unica chave primaria
  * - Uma chave estrangeira (FK) que referencie a chave primaria.
  * 
  * Nestas condicoes, Lumine consegue identificar quais sao os campos
  * que compoe a arvore a partir de um dado objeto
  * 
  * @author Hugo Ferreira da Silva
  * @param Lumine_Base $pObj
  * @return array Contendo os campos identificadores
  */
 public static function getTreeFields(Lumine_Base $pObj)
 {
     $pFieldID = null;
     $pFieldParentId = null;
     // pega as definicoes do objeto
     $def = $pObj->metadata()->getFields();
     // chave primaria
     $pk = null;
     // para cada definicao
     foreach ($def as $name => $item) {
         // se for chave primaria
         if (!empty($item['options']['primary'])) {
             // armazenamos seus dados
             $pk = $item;
             $pk['name'] = $name;
             continue;
         }
         // se for chave estrangeira
         if (!empty($item['options']['foreign'])) {
             // se o campo de linkagem for igual a pk e o nome da classe for o nome do objeto
             if ($item['options']['linkOn'] == $pk['name'] && $item['options']['class'] == $pObj->metadata()->getClassname()) {
                 // encontramos os campos!
                 $pFieldId = $pk['name'];
                 $pFieldParentId = $name;
                 break;
             }
         }
     }
     // se continuar nulo
     if (is_null($pFieldId) && is_null($pFieldParentId)) {
         // dispara excecao
         new Lumine_Exception('Os campos indicativos de arvore devem ser informados!');
     }
     $data['fieldId'] = $pFieldId;
     $data['fieldParentId'] = $pFieldParentId;
     return $data;
 }
コード例 #13
0
ファイル: PHPValidator.php プロジェクト: rrmoura1/Abstergo
 /**
  * @param Lumine_Base $obj Objeto a ser validado
  * @return array - Retorna array contendo erros caso validacao invalida
  * @author Cairo Lincoln de Morais Noleto
  * @link http://caironoleto.wordpress.com
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br
  **/
 public static function validate(Lumine_Base $obj)
 {
     $fieldList = !empty(self::$validateList[$obj->_getName()]) ? self::$validateList[$obj->_getName()] : array();
     $errors = array();
     foreach ($fieldList as $fieldName => $validators) {
         // se ja houver um erro para o campo atual
         if (self::checkStackError($errors, $fieldName) == true) {
             // passa para o proximo campo
             continue;
         }
         foreach ($validators as $array) {
             // se ja houver um erro para o campo atual
             if (self::checkStackError($errors, $fieldName) == true) {
                 // passa para o proximo campo
                 break;
             }
             switch ($array["tipoValidacao"]) {
                 //Verifica se e String
                 case 'requiredString':
                     if (!is_string($obj->{$array}["campo"]) || strlen($obj->{$array}["campo"]) == 0) {
                         self::stackError($errors, $fieldName, $array['message']);
                     }
                     if (isset($array["minimo"]) && strlen($obj->{$array}['campo']) < $array['minimo']) {
                         self::stackError($errors, $fieldName, $array['message']);
                     }
                     // se foi informado o tamanho maximo
                     if (isset($array['maximo'])) {
                         // pega o campo
                         $field = $obj->_getField($fieldName);
                         // se o tamanho informado for maior que o comprimento
                         if (isset($field['length']) && $array['maximo'] > $field['length']) {
                             throw new Lumine_Exception('Tamanho invalido para o campo ' . $fieldName, Lumine_Exception::WARNING);
                         }
                         // alterado para se o usuario
                         // informou um tamanho minimo, mas nao o maximo,
                         // o maximo passa a ser o do campo
                     } else {
                         if (!isset($array['maximo']) && isset($array['minimo'])) {
                             $field = $obj->_getField($fieldName);
                             if (isset($field['length'])) {
                                 $array['maximo'] = $field['length'];
                             }
                         }
                     }
                     if (isset($array["maximo"]) && strlen($obj->{$array}['campo']) > $array['maximo']) {
                         self::stackError($errors, $fieldName, $array['message']);
                     }
                     break;
                     //Verifica se e Numero
                 //Verifica se e Numero
                 case 'requiredNumber':
                     if (!is_numeric($obj->{$array}["campo"])) {
                         self::stackError($errors, $fieldName, $array['message']);
                     } else {
                         if (is_numeric($obj->{$array}['campo'])) {
                             if (!is_null($array['minimo']) && $obj->{$array}['campo'] < $array['minimo']) {
                                 self::stackError($errors, $fieldName, $array['message']);
                             } else {
                                 if (!is_null($array['maximo']) && $obj->{$array}['campo'] > $array['maximo']) {
                                     self::stackError($errors, $fieldName, $array['message']);
                                 }
                             }
                         }
                     }
                     break;
                     //Verifica se Tamanho invalido
                 //Verifica se Tamanho invalido
                 case 'requiredLength':
                     if (isset($array["minimo"])) {
                         if (strlen($obj->{$array}["campo"]) < $array["minimo"]) {
                             self::stackError($errors, $fieldName, $array['message']);
                         }
                     }
                     if (isset($array["maximo"])) {
                         if (strlen($obj->{$array}["campo"]) > $array["maximo"]) {
                             self::stackError($errors, $fieldName, $array['message']);
                         }
                     }
                     break;
                     //Verifica se e email
                 //Verifica se e email
                 case 'requiredEmail':
                     //Lumine_Util::validateEmail( $val );
                     $res = Lumine_Util::validateEmail($obj->{$array}["campo"]);
                     if ($res === false) {
                         self::stackError($errors, $fieldName, $array['message']);
                     }
                     break;
                     //Verifica se e uma data
                 //Verifica se e uma data
                 case 'requiredDate':
                     $val = $obj->{$array}["campo"];
                     if (!preg_match('@^((\\d{2}\\/\\d{2}\\/\\d{4})|(\\d{4}-\\d{2}-\\d{2}))$@', $val, $reg)) {
                         self::stackError($errors, $fieldName, $array['message']);
                         // se digitou no formato com barras
                     } else {
                         if (!empty($reg[2])) {
                             list($dia, $mes, $ano) = explode('/', $reg[2]);
                             // se nao for formato brasileiro e norte-americano
                             if (!checkdate($mes, $dia, $ano) && !checkdate($dia, $mes, $ano)) {
                                 self::stackError($errors, $fieldName, $array['message']);
                             }
                             // se digitou no formato ISO
                         } else {
                             if (!empty($reg[3])) {
                                 list($ano, $mes, $dia) = explode('-', $reg[3]);
                                 // se for uma data valida
                                 if (!checkdate($mes, $dia, $ano)) {
                                     self::stackError($errors, $fieldName, $array['message']);
                                 }
                             }
                         }
                     }
                     break;
                     //Verifica se e uma data/hora
                 //Verifica se e uma data/hora
                 case 'requiredDateTime':
                     $val = $obj->{$array}["campo"];
                     if (!preg_match('@^((\\d{2}\\/\\d{2}\\/\\d{4})|(\\d{4}-\\d{2}-\\d{2})) (\\d{2}:\\d{2}(:\\d{2})?)$@', $val, $reg)) {
                         self::stackError($errors, $fieldName, $array['message']);
                         // se digitou no formato com barras
                     } else {
                         if (!empty($reg[2])) {
                             list($dia, $mes, $ano) = explode('/', $reg[2]);
                             // se nao for formato brasileiro e norte-americano
                             if (!checkdate($mes, $dia, $ano) && !checkdate($dia, $mes, $ano)) {
                                 self::stackError($errors, $fieldName, $array['message']);
                             }
                             // se digitou no formato ISO
                         } else {
                             if (!empty($reg[3])) {
                                 list($ano, $mes, $dia) = explode('-', $reg[3]);
                                 // se for uma data valida
                                 if (!checkdate($mes, $dia, $ano)) {
                                     self::stackError($errors, $fieldName, $array['message']);
                                 }
                             }
                         }
                     }
                     break;
                     //Verifica uniquidade
                     // - Alteracao por Hugo: Aqui fiz uma mudanca, porque
                     //   se fosse feita um update, daria erro. por isso, checamos as chaves primarias
                 //Verifica uniquidade
                 // - Alteracao por Hugo: Aqui fiz uma mudanca, porque
                 //   se fosse feita um update, daria erro. por isso, checamos as chaves primarias
                 case 'requiredUnique':
                     $reflection = new ReflectionClass($obj->_getName());
                     $objeto = $reflection->newInstance();
                     $objeto->{$fieldName} = $obj->{$fieldName};
                     $objeto->find();
                     $todas = true;
                     while ($objeto->fetch()) {
                         $pks = $objeto->_getPrimaryKeys();
                         foreach ($pks as $def) {
                             if ($objeto->{$def}['name'] != $obj->{$def}['name']) {
                                 $todas = false;
                                 self::stackError($errors, $fieldName, $array['message']);
                                 break;
                             }
                             if ($todas == false) {
                                 break;
                             }
                         }
                     }
                     unset($objeto, $reflection);
                     break;
                     //Verifica uma funcao
                 //Verifica uma funcao
                 case 'requiredFunction':
                     // se for um array
                     if (is_array($array['message'])) {
                         $result = call_user_func_array($array['message'], array($obj, $fieldName, $obj->{$fieldName}));
                         if ($result !== true) {
                             self::stackError($errors, $fieldName, $result);
                             break;
                         }
                     }
                     if (is_string($array['message'])) {
                         $function = new ReflectionFunction($array['message']);
                         $result = $function->invoke($obj, $fieldName, $obj->{$fieldName});
                         if ($result !== true) {
                             //$errors[] = $result;
                             self::stackError($errors, $fieldName, $result);
                         }
                         unset($function);
                     }
                     break;
                     //Verifica se e CPF
                 //Verifica se e CPF
                 case 'requiredCpf':
                     $res = ValidateCPF::execute($obj->{$array}["campo"]);
                     if ($res === false) {
                         self::stackError($errors, $fieldName, $array['message']);
                     }
                     break;
                     //Verifica se e CNPJ
                 //Verifica se e CNPJ
                 case 'requiredCnpj':
                     $res = ValidateCNPJ::execute($obj->{$array}["campo"]);
                     if ($res === false) {
                         self::stackError($errors, $fieldName, $array['message']);
                     }
                     break;
                 default:
                     return true;
                     break;
             }
         }
     }
     return $errors;
 }
コード例 #14
0
ファイル: Util.php プロジェクト: rrmoura1/Abstergo
 /**
  * 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));
     }
 }
コード例 #15
0
ファイル: KitMs.php プロジェクト: rrmoura1/Abstergo
 /**
  * chama o destrutor pai
  *
  */
 function __destruct()
 {
     parent::__destruct();
 }
コード例 #16
0
ファイル: Model.php プロジェクト: rrmoura1/Abstergo
 /**
  * Realiza os joins informados em uma model
  * 
  * Quando chamar o metodo find, o usuario podera informar que uma
  * classe une com a outra, em varios niveis.
  * 
  * Este metodo auxilia para poder fazer as unioes de forma recursiva,
  * para nao ter limite de unioes de classe.
  * 
  * @author Hugo Ferreira da silva
  * @link http://www.hufersil.com.br
  * @param Lumine_Base $base Arquivo que tera as unioes incluidas
  * @param array $config Configuracoes de preferencia do find
  * @return void
  */
 protected function makeJoins(Lumine_Base $base, array $config)
 {
     // se informou o nome da classe
     if (isset($config['class'])) {
         // importamos a classe
         $base->_getConfiguration()->import($config['class']);
         // reflexao
         $ref = new ReflectionClass($config['class']);
         $target = $ref->newInstance();
         // se indicou um alias
         if (isset($config['alias'])) {
             $target->alias($config['alias']);
         }
         // se tiver join dentro dele
         if (!empty($config['join'])) {
             foreach ($config['join'] as $join) {
                 // faz os join's aninhados
                 $this->makeJoins($target, $join);
             }
         }
         // tipo de uniao
         $joinType = isset($config['type']) ? $config['type'] : 'INNER';
         // se indicou os campos de uniao
         if (isset($config['fieldFrom']) && isset($config['fieldTo'])) {
             // se indicou um extra
             if (isset($config['extra'])) {
                 // unimos as classes
                 $base->join($target, $joinType, $target->_getAlias(), $config['fieldFrom'], $config['fieldTo'], $config['extra'], isset($config['extraArgs']) ? $config['extraArgs'] : '');
                 // se nao indicou extra
             } else {
                 // une as classes sem extra
                 $base->join($target, $joinType, $target->_getAlias(), $config['fieldFrom'], $config['fieldTo']);
             }
             // se nao indicou os campos mas indicou extra
         } else {
             if (isset($config['extra'])) {
                 // une as classes sem indicar os campos, mas indica os argumentos extras
                 $base->join($target, $joinType, $target->_getAlias(), null, null, $config['extra'], isset($config['extraArgs']) ? $config['extraArgs'] : '');
                 // une as classes
             } else {
                 $base->join($target, $joinType, $target->_getAlias());
             }
         }
         // se indicou alias
         if (isset($config['alias'])) {
             // muda o selectAs
             $base->selectAs($target, $config['alias'] . '%s');
         }
     }
 }
コード例 #17
0
ファイル: Parser.php プロジェクト: bladerangel/aplicacao
 /**
  * Faz o parse de nomes de colunas e tabelas de uma string
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param Lumine_Base $obj
  * @param string $str
  * @return string
  */
 public static function parseEntityNames(Lumine_Base $obj, $str)
 {
     // fazer parse de u.nome (alias + . + nome_do_campo) de cada entidade
     $list = $obj->_getObjectPart('_join_list');
     foreach ($list as $ent) {
         $a = $ent->alias();
         $name = $ent->metadata()->getClassname();
         if (!empty($a)) {
             preg_match_all('@\\b' . $a . '\\b\\.(\\w+)\\b@', $str, $reg);
             $total = count($reg[0]);
             for ($i = 0; $i < $total; $i++) {
                 $field = $ent->metadata()->getField($reg[1][$i]);
                 $exp = '@\\b' . $a . '\\b\\.(' . $reg[1][$i] . ')\\b@';
                 $str = preg_replace($exp, $a . '.' . $field['column'], $str);
             }
         }
         preg_match_all('@\\{' . $name . '\\.(\\w+)\\}@', $str, $reg);
         $total = count($reg[0]);
         for ($i = 0; $i < $total; $i++) {
             $field = $ent->metadata()->getField($reg[1][$i]);
             if (!empty($a)) {
                 $str = str_replace($reg[0][$i], $a . '.' . $field['column'], $str);
             } else {
                 $str = str_replace($reg[0][$i], $ent->metadata()->getTablename() . '.' . $field['column'], $str);
             }
         }
     }
     // encontra por {propriedade}
     // quando nao especificado, significa que pertence a mesma entidade
     // chamadora da funcao, por isso nao fazemos loop
     preg_match_all('@\\{(\\w+)\\}@', $str, $reg);
     $total = count($reg[0]);
     for ($i = 0; $i < $total; $i++) {
         $f = $obj->metadata()->getField($reg[1][$i]);
         $a = $obj->alias();
         if ($a == '') {
             $a = $obj->metadata()->getTablename();
         }
         $str = str_replace($reg[0][$i], $a . '.' . $f['column'], $str);
     }
     return $str;
 }
コード例 #18
0
ファイル: Lumine.php プロジェクト: bladerangel/aplicacao
 /**
  * Destroi o objeto
  * 
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br/
  * @param Lumine_Base $obj
  * @return void
  */
 public static function destroy(Lumine_Base &$obj)
 {
     $obj->destroy();
     unset($obj);
 }
コード例 #19
0
ファイル: Base.php プロジェクト: bladerangel/aplicacao
 /**
  * Permite adicionar um JOIN com uma expressao livre.
  * 
  * @param Lumine_Base $obj Objeto que sera unido
  * @param string $expression Expressao que sera utilizada no join
  * @param string $alias Apelido para a classe que esta sendo unida
  * @author Hugo Ferreira da Silva
  * @return Lumine_Base o proprio objeto
  */
 public function joinExpression($obj, $type, $expression, $alias = null)
 {
     $type = trim(strtoupper($type));
     if (!preg_match('@^(LEFT|LEFT OUTER|INNER|RIGHT|RIGHT OUTER|CROSS)$@', $type)) {
         throw new Lumine_Exception('Tipo nao suportado: ' . $type, Lumine_Exception::ERROR);
     }
     // se indicar o alias
     if (!is_null($alias)) {
         $obj->alias($alias);
     } else {
         $alias = $obj->alias();
         if (empty($alias)) {
             $alias = $obj->metadata()->getTablename();
         }
     }
     // pega a lista de join's do objeto que esta sendo unido
     $list = $obj->_getObjectPart('_join_list');
     // reinicia a lista de join's deste objeto
     reset($this->_join_list);
     // argumentos extras
     $args = func_get_args();
     array_splice($args, 0, 4);
     $expression = trim($expression);
     // remove espacos em branco
     try {
         $expression = Lumine_Parser::parsePart($obj, $expression, $args);
         // faz o parser para certificacao que os campos existem certinho
         $expression = Lumine_Parser::parseEntityNames($obj, $expression);
     } catch (Exception $e) {
         try {
             $expression = Lumine_Parser::parsePart($this, $expression, $args);
             // faz o parser para certificacao que os campos existem certinho
             $expression = Lumine_Parser::parseEntityNames($this, $expression);
         } catch (Exception $e) {
             Lumine_Log::warning('Houve um erro na analise da condicao extra');
         }
     }
     // adiciona a expressao
     $this->_join[] = sprintf('%s JOIN %s %s ON %s', $type, $obj->metadata()->getTablename(), $alias, $expression);
     // para cada item na lista do objeto alvo
     foreach ($list as $ent) {
         // indica que pode adicionar
         $add = true;
         // para cada item na lista deste objeto
         foreach ($this->_join_list as $this_ent) {
             // se for a mesma classe e tiver o mesmo alias
             if ($ent->metadata()->getClassname() == $this_ent->metadata()->getClassname() && $ent->alias() == $this_ent->alias()) {
                 // nao pode fazer o join
                 $add = false;
                 break;
             }
         }
         // se nao puder fazer o join
         if (!$add) {
             // pula para o proximo item
             continue;
         }
         // ok pode adicionar
         $this->_join_list[] = $ent;
         $this->_join = array_merge($this->_join, $ent->_getStrJoinList());
         // faz o where
         $where = $ent->_makeWhereFromFields();
         // se teve condicoes
         if (!empty($where)) {
             // inclui neste objeto
             $this->where($where);
         }
     }
     // deixa a lista unica
     $this->_join = array_unique($this->_join);
     return $this;
 }
コード例 #20
0
ファイル: Factory.php プロジェクト: rrmoura1/Abstergo
 /**
  * Construtor da classe
  *
  * @author Hugo Ferreira da Silva
  * @link http://www.hufersil.com.br
  * @param string $package Nome do pacote
  * @param string $tablename nome da tabela que ela representa
  * @return Lumine_Factory
  */
 function __construct($package, $tablename)
 {
     $this->_tablename = $tablename;
     $this->_package = $package;
     parent::__construct();
 }