From 4aaed76c236135634c11f5e763465aa4cd4817e7 Mon Sep 17 00:00:00 2001 From: bjverde Date: Sun, 19 Jul 2020 00:07:38 -0300 Subject: [PATCH] :memo: new version v5.0.0-alpha8 --- .../FormDin5/helpers/FormDinHelper.class.php | 32 +- .../FormDin5/webform/TFormDin.class.php | 8 +- .../webform/TFormDinDaoDbms.class.php | 912 ++++++++++++++++++ .../FormDin5/webform/TFormDinGrid.class.php | 346 +++++-- .../webform/TFormDinGridColumn.class.php | 29 +- .../webform/TFormDinMessage.class.php | 34 + .../webform/TFormDinPdoConnection.class.php | 309 ++++++ .../FormDin5/helpers/FormDinHelperTest.php | 2 +- .../FormDin5/webform/TFormDinDaoDbmsTest.php | 90 ++ .../webform/TFormDinGridColumnTest.php | 91 ++ .../FormDin5/webform/TFormDinGridTest.php | 161 ++++ .../webform/TFormDinPdoConnectionTest.php | 142 +++ FormDin5/tests/lib/widget/mockFormAdianti.php | 10 + .../FormDin5/helpers/FormDinHelper.class.php | 2 +- .../FormDin5/helpers/FormDinHelperTest.php | 2 +- 15 files changed, 2067 insertions(+), 103 deletions(-) create mode 100644 FormDin5/lib/widget/FormDin5/webform/TFormDinDaoDbms.class.php create mode 100644 FormDin5/lib/widget/FormDin5/webform/TFormDinPdoConnection.class.php create mode 100644 FormDin5/tests/lib/widget/FormDin5/webform/TFormDinDaoDbmsTest.php create mode 100644 FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridColumnTest.php create mode 100644 FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridTest.php create mode 100644 FormDin5/tests/lib/widget/FormDin5/webform/TFormDinPdoConnectionTest.php create mode 100644 FormDin5/tests/lib/widget/mockFormAdianti.php diff --git a/FormDin5/lib/widget/FormDin5/helpers/FormDinHelper.class.php b/FormDin5/lib/widget/FormDin5/helpers/FormDinHelper.class.php index a4d187d9..592167bf 100644 --- a/FormDin5/lib/widget/FormDin5/helpers/FormDinHelper.class.php +++ b/FormDin5/lib/widget/FormDin5/helpers/FormDinHelper.class.php @@ -58,15 +58,7 @@ class FormDinHelper { - const FORMDIN_VERSION = '5.0.0-alpha7'; - - const DBMS_ACCESS = 'ACCESS'; - const DBMS_FIREBIRD = 'ibase'; - const DBMS_MYSQL = 'mysql'; - const DBMS_ORACLE = 'oracle'; - const DBMS_POSTGRES = 'pgsql'; - const DBMS_SQLITE = 'sqlite'; - const DBMS_SQLSERVER = 'sqlsrv'; + const FORMDIN_VERSION = '5.0.0-alpha8'; /** * Return FormDin version @@ -111,20 +103,7 @@ public static function setFormDinMinimumVersion($minimumVersion) { throw new DomainException($msg); } } - } - - public static function getListDBMS() - { - $list = array(); - //$list[self::DBMS_ACCESS]='Access'; - //$list[self::DBMS_FIREBIRD]='FIREBIRD'; - $list[self::DBMS_MYSQL]='MariaDB ou MySQL'; - $list[self::DBMS_ORACLE]='Oracle'; - $list[self::DBMS_POSTGRES]='PostgreSQL'; - $list[self::DBMS_SQLITE]='SqLite'; - $list[self::DBMS_SQLSERVER]='SQL Server'; - return $list; - } + } //-------------------------------------------------------------------------------- @@ -243,13 +222,16 @@ public static function issetOrNotZero($variable,$testZero=true) return $result; } - + /** + * @codeCoverageIgnore + */ public static function d( $mixExpression,$strComentario='Debug', $boolExit=FALSE ) { return self::debug($mixExpression,$strComentario,$boolExit); } - /*** + /** + * @codeCoverageIgnore * função para depuração. Exibe o modulo a linha e a variável/objeto solicitado * Retirado do FormDin 4.9.0 * https://github.com/bjverde/formDin/blob/master/base/includes/funcoes.inc diff --git a/FormDin5/lib/widget/FormDin5/webform/TFormDin.class.php b/FormDin5/lib/widget/FormDin5/webform/TFormDin.class.php index 461e24fb..3492beee 100644 --- a/FormDin5/lib/widget/FormDin5/webform/TFormDin.class.php +++ b/FormDin5/lib/widget/FormDin5/webform/TFormDin.class.php @@ -59,6 +59,7 @@ class TFormDin { const TYPE_FIELD = 'feild'; const TYPE_LAYOUT = 'layout'; + const TYPE_HIDDEN = 'hidden'; protected $adiantiObj; private $listFormElements = array(); @@ -251,7 +252,10 @@ public function getAdiantiObj2() $adiantiObj = $this->adiantiObj; call_user_func_array(array($adiantiObj, "addFields"), $fieldsRow); $key = $fieldsRowResult['key']; - } elseif ($element['type']==self::TYPE_LAYOUT){ + }elseif ($element['type']==self::TYPE_HIDDEN){ + $adiantiObj = $this->adiantiObj; + $adiantiObj->addFields( [$element['obj']] ); + }elseif ($element['type']==self::TYPE_LAYOUT){ $adiantiObj = $this->adiantiObj; $adiantiObj->addContent( [$element['obj']] ); //call_user_func_array(array($adiantiObj, "addFields"), $fieldsRow); @@ -620,7 +624,7 @@ public function addHiddenField(string $id $formField = new TFormDinHiddenField($id,$strValue,$boolRequired); $objField = $formField->getAdiantiObj(); //$this->adiantiObj->addFields([$objField]); - $this->addElementFormList($objField,self::TYPE_FIELD); + $this->addElementFormList($objField,self::TYPE_HIDDEN); return $formField; } diff --git a/FormDin5/lib/widget/FormDin5/webform/TFormDinDaoDbms.class.php b/FormDin5/lib/widget/FormDin5/webform/TFormDinDaoDbms.class.php new file mode 100644 index 00000000..ac5d5700 --- /dev/null +++ b/FormDin5/lib/widget/FormDin5/webform/TFormDinDaoDbms.class.php @@ -0,0 +1,912 @@ + + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Formdin. + * + * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ + +class TFormDinDaoDbms +{ + private $connection = null; + private $schema = null; + private $utf8 = null; + private $error = null; + private $conn = null; + private $tableName = null; + private $fields = null; + private $specialChars = array(); + private $charset = null; + private $metadataDir = null; + private $primaryKeys = null; + private $autoincFieldName = null; + private $lastId = null; + private $autoCommit = null; + private $hasActiveTransaction = false; + private $sqlCmd = null; + private $sqlParams = null; + private $cursor = null; + private $eof = null; + + /** + * Classe para pegar metadatos sobre diversos banco de dados. + * + * @param [type] $tableName - 1: nome da tabela + * @param [type] $type - 2: Tipo de banco de dados conforme TFormDinPdoConnection + * @param [type] $user - 3: usuario do banco + * @param [type] $pass - 4: senha do usuario no SGBD + * @param [type] $name - 5: nome da bando de dados ou arquivo + * @param [type] $host - 6: nome ou ip do servidor + * @param [type] $port - 7: porta padrão + * @param [type] $strSchema + */ + public function __construct( $tableName = null + , $type = null + , $user = null + , $pass = null + , $name = null + , $host = null + , $port = null + , $strSchema = null) + { + $this->setTableName( $tableName ); + $this->setType($type); + $this->setSchema( $strSchema ); + + $connection = new TFormDinPdoConnection(); + $connection->setType($type); + $connection->setUser($user); + $connection->setPass($pass); + $connection->setName($name); + $connection->setHost($host); + $connection->setPort($port); + $this->setConnection($connection); + } + + public function getType() + { + return $this->type; + } + /** + * Define o tipo do banco de dados que será acessado. + * Os tipos de banco de dados suportados atualmente estão em + * TFormDinPdoConnection::getListDBMS() + * + * @param string $type + * @return void + */ + public function setType($type) + { + $listType = TFormDinPdoConnection::getListDBMS(); + $inArray = ArrayHelper::has($type,$listType); + if (!$inArray) { + throw new InvalidArgumentException('Type DBMS is not value valid'); + } + $this->type = $type; + } + + public function getConnection() + { + return $this->connection; + } + public function setConnection($connection) + { + if(!($connection instanceof TFormDinPdoConnection)){ + throw new InvalidArgumentException(TFormDinMessage::ERROR_OBJ_TYPE_WRONG); + } + $this->connection = $connection; + } + + /** + * Define o nome do esquema dentro do banco de dados que deverã ser utilizado. + * Este método aplica somente ao banco de dados postgres + * Quando informado será adicionado ao path do banco de dados + * + * @param string $strNewValue + */ + public function setSchema( $strNewValue = null ) + { + $this->schema=$strNewValue; + } + + /** + * Retorna o nome do esquema do banco de dados que será utilizado. Aplica-se somente + * ao banco de dados postgres. + * + * Quando informado será adicionado ao path do banco de dados + * + * @return string + */ + public function getSchema() + { + if( $this->conn ) + { + return $this->getConnSchema(); + } + return $this->schema; + } + + /** + * Adiciona campos da tabela ao array de campos que serão utilizados + * nos binds e nos métodos save, insert e delete da classe + * + * @param string $strFieldName + * @param string $strFieldType + * @param integer $intSize + * @param integer $intPrecision + * @param string $strDefaultValue + * @param boolean $boolNullable + * @param boolean $boolAutoincrement + * @param boolean $boolPrimaryKey + */ + public function addField( $strFieldName, $strFieldType = null, $intSize = null, $intPrecision = null, $strDefaultValue = null, $boolNullable = null, $boolAutoincrement = null, $boolPrimaryKey = null ) + { + $strFieldType =( is_null( $strFieldType ) ? 'varchar':$strFieldType); + $boolAutoincrement =( is_null( $boolAutoincrement ) ? 0 : $boolAutoincrement ); + $boolNullable =( is_null( $boolNullable ) ? 1 : $boolNullable ); + $boolPrimaryKey =( is_null( $boolPrimaryKey ) ? 0 : $boolPrimaryKey ); + $this->fields[ strtoupper( $strFieldName )]=(object)array + ( + 'fieldName' => $strFieldName, + 'fieldType' => $strFieldType, + 'size' => $intSize, + 'precision' => $intPrecision, + 'defaultValue' => $strDefaultValue, + 'nullable' => $boolNullable, + 'autoincrement' => $boolAutoincrement, + 'primaryKey' => $boolPrimaryKey, + 'value' => null + ); + } + + /** + * Retorna o objeto do campo solictado + * Se o campo não existier retorna null + * + * @param string $strFieldName + */ + public function getField( $strFieldName ) + { + $strFieldName=strtoupper( $strFieldName ); + + if ( isset( $this->fields[ $strFieldName ] ) ) + { + return $this->fields[ $strFieldName ]; + } + + return null; + } + + /** + * Retorna o array de objetos dos campos da tabela + * + */ + public function getFields() + { + return $this->fields; + } + /** + * Defina a mensagem de erro + * + * @param string $strError + */ + public function setError( $strError = null ) + { + $this->error=$strError; + } + /** + * Retorna a mensagem de erro atual + * + */ + public function getError() + { + return $this->error; + } + + /** + * Define o nome da tabela do banco de dados que será utizizada nos + * comando insert, save, delete ... + * + * @param string $strNewValue + */ + public function setTableName( $strNewValue = null ) + { + $this->tableName=$strNewValue; + } + /** + * Retorna o nome da tabela que está sendo utilizada nos comandos + * insert, delete, save ... + * + */ + public function getTableName() + { + return $this->tableName; + } + + /** + * Retorna o diretório/pasta onde será armazenada as informações dos campos + * extraídos das tabela + * + * @param string $strNewValue + */ + public function setMetadataDir( $strNewValue = null ) + { + $this->metadataDir=trim( $strNewValue ) . '/'; + $this->metadataDir=preg_replace( '/\/\//', '', $this->metadataDir ) . '/'; + + if ( !is_null( $strNewValue ) && !file_exists( $strNewValue ) ) + { + $oldumask=umask( 0 ); + @mkdir( $strNewValue, 0755, true ); + umask( $oldumask ); + } + } + /** + * Retorna o nome do diretório/pasta onde serão armazendas as informações dos campos + * das tabelas + * + * @return string; + */ + public function getMetadataDir() + { + if ( !is_null( $this->metadataDir ) && file_exists( $this->metadataDir ) ) + { + return preg_replace( '/\/\//', '/', $this->metadataDir . '/' ); + } + + return null; + } + + /** + * Serialize e salva os campos no diretório/pasta de metadados + * + * @return null + */ + public function serializeFields() + { + if ( $this->getMetadataDir() && $this->getTableName() ) + { + $filename = $this->getMetadataDir() . $this->getConnDbType() . '-' . $this->getTableName() . '.ser'; + $data = serialize( $this->getFields() ); + file_put_contents( $filename, $data ); + } + } + + public function loadTablesFromDatabaseSqLite() { + $sql = 'SELECT + \'\' as TABLE_SCHEMA + ,name as TABLE_NAME + ,\'\' as COLUMN_QTD + ,upper(type) as TABLE_TYPE + FROM sqlite_master where type in (\'table\', \'view\')'; + return $sql; + } + + public function loadTablesFromDatabaseMySql() { + $sql = "select vg.TABLE_SCHEMA + ,vg.TABLE_NAME + ,vg.COLUMN_QTD + ,vg.TABLE_TYPE + from + ( + select vt.TABLE_SCHEMA + ,vt.TABLE_NAME + ,count(*) as COLUMN_QTD + ,vt.TABLE_TYPE + from + ( + SELECT t.TABLE_SCHEMA + ,t.TABLE_NAME + ,case when upper(t.TABLE_TYPE) = 'BASE TABLE' then 'TABLE' else upper(t.TABLE_TYPE) end as TABLE_TYPE + FROM INFORMATION_SCHEMA.TABLES as t + ,INFORMATION_SCHEMA.COLUMNS as c + WHERE t.TABLE_NAME = c.TABLE_NAME + and t.TABLE_SCHEMA = c.TABLE_SCHEMA + and (t.TABLE_TYPE = 'BASE TABLE' OR t.TABLE_TYPE = 'VIEW') + and t.TABLE_SCHEMA not in ('sys','phpmyadmin','performance_schema','mysql','information_schema') + ) as vt + group by vt.TABLE_SCHEMA + ,vt.TABLE_NAME + ,vt.TABLE_TYPE + + union + + select vp.TABLE_SCHEMA + ,vp.TABLE_NAME + ,count(*) as COLUMN_QTD + ,'PROCEDURE' as TABLE_TYPE + from + ( + select p.SPECIFIC_SCHEMA as TABLE_SCHEMA + ,p.SPECIFIC_NAME as TABLE_NAME + ,p.routine_type as TABLE_TYPE + from information_schema.routines as r + left join information_schema.parameters as p + on p.specific_schema = r.routine_schema + and p.specific_name = r.specific_name + where r.routine_schema not in ('sys','phpmyadmin','information_schema','mysql', 'performance_schema') + and p.routine_type = 'PROCEDURE' + ) as vp + group by vp.TABLE_SCHEMA + ,vp.TABLE_NAME + ,vp.TABLE_TYPE + ) as vg + order by + vg.TABLE_SCHEMA + ,vg.TABLE_TYPE + ,vg.TABLE_NAME"; + return $sql; + } + + public function loadTablesFromDatabaseSqlServer() { + $sql = "select + TABLE_SCHEMA + ,TABLE_NAME + ,COLUMN_QTD + ,TABLE_TYPE + from ( + SELECT qtd.TABLE_SCHEMA + ,qtd.TABLE_NAME + ,qtd.COLUMN_QTD + ,case ty.TABLE_TYPE WHEN 'BASE TABLE' THEN 'TABLE' ELSE ty.TABLE_TYPE end as TABLE_TYPE + FROM + (SELECT TABLE_SCHEMA + ,TABLE_NAME + ,COUNT(TABLE_NAME) COLUMN_QTD + FROM INFORMATION_SCHEMA.COLUMNS c + where c.TABLE_SCHEMA <> 'METADADOS' + group by TABLE_SCHEMA, TABLE_NAME + ) as qtd + ,(SELECT TABLE_SCHEMA + , TABLE_NAME + , TABLE_TYPE + FROM INFORMATION_SCHEMA.TABLES i + where I.TABLE_SCHEMA <> 'METADADOS' + ) as ty + where qtd.TABLE_SCHEMA = ty.TABLE_SCHEMA + and qtd.TABLE_NAME = ty.TABLE_NAME + + UNION + + SELECT Schema_name(schema_id) AS TABLE_SCHEMA, + SO.NAME AS TABLE_NAME, + count(*) AS COLUMN_QTD, + CASE SO.type_desc + WHEN 'SQL_STORED_PROCEDURE' THEN 'PROCEDURE' + ELSE 'FUNCTION' + END AS TABLE_TYPE + FROM sys.objects AS SO + INNER JOIN sys.parameters AS P + ON SO.object_id = P.object_id + WHERE SO.object_id IN (SELECT object_id + FROM sys.objects + WHERE type IN ( 'P', 'FN' )) + group by schema_id, SO.NAME, SO.type_desc + ) as res + order by res.TABLE_SCHEMA + , res.TABLE_TYPE + , res.TABLE_NAME"; + return $sql; + } + + public function loadTablesFromDatabasePostGres() { + $sql = "SELECT qtd.TABLE_SCHEMA + ,qtd.TABLE_NAME + ,qtd.COLUMN_QTD + ,ty.TABLE_TYPE + ,case ty.TABLE_TYPE WHEN 'BASE TABLE' THEN 'TABLE' ELSE ty.TABLE_TYPE end as TABLE_TYPE + FROM + (SELECT TABLE_SCHEMA + ,TABLE_NAME + ,COUNT(TABLE_NAME) COLUMN_QTD + FROM INFORMATION_SCHEMA.COLUMNS c + where c.TABLE_SCHEMA <> 'pg_catalog' and c.TABLE_SCHEMA <> 'information_schema' + group by TABLE_SCHEMA, TABLE_NAME + ) as qtd + ,(SELECT TABLE_SCHEMA + , TABLE_NAME + , TABLE_TYPE + FROM INFORMATION_SCHEMA.TABLES i + where I.TABLE_SCHEMA <> 'pg_catalog' and I.TABLE_SCHEMA <> 'information_schema' + ) as ty + where qtd.TABLE_SCHEMA = ty.TABLE_SCHEMA + and qtd.TABLE_NAME = ty.TABLE_NAME + order by qtd.TABLE_SCHEMA, qtd.TABLE_NAME"; + return $sql; + } + + /** + * @codeCoverageIgnore + * Retorna a lista de tabela de banco de dados + * + * @return void + */ + public function loadTablesFromDatabase() { + $DbType = $this->getType(); + $sql = null; + switch( $DbType ) { + case TFormDinPdoConnection::DBMS_SQLITE: + $sql = $this->loadTablesFromDatabaseSqLite(); + break; + //-------------------------------------------------------------------------------- + case TFormDinPdoConnection::DBMS_MYSQL: + $sql = $this->loadTablesFromDatabaseMySql(); + break; + //-------------------------------------------------------------------------------- + case TFormDinPdoConnection::DBMS_SQLSERVER: + $sql = $this->loadTablesFromDatabaseSqlServer(); + break; + //-------------------------------------------------------------------------------- + case TFormDinPdoConnection::DBMS_POSTGRES: + $sql = $this->loadTablesFromDatabasePostGres(); + break; + //-------------------------------------------------------------------------------- + default: + throw new DomainException('Database '.$DbType.' not implemented ! TDAO->loadTablesFromDatabase. Contribute to the project https://github.com/bjverde/sysgen !'); + } + $result = $this->getConnection()->executeSql($sql); + return $result; + } + + private function getMsSqlShema() { + $result = ''; + if($this->getSchema()){ + $result = " AND upper(c.TABLE_SCHEMA) = upper('".$this->getSchema()."') "; + } + return $result; + } + + public function getSqlToFieldsFromOneStoredProcedureMySQL() { + $sql="select + p.parameter_name as COLUMN_NAME + ,'FALSE' as REQUIRED + ,r.routine_type AS DATA_TYPE + ,p.character_maximum_length as CHAR_MAX + ,p.numeric_precision as NUM_LENGTH + ,p.numeric_scale as NUM_SCALE + ,r.ROUTINE_COMMENT as COLUMN_COMMENT + ,r.specific_name as TABLE_NAME + ,r.routine_schema as TABLE_SCHEMA + ,p.ordinal_position + ,case when p.parameter_mode is null and p.data_type is not null + then 'RETURN' + else parameter_mode end as parameter_mode + from information_schema.routines r + left join information_schema.parameters p + on p.specific_schema = r.routine_schema + and p.specific_name = r.specific_name + where r.routine_schema not in ('sys', 'information_schema','mysql', 'performance_schema') + and upper(r.specific_name) = upper('".$this->getTableName()."') + and upper(r.routine_schema) = upper('".$this->getSchema()."') + order by r.routine_schema, + r.specific_name, + p.ordinal_position"; + return $sql; + } + + public function getSqlToFieldsFromOneStoredProcedureSqlServer() { + $name = $this->getTableName(); + $shema = $this->getSchema(); + $sql="SELECT REPLACE(P.NAME,'@','') AS COLUMN_NAME + ,'FALSE' AS REQUIRED + ,Type_name(P.user_type_id) AS DATA_TYPE + ,P.max_length AS CHAR_MAX + ,null AS NUM_LENGTH + ,null AS NUM_SCALE + ,null AS COLUMN_COMMENT + ,null AS COLUMN_COMMENT + ,null AS KEY_TYPE + ,null AS REFERENCED_TABLE_NAME + ,null AS REFERENCED_COLUMN_NAME + ,Schema_name(schema_id) AS TABLE_SCHEMA + ,SO.NAME AS table_name + FROM sys.objects AS SO + INNER JOIN sys.parameters AS P + ON SO.object_id = P.object_id + WHERE SO.object_id IN (SELECT object_id + FROM sys.objects + WHERE type IN ( 'P')) + AND upper(SO.NAME) = upper('".$name."') + AND upper(Schema_name(schema_id)) = upper('".$shema."') + "; + return $sql; + } + + public function getSqlToFieldsOneStoredProcedureFromDatabase() { + //$DbType = $this->getConnDbType(); + $DbType = $this->getType(); + $sql = null; + $params = null; + $data = null; + + // ler os campos do banco de dados + if ( $DbType == TFormDinPdoConnection::DBMS_MYSQL ){ + $sql = $this->getSqlToFieldsFromOneStoredProcedureMySQL(); + } + else if( $DbType == TFormDinPdoConnection::DBMS_SQLSERVER ) { + $sql = $this->getSqlToFieldsFromOneStoredProcedureSqlServer(); + $params=array($this->getTableName()); + } + $result = array(); + $result['sql'] = $sql; + $result['params'] = $params; + $result['data'] = $data; + return $result; + } + + /** + * Recupera as informações dos parametros de uma Storage Procedeure diretamente do banco de dados + * @return null + */ + public function loadFieldsOneStoredProcedureFromDatabase() { + $DbType = $this->getType(); + if ( !$this->getTableName() ) { + throw new InvalidArgumentException(TFormDinMessage::ERROR_OBJ_STORED_PROC); + } + $result = $this->getSqlToFieldsOneStoredProcedureFromDatabase(); + $sql = $result['sql']; + switch( $DbType ) { + case TFormDinPdoConnection::DBMS_MYSQL: + case TFormDinPdoConnection::DBMS_SQLSERVER: + $result = $this->getConnection()->executeSql($sql); + break; + //-------------------------------------------------------------------------------- + default: + throw new DomainException('Database '.$DbType.' not implemented ! '.TFormDinMessage::MSG_CONTRIB_PROJECT); + } + return $result; + } + + public function getSqlToFieldsFromDatabaseMySQL() { + // http://dev.mysql.com/doc/refman/5.0/en/tables-table.html + $sql="SELECT c.column_name COLUMN_NAME + , case when upper(c.IS_NULLABLE) = 'NO' then 'TRUE' else 'FALSE' end REQUIRED + , c.data_type DATA_TYPE + , c.character_maximum_length CHAR_MAX + , c.numeric_precision NUM_LENGTH + , c.numeric_scale NUM_SCALE + , c.COLUMN_COMMENT + , case when upper(c.COLUMN_KEY) = 'PRI' then 'PK' when ( upper(c.COLUMN_KEY) = 'MUL' AND k.REFERENCED_TABLE_NAME is not null ) then 'FOREIGN KEY' else 0 end KEY_TYPE + , case when lower(c.EXTRA) = 'auto_increment' then 1 else 0 end AUTOINCREMENT + , c.COLUMN_DEFAULT + , k.REFERENCED_TABLE_NAME + , k.REFERENCED_COLUMN_NAME + , c.TABLE_SCHEMA + , c.table_name + , c.TABLE_CATALOG + from information_schema.columns as c + left join information_schema.KEY_COLUMN_USAGE as k + on c.TABLE_SCHEMA = k.TABLE_SCHEMA + and c.table_name = k.table_name + and c.column_name = k.column_name + WHERE upper(c.table_name) = upper('".$this->getTableName()."') + order by c.table_name + ,c.ordinal_position"; + return $sql; + } + + public function getSqlToFieldsFromDatabaseSqlServer() { + $sql="SELECT c.column_name as COLUMN_NAME + ,case c.IS_NULLABLE WHEN 'YES' THEN 'FALSE' ELSE 'TRUE' end as REQUIRED + ,c.DATA_TYPE + ,c.CHARACTER_MAXIMUM_LENGTH as CHAR_MAX + ,c.NUMERIC_PRECISION as NUM_LENGTH + ,c.NUMERIC_SCALE as NUM_SCALE + ,prop.value AS COLUMN_COMMENT + ,fk2.CONSTRAINT_TYPE as KEY_TYPE + ,fk2.REFERENCED_TABLE_NAME + ,fk2.REFERENCED_COLUMN_NAME + ,c.TABLE_SCHEMA + ,c.table_name + ,c.TABLE_CATALOG + from INFORMATION_SCHEMA.COLUMNS c + join sys.columns AS sc on sc.object_id = object_id(c.TABLE_SCHEMA + '.' + c.TABLE_NAME) AND sc.NAME = c.COLUMN_NAME + LEFT JOIN sys.extended_properties prop ON prop.major_id = sc.object_id AND prop.minor_id = sc.column_id AND prop.NAME = 'MS_Description' + LEFT JOIN ( + SELECT CT.TABLE_CATALOG + , CT.TABLE_SCHEMA + , CT.TABLE_NAME + , CT.COLUMN_NAME + , CT.CONSTRAINT_TYPE + , FK.REFERENCED_TABLE_NAME + , FK.REFERENCED_COLUMN_NAME + FROM ( + SELECT kcu.TABLE_CATALOG + , kcu.TABLE_SCHEMA + , kcu.TABLE_NAME + , kcu.COLUMN_NAME + , tc.CONSTRAINT_TYPE + , kcu.CONSTRAINT_NAME + FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu + ,INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc + where kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME + ) as CT + + LEFT JOIN ( + SELECT + KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME + ,KCU1.TABLE_NAME AS FK_TABLE_NAME + ,KCU1.COLUMN_NAME AS FK_COLUMN_NAME + ,KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME + ,KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME + FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC + + INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 + ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG + AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA + AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME + + INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 + ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG + AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA + AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME + AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION + ) as FK + ON CT.CONSTRAINT_NAME = FK.FK_CONSTRAINT_NAME + AND CT.TABLE_NAME = FK.FK_TABLE_NAME + AND CT.COLUMN_NAME = FK.FK_COLUMN_NAME + ) as FK2 + on c.TABLE_SCHEMA = FK2.TABLE_SCHEMA + and c.TABLE_NAME = Fk2.TABLE_NAME + and c.COLUMN_NAME = fk2.COLUMN_NAME + WHERE upper(c.table_name) = upper('".$this->getTableName()."')".$this->getMsSqlShema()." + ORDER by c.TABLE_SCHEMA + ,c.TABLE_NAME + ,c.ORDINAL_POSITION"; + return $sql; + } + + public function getSqlToFieldsFromDatabasePostGres() { + $sql ="SELECT c.column_name as COLUMN_NAME + , case c.IS_NULLABLE WHEN 'YES' THEN 'FALSE' ELSE 'TRUE' end as REQUIRED + , data_type as DATA_TYPE + , character_maximum_length CHAR_MAX + , coalesce(numeric_precision, datetime_precision) as NUM_LENGTH + , numeric_scale as NUM_SCALE + , des.description COLUMN_COMMENT + , refe.KEY_TYPE + , column_default COLUMN_DEFAULT + , refe.REFERENCED_TABLE_NAME + , refe.REFERENCED_COLUMN_NAME + , position('nextval(' in column_default)=1 as AUTOINCREMENT + , c.TABLE_SCHEMA + , c.table_name + , c.TABLE_CATALOG + FROM information_schema.columns as c + left join (SELECT st.schemaname as table_schema + , st.relname as table_name + , pgd.objsubid + , pgd.description + FROM pg_catalog.pg_statio_all_tables as st + inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid) + ) as des + on (des.objsubid=c.ordinal_position and des.table_schema = c.table_schema and des.table_name = c.table_name) + left join (SELECT + tc.table_schema + , tc.table_name + , kcu.column_name + , tc.constraint_name + , tc.constraint_type + , case when upper(tc.constraint_type) = 'PRIMARY KEY' THEN 'PK' + when upper(tc.constraint_type) = 'FOREIGN KEY' THEN 'FOREIGN KEY' + ELSE tc.constraint_type + END as KEY_TYPE + , ccu.table_schema AS REFERENCED_TABLE_SCHEMA + , ccu.table_name AS REFERENCED_TABLE_NAME + , ccu.column_name AS REFERENCED_COLUMN_NAME + FROM + information_schema.table_constraints AS tc + JOIN information_schema.key_column_usage AS kcu + ON tc.constraint_name = kcu.constraint_name + JOIN information_schema.constraint_column_usage AS ccu + ON ccu.constraint_name = tc.constraint_name + WHERE constraint_type in ('FOREIGN KEY' ,'PRIMARY KEY') + ) as refe + on (refe.table_schema = c.table_schema and refe.table_name = c.table_name and refe.column_name = c.column_name) + WHERE upper(c.table_name) =upper('".$this->getTableName()."')".$this->getMsSqlShema()." + ORDER BY c.TABLE_SCHEMA + ,c.table_name + ,c.ordinal_position"; + return $sql; + } + + public function getSqlToFieldsFromDatabase() { + //$DbType = $this->getConnDbType(); + $DbType = $this->getType(); + $sql = null; + $params = null; + $data = null; + + // ler os campos do banco de dados + if ( $DbType == TFormDinPdoConnection::DBMS_MYSQL ){ + $sql = $this->getSqlToFieldsFromDatabaseMySQL(); + $params=null; + } + else if( $DbType == TFormDinPdoConnection::DBMS_SQLSERVER ) { + $sql = $this->getSqlToFieldsFromDatabaseSqlServer(); + $params=array($this->getTableName()); + } + else if( $DbType == TFormDinPdoConnection::DBMS_ORACLE ) { + $sql="select a.column_name COLUMN_NAME + , a.data_type DATA_TYPE + , data_default as COLUMN_DEFAULT + , 0 AUTOINCREMENT + , decode(nullable,'Y',1,0) as REQUIRED + , a.data_length CHAR_MAX + , a.data_precision NUM_LENGTH + , a.data_scale NUM_SCALE + from all_tab_columns a + where upper(a.table_name) = upper(:0)"; + + $params=array($this->getTableName()); + } + else if( $DbType == TFormDinPdoConnection::DBMS_POSTGRES ) { + $schema=( is_null( $this->getSchema() ) ? 'public' : $this->getSchema()); + $sql = $this->getSqlToFieldsFromDatabasePostGres(); + $params=array( $schema ,$this->getTableName() ); + } + else if( $DbType == TFormDinPdoConnection::DBMS_FIREBIRD ) { + $sql='SELECT + RDB$RELATION_FIELDS.RDB$FIELD_NAME COLUMN_NAME, + \'\' as COLUMN_DEFAULT, + 0 AUTOINCREMENT, + 0 REQUIRED, + RDB$TYPES.RDB$TYPE_NAME DATA_TYPE, + RDB$FIELDS.RDB$CHARACTER_LENGTH CHAR_MAX, + RDB$FIELDS.RDB$FIELD_PRECISION NUM_LENGTH, + RDB$FIELDS.RDB$FIELD_SCALE NUM_SCALE + FROM RDB$RELATIONS + INNER JOIN RDB$RELATION_FIELDS ON RDB$RELATIONS.RDB$RELATION_NAME = RDB$RELATION_FIELDS.RDB$RELATION_NAME + LEFT JOIN RDB$FIELDS ON RDB$RELATION_FIELDS.RDB$FIELD_SOURCE = RDB$FIELDS.RDB$FIELD_NAME + LEFT JOIN RDB$TYPES ON RDB$FIELDS.RDB$FIELD_TYPE = RDB$TYPES.RDB$TYPE + LEFT JOIN RDB$FIELD_DIMENSIONS on RDB$FIELD_DIMENSIONS.RDB$FIELD_NAME = RDB$FIELDS.RDB$FIELD_NAME + WHERE UPPER(RDB$RELATIONS.RDB$RELATION_NAME) = upper(?) + AND RDB$RELATIONS.RDB$SYSTEM_FLAG = 0 + AND RDB$TYPES.RDB$FIELD_NAME=\'RDB$FIELD_TYPE\' + ORDER BY RDB$RELATION_FIELDS.RDB$FIELD_POSITION'; + + $params=array($this->getTableName()); + } + else if( $DbType == TFormDinPdoConnection::DBMS_SQLITE) { + $stmt = $this->getConn()->query( "PRAGMA table_info(".$this->getTableName().")"); + $res = $stmt->fetchAll(); + $data = null; + $sql = null; + foreach($res as $rownum => $row) + { + $data[$rownum]['COLUMN_NAME'] = $row['NAME']; + $data[$rownum]['COLUMN_DEFAULT']= $row['DFLT_VALUE']; + $data[$rownum]['AUTOINCREMENT'] = $row['PK']; + $data[$rownum]['REQUIRED'] = ( $row['NOTNULL'] == 0 ? 'FALSE' : 'TRUE' ); + $data[$rownum]['DATA_TYPE'] = strtoupper($row['TYPE']); + $data[$rownum]['CHAR_MAX'] = null; + $data[$rownum]['NUM_LENGTH']= 0; + $data[$rownum]['NUM_SCALE'] = 0; + $data[$rownum]['PRIMARYKEY'] = $row['PK']; + if( preg_match('/\(/',$row['TYPE']) == 1 ) + { + $aTemp = explode('(',$row['TYPE']); + $data[$rownum]['DATA_TYPE'] = $aTemp[0]; + $type= substr($row['TYPE'],strpos($row['TYPE'],'(')); + $type = preg_replace('/(\(|\))/','',$type); + @list($length,$precision) = explode(',',$type); + + if( preg_match('/varchar/i',$aTemp[0]==1) ) { + $data[$rownum]['DATA_LENGTH'] = $length; + } + else { + $data[$rownum]['CHAR_MAX'] = 0; + $data[$rownum]['NUM_LENGTH'] = $length; + $data[$rownum]['NUM_SCALE'] = $precision; + } + } + } + } + $result = array(); + $result['sql'] = $sql; + $result['params'] = $params; + $result['data'] = $data; + + return $result; + } + + /** + * Recupera as informações dos campos da tabela defida na classe diretamente do banco de dados + * @return null + */ + public function loadFieldsOneTableFromDatabase() { + $DbType = $this->getType(); + if ( !$this->getTableName() ) { + throw new InvalidArgumentException(TFormDinMessage::ERROR_OBJ_TABLE); + } + $result = $this->getSqlToFieldsFromDatabase(); + $sql = $result['sql']; + $data = $result['data']; + switch( $DbType ) { + case TFormDinPdoConnection::DBMS_SQLITE: + $result = ArrayHelper::convertArrayPdo2FormDin($data); + break; + //-------------------------------------------------------------------------------- + case TFormDinPdoConnection::DBMS_MYSQL: + case TFormDinPdoConnection::DBMS_SQLSERVER: + case TFormDinPdoConnection::DBMS_POSTGRES: + $result = $this->getConnection()->executeSql($sql); + break; + //-------------------------------------------------------------------------------- + default: + throw new DomainException('Database '.$DbType.' not implemented ! '.TFormDinMessage::MSG_CONTRIB_PROJECT); + } + return $result; + } + + /** + * Recupera as informações dos campos da tabela defida na classe diretamente do banco de dados + * @return null + */ + public function loadFieldsFromDatabase() { + if ( !$this->getTableName() ) { + return null; + } + $result = $this->getSqlToFieldsFromDatabase(); + $sql = $result['sql']; + $params = $result['params']; + $data = $result['data']; + + if ( !is_null( $sql ) ) { + $data = $this->query( $sql, $params ); + } + + if ( is_array( $data ) ){ + foreach( $data as $k => $row ) { + $boolPrimaryKey = ArrayHelper::get($row,'PRIMARYKEY'); + $this->addField( trim( $row[ 'COLUMN_NAME' ] ) + , trim( strtolower($row[ 'DATA_TYPE' ]) ) + , ( (int) $row[ 'NUM_LENGTH' ] > 0 ? $row[ 'NUM_LENGTH' ] : $row[ 'CHAR_MAX' ] ) + , $row[ 'NUM_SCALE' ] + , $row[ 'COLUMN_DEFAULT' ] + , $row[ 'REQUIRED' ] + , $row[ 'AUTOINCREMENT' ] + , $boolPrimaryKey); + } + if ( is_array( $this->getfields() ) ) { + $this->serializeFields(); + } + } + } + +} +?> diff --git a/FormDin5/lib/widget/FormDin5/webform/TFormDinGrid.class.php b/FormDin5/lib/widget/FormDin5/webform/TFormDinGrid.class.php index 15e5c893..75d4c044 100644 --- a/FormDin5/lib/widget/FormDin5/webform/TFormDinGrid.class.php +++ b/FormDin5/lib/widget/FormDin5/webform/TFormDinGrid.class.php @@ -40,58 +40,154 @@ * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ +/** + * Classe para criação de Grid para apresentar os dados + * ------------------------------------------------------------------------ + * Esse é o FormDin 5, que é uma reconstrução do FormDin 4 Sobre o Adianti 7.X + * os parâmetros do metodos foram marcados com: + * + * NOT_IMPLEMENTED = Parâmetro não implementados, talvez funcione em + * verões futuras do FormDin. Não vai fazer nada + * DEPRECATED = Parâmetro que não vai funcionar no Adianti e foi mantido + * para diminuir o impacto sobre as migrações. Vai gerar um Warning + * FORMDIN5 = Parâmetro novo disponivel apenas na nova versão + * ------------------------------------------------------------------------ + * + * @author Reinaldo A. Barrêto Junior + */ class TFormDinGrid { - protected $adiantiObj; + + const TYPE_SIMPLE = 'simple'; + const TYPE_CHECKOUT = 'checkout'; + + private $adiantiObj; + private $panelGroupGrid; + private $objForm; + private $listColumn = array(); protected $action; protected $idGrid; protected $title; protected $key; - - /** - * Grid Padronizado em BoorStrap - * Reconstruido FormDin 4 Sobre o Adianti 7 - * - * @param $action Callback to be executed - * @param string $strName - 1: ID do Grid - * @param string $strTitle - 2: Titulo do Grid - * @param string $strKeyField - 3: Id da chave primaria - * - * @return BootstrapFormBuilder - */ + + protected $data; + /** - * Grid Padronizado em BoorStrap + * Classe para criação de grides, Padronizado em BoorStrap * Reconstruido FormDin 4 Sobre o Adianti 7 + * + * Parametros do evento onDrawHeaderCell + * 1) $th - objeto TElement + * 2) $objColumn - objeto TGridColum + * 3) $objHeader - objeto TElement * - * @param [type] $action - 1: função callback $this na classe origem - * @param string $idGrid - 2: ID do Grid recebe __CLASS__ - * @param string $title - 3: Titulo do Grid - * @param string $key - 4: Id da chave primaria - * @param boolean $boolDataTable - * @param boolean $boolDefaultClick - */ - public function __construct($action - ,string $idGrid - ,string $title - ,string $key - ,$boolDataTable = false - ,$boolDefaultClick = true - ) + * Parametros do envento onDrawRow + * 1) $row - objeto TGridRow + * 2) $rowNum - número da linha corrente + * 3) $aData - o array de dados da linha ex: $res[''][n] + * + * Parametros do envento onDrawCell + * 1) $rowNum - número da linha corrente + * 2) $cell - objeto TTableCell + * 3) $objColumn - objeto TGrideColum + * 4) $aData - o array de dados da linha ex: $res[''][n] + * 5) $edit - o objeto campo quando a coluna for um campo de edição + * ex: function ondrawCell($rowNum=null,$cell=null,$objColumn=null,$aData=null,$edit=null) + * + * Parametros do evento onDrawActionButton + * 1) $rowNum - número da linha corrente + * 2) $button - objeto TButton + * 3) $objColumn - objeto TGrideColum + * 4) $aData - o array de dados da linha ex: $res[''][n] + * Ex: function tratarBotoes($rowNum,$button,$objColumn,$aData); + * + * Parametros do evento onGetAutocompleteParameters + * 1) $ac - classe TAutocomplete + * 2) $aData - o array de dados da linha ex: $res[''][n] + * 3) $rowNum - número da linha corrente + * 3) $cell - objeto TTableCell + * 4) $objColumn - objeto TGrideColum + * + * @param object $objForm - 1: FORMDIN5 Objeto do Adianti da classe do Form, é só informar $this + * @param string $strName - 2: ID da grid + * @param string $strTitle - 3: Titulo da grip + * @param array $mixData - 4: Array de dados. Pode ser form formato Adianti, FormDin ou PDO + * @param mixed $strHeight - 5: Altura + * @param mixed $strWidth - 6: NOT_IMPLEMENTED Largura + * @param mixed $strKeyField - 7: NOT_IMPLEMENTED Chave primaria + * @param array $mixUpdateFields - 8: NOT_IMPLEMENTED Campos do form origem que serão atualizados ao selecionar o item desejado. Separados por virgulas seguindo o padrão | , | + * @param mixed $intMaxRows - 9: NOT_IMPLEMENTED Qtd Max de linhas + * @param mixed $strRequestUrl -10: NOT_IMPLEMENTED Url request do form + * @param mixed $strOnDrawCell -11: NOT_IMPLEMENTED + * @param mixed $strOnDrawRow -13: NOT_IMPLEMENTED + * @param mixed $strOnDrawHeaderCell -14: NOT_IMPLEMENTED + * @param mixed $strOnDrawActionButton-15: NOT_IMPLEMENTED + * @return TGrid + */ + public function __construct( $objForm + , string $strName + , string $strTitle = null + , $mixData = null + , $strHeight = null + , $strWidth = null + , string $strKeyField = null + , $mixUpdateFields = null + , $intMaxRows = null + , $strRequestUrl = null + , $strOnDrawCell = null + , $strOnDrawRow = null + , $strOnDrawHeaderCell = null + , $strOnDrawActionButton = null ) + { + if( !is_object($objForm) ){ + $track = debug_backtrace(); + $msg = 'A classe GRID MUDOU! o primeiro parametro agora recebe $this! o Restante está igual ;-)'; + ValidateHelper::migrarMensage($msg + ,ValidateHelper::ERROR + ,ValidateHelper::MSG_CHANGE + ,$track[0]['class'] + ,$track[0]['function'] + ,$track[0]['line'] + ,$track[0]['file'] + ); + }else{ + $this->setObjForm($objForm); + + $bootgrid = new BootstrapDatagridWrapper(new TDataGrid); + $bootgrid->width = '100%'; + $this->setAdiantiObj($bootgrid); + $this->setId($strName); + $this->setHeight($strHeight); + //$this->setWidth($strWidth); + + $panel = new TPanelGroup($strTitle); + $this->setPanelGroupGrid($panel); + } + } + + + public function setObjForm($objForm) { - $this->adiantiObj = new BootstrapDatagridWrapper(new TDataGrid); - $this->adiantiObj->width = '100%'; - if($boolDataTable){ - $this->adiantiObj->datatable = 'true'; + if( empty($objForm) ){ + throw new InvalidArgumentException(TFormDinMessage::ERROR_FD5_OBJ_ADI); } - if(!$boolDefaultClick){ - $this->adiantiObj->disableDefaultClick(); + if( !is_object($objForm) ){ + throw new InvalidArgumentException(TFormDinMessage::ERROR_FD5_OBJ_ADI); + } + return $this->objForm=$objForm; + } + public function getObjForm(){ + return $this->objForm; + } + + public function setAdiantiObj( $bootgrid ) + { + if( !($bootgrid instanceof BootstrapDatagridWrapper) ){ + throw new InvalidArgumentException(TFormDinMessage::ERROR_FD5_OBJ_BOOTGRID); } - $this->setAction($action); - $this->setIdGrid($idGrid); - $this->setTitle($title); - $this->setKey($key); + $this->adiantiObj = $bootgrid; } public function getAdiantiObj(){ @@ -101,25 +197,80 @@ public function getAdiantiObj(){ return $this->adiantiObj; } + public function getId(){ + return $this->idGrid; + } + + public function setId(string $idGrid){ + if(empty($idGrid)){ + throw new InvalidArgumentException(TFormDinMessage::ERROR_EMPTY_INPUT); + } + $this->getAdiantiObj()->setId($idGrid); + $this->idGrid = $idGrid; + } + + public function getHeight(){ + return $this->getAdiantiObj()->height; + } + + public function setHeight($Height){ + $this->getAdiantiObj()->setHeight($Height); + } + + + public function getWidth() + { + //return $this->getAdiantiObj()->getWidth(); + return null; + } + public function setWidth( $width ) + { + //$this->getAdiantiObj()->setWidth($width); + } + + public function setData( $data ) + { + $this->data = $data; + } + public function getData() + { + return $this->data; + } + /** - * Coluna do Grid Padronizado em BoorStrap - * Reconstruido FormDin 4 Sobre o Adianti 7.1 - * - * @param string $name = Name of the column in the database - * @param string $label = Text label that will be shown in the header - * @param string $align = Column align (left, center, right) - * @param string $width = Column Width (pixels) - * @return TDataGridColumn + * Adciona um Objeto Adianti na lista de objetos que compeen o Formulário. + * + * @param string $type - 1: Type column constante + * @param string $idcolumn- 2: idcolumn + * @param string $label - 3: Label da coluna + * @param string $width - 4: + * @param string $align - 5: + * @return void */ - public function addColumn(string $name - , string $label - , string $align='left' - , string $width = NULL){ - $action = $this->getAction(); - $formDinGridColumn = new TFormDinGridColumn($action, $name, $label,$align,$width); - $column = $formDinGridColumn->getAdiantiObj(); - $this->adiantiObj->addColumn($column); - return $column; + public function addElementColumnList($type = self::TYPE_SIMPLE + , string $idcolumn + , string $label + , string $width = NULL + , string $align = 'left' + ) + { + $element = array(); + $element['type']=$type; + $element['idcolumn']=$idcolumn; + $element['label']=$label; + $element['align']=$align; + $element['width']=$width; + $this->listColumn[]=$element; + } + + public function show() + { + $this->getAdiantiObj()->createModel(); + if( !empty($this->getData()) ){ + $this->getAdiantiObj()->addItems( $this->getData() ); + } + $this->getPanelGroupGrid()->add($this->getAdiantiObj())->style = 'overflow-x:auto'; + return $this->getAdiantiObj(); } public function getAction(){ @@ -130,19 +281,14 @@ public function setAction($action){ $this->action = $action; } - public function getIdGrid(){ - return $this->idGrid; - } - public function setIdGrid(string $idGrid){ - $this->idGrid = $idGrid; - } public function getTitle(){ return $this->title; } public function setTitle(string $title){ + $this->getPanelGroupGrid()->setTitle($title); $this->title = $title; } @@ -153,4 +299,82 @@ public function getKey(){ public function setKey(string $key){ $this->key = $key; } + + public function getPanelGroupGrid(){ + return $this->panelGroupGrid; + } + + public function setPanelGroupGrid($panel){ + if( !($panel instanceof TPanelGroup) ){ + throw new InvalidArgumentException(TFormDinMessage::ERROR_OBJ_TYPE_WRONG.' use TPanelGroup'); + } + $this->panelGroupGrid = $panel; + } + + public function getFooter(){ + return $this->getPanelGroupGrid()->getFooter(); + } + + public function addFooter($footer){ + return $this->getPanelGroupGrid()->addFooter($footer); + } + + public function enableDataTable(){ + $this->getAdiantiObj()->datatable = 'true'; + } + + public function disableDataTable(){ + $this->getAdiantiObj()->datatable = 'false'; + } + + /** + * Coluna do Grid Padronizado em BoorStrap + * Reconstruido FormDin 4 Sobre o Adianti 7.1 + * + * @param string $name - 1: Name of the column in the database + * @param string $label - 2: Text label that will be shown in the header + * @param string $width - 3: Column Width (pixels) + * @param string $align - 4: Column align (left|right|center|justify) + * @return TDataGridColumn + */ + public function addColumn(string $name + , string $label + , string $width = NULL + , string $align='left' ) + { + $formDinGridColumn = new TFormDinGridColumn( $name,$label,$width,$align); + $column = $formDinGridColumn->getAdiantiObj(); + $this->getAdiantiObj()->addColumn($column); + return $column; + } + + //--------------------------------------------------------------------------------------- + /** + * coluna tipo checkbox. Irá criar no gride uma coluno do tipo checkbox. Quando é feito o POST + * será criado uma nova variavel com valor de strName + * + * + * @param string $strName - Nome do variavel no POST + * @param string $strTitle - Titulo que aparece no grid + * @param string $strKeyField - Valor que será passado no POST + * @param string $strDescField - Descrição do campo, valor que irá aparecer o gride + * @param boolean $boolReadOnly + * @param boolean $boolAllowCheckAll - TRUE = pode selecionar todos , FALSE = não permite multiplas seleções + * @return TGridCheckColumn + */ + public function addCheckColumn( $strName + , $strTitle = null + , $strKeyField + , $strDescField = null + , $boolReadOnly = null + , $boolAllowCheckAll = null ) + { + if ( !$strKeyField ){ + $strKeyField = strtoupper( $strName ); + } + $this->getAdiantiObj()->disableDefaultClick(); //IMPORTANTE DESATIVAR + $col = new TGridCheckColumn( $strName, $strTitle, $strKeyField, $strDescField, $boolReadOnly, $boolAllowCheckAll ); + $this->columns[ strtolower( $strName )] = $col; + return $col; + } } \ No newline at end of file diff --git a/FormDin5/lib/widget/FormDin5/webform/TFormDinGridColumn.class.php b/FormDin5/lib/widget/FormDin5/webform/TFormDinGridColumn.class.php index 1bc600f9..6a1039ea 100644 --- a/FormDin5/lib/widget/FormDin5/webform/TFormDinGridColumn.class.php +++ b/FormDin5/lib/widget/FormDin5/webform/TFormDinGridColumn.class.php @@ -43,30 +43,35 @@ class TFormDinGridColumn { protected $adiantiObj; + protected $action; /** * Coluna do Grid Padronizado em BoorStrap * Reconstruido FormDin 4 Sobre o Adianti 7.1 * - * @param $action Callback to be executed - * @param string $name = Name of the column in the database - * @param string $label = Text label that will be shown in the header - * @param string $align = Column align (left, center, right) - * @param string $width = Column Width (pixels) + * @param string $name - 1: Name of the column in the database + * @param string $label - 2: Text label that will be shown in the header + * @param string $width - 3: Column Width (pixels) + * @param string $align - 4: Column align (left|right|center|justify) * @return BootstrapFormBuilder */ - public function __construct($action - , string $name + public function __construct(string $name , string $label - , string $align='left' - , string $width = NULL) + , string $width = NULL + , string $align = 'left' + ) { - $this->adiantiObj = new TDataGridColumn($name, $label,$align,$width); - $tAction = new TAction([$action, 'onReload']); - $this->adiantiObj->setAction( $tAction , ['order' => $name]); + $column = new TDataGridColumn($name, $label,$align,$width); + $this->setAdiantiObj($column); return $this->getAdiantiObj(); } + public function setAdiantiObj($adiantiObj){ + if( empty($adiantiObj) ){ + throw new InvalidArgumentException(TFormDinMessage::ERROR_FD5_OBJ_ADI); + } + return $this->adiantiObj=$adiantiObj; + } public function getAdiantiObj(){ return $this->adiantiObj; } diff --git a/FormDin5/lib/widget/FormDin5/webform/TFormDinMessage.class.php b/FormDin5/lib/widget/FormDin5/webform/TFormDinMessage.class.php index dee8a78a..6207df21 100644 --- a/FormDin5/lib/widget/FormDin5/webform/TFormDinMessage.class.php +++ b/FormDin5/lib/widget/FormDin5/webform/TFormDinMessage.class.php @@ -83,6 +83,15 @@ class TFormDinMessage { const ERROR_FD5_PARAM_MIGRA = 'Falha na migração do FormDin 4 para 5.'; const ERROR_FD5_OBJ_ADI = 'Erro objeto Adianti Fieald não pode ficar em branco.'; const ERROR_FD5_OBJ_BUILDER = 'Erro objeto não é um Adianti BootstrapFormBuilder.'; + const ERROR_FD5_OBJ_BOOTGRID = 'Erro objeto não é um Adianti BootstrapDatagridWrapper.'; + + const ERROR_OBJ_TYPE_WRONG = 'type object is wrong'; + const ERROR_OBJ_STORED_PROC = 'Stored Procedure Name is empty'; + const ERROR_OBJ_TABLE = 'Table Name is empty'; + + //----------------------------------------------------------- + + const MSG_CONTRIB_PROJECT = 'Contribute to the project https://github.com/bjverde/sysgenad !'; //------------ Adianti Mensage Type ------------------------- const TYPE_INFO = 'info'; @@ -135,5 +144,30 @@ public static function messageTransform($mixMessage){ } return $result; } + + public static function logRecord(Exception $exception) + { + $app = $_SESSION[APLICATIVO]; + $login = null; + $grupo = null; + if( ArrayHelper::has('USER',$_SESSION[APLICATIVO]) ) { + $login = ( ArrayHelper::has('LOGIN', $_SESSION[APLICATIVO]['USER']) ? $_SESSION[APLICATIVO]['USER']['LOGIN']:null ); + $grupo = ( ArrayHelper::has('GRUPO_NOME', $_SESSION[APLICATIVO]['USER']) ? $_SESSION[APLICATIVO]['USER']['GRUPO_NOME']:null ); + } + $log = 'formDin: '.FORMDIN_VERSION.' ,sistem: '.SYSTEM_ACRONYM.' v:'.SYSTEM_VERSION.' ,usuario: '.$login + .PHP_EOL.'type: '.get_class($exception).' ,Code: '.$exception->getCode().' ,file: '.$exception->getFile().' ,line: '.$exception->getLine() + .PHP_EOL.'mensagem: '.$exception->getMessage() + .PHP_EOL."Stack trace:" + .PHP_EOL.$exception->getTraceAsString(); + + error_log($log); + } + + public static function logRecordSimple($message) + { + $log = 'formDin: '.FORMDIN_VERSION.' ,sistem: '.SYSTEM_ACRONYM.' v:'.SYSTEM_VERSION + .PHP_EOL.TAB.'mensagem: '.$message; + error_log($log); + } } ?> \ No newline at end of file diff --git a/FormDin5/lib/widget/FormDin5/webform/TFormDinPdoConnection.class.php b/FormDin5/lib/widget/FormDin5/webform/TFormDinPdoConnection.class.php new file mode 100644 index 00000000..d85921ea --- /dev/null +++ b/FormDin5/lib/widget/FormDin5/webform/TFormDinPdoConnection.class.php @@ -0,0 +1,309 @@ + + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Formdin. + * + * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ + +class TFormDinPdoConnection +{ + const DBMS_ACCESS = 'ACCESS'; + const DBMS_FIREBIRD = 'ibase'; + const DBMS_MYSQL = 'mysql'; + const DBMS_ORACLE = 'oracle'; + const DBMS_POSTGRES = 'pgsql'; + const DBMS_SQLITE = 'sqlite'; + const DBMS_SQLSERVER = 'sqlsrv'; + + private $database = null; + private $fech = null; + + + private $host; + private $port; + private $name; + private $user; + private $pass; + private $type; + + public function __construct($database = null,$fech = null) + { + if(!empty($database)){ + $this->setDatabase($database); + } + $this->setFech($fech); + } + + public function setDatabase($database) + { + if( empty($database) ){ + throw new InvalidArgumentException('Database Not Object .class:'); + } + $this->database = $database; + } + public function getDatabase() + { + return $this->database; + } + + public function setFech($fech) + { + if(empty($fech)){ + $fech = PDO::FETCH_ASSOC; + } + $this->fech = $fech; + } + public function getFech() + { + return $this->fech; + } + + /** + * Retorna um array com o tipo de SGBD e descrição + * + * @return array + */ + public static function getListDBMS() + { + $list = array(); + //$list[self::DBMS_ACCESS]='Access'; + //$list[self::DBMS_FIREBIRD]='FIREBIRD'; + $list[self::DBMS_MYSQL]='MariaDB ou MySQL'; + $list[self::DBMS_ORACLE]='Oracle'; + $list[self::DBMS_POSTGRES]='PostgreSQL'; + $list[self::DBMS_SQLITE]='SqLite'; + $list[self::DBMS_SQLSERVER]='SQL Server'; + return $list; + } + + public function getHost() + { + return $this->host; + } + public function setHost($host) + { + $this->host = $host; + } + + public function getPort() + { + return $this->port; + } + public function setPort($port) + { + $this->port = $port; + } + + public function getName() + { + return $this->name; + } + public function setName($name) + { + $this->name = $name; + } + + public function getUser() + { + return $this->user; + } + public function setUser($user) + { + $this->user = $user; + } + + public function getPass() + { + return $this->pass; + } + public function setPass($pass) + { + $this->pass = $pass; + } + + public function getType() + { + return $this->type; + } + public function setType($type) + { + $listType = self::getListDBMS(); + $inArray = ArrayHelper::has($type,$listType); + if (!$inArray) { + throw new InvalidArgumentException('Type DBMS is not value valid'); + } + $this->type = $type; + } + + public function getConfigConnect() + { + $result = array(); + $databese = $this->getDatabase(); + $type = $this->getType(); + $name = $this->getName(); + $conditionArrayConnectEmpty = empty($type) || empty($name); + if( empty($databese) && $conditionArrayConnectEmpty ){ + throw new InvalidArgumentException('Fail to configure the database! Please input correct config'); + } + + $db = null; + if(!$conditionArrayConnectEmpty){ + $db = array(); + $db['host'] = $this->getHost(); + $db['port'] = $this->getPort(); + $db['name'] = $name; + $db['user'] = $this->getUser(); + $db['pass'] = $this->getPass(); + $db['type'] = $type; + } + + $result['database'] = $databese; + $result['db'] = $db; + + return $result; + } + + /** + * Retorna o valor Default da porta do SGBD + * + * @return string + */ + public function getDefaulPort() { + $result = null; + switch( $this->getType() ) { + case self::DBMS_POSTGRES: + $result = '5432'; + break; + case self::DBMS_MYSQL: + $result = '3306'; + break; + case self::DBMS_SQLSERVER: + $$result = '1433'; + break; + case self::DBMS_ORACLE: + $result = '1521'; + break; + } + return $result; + } + + /** + * Executa o comando sql recebido retornando o cursor ou verdadeiro o falso + * se a operação foi bem sucedida. + * + * @param string $sql + * @param array $values + * @return mixed + */ + public function executeSql($sql, $values = null) + { + try { + $configConnect = $this->getConfigConnect(); + $database = $configConnect['database']; + $db = $configConnect['db']; + $fech = $this->getFech(); + + TTransaction::open($database,$db); // abre uma transação + $conn = TTransaction::get(); // obtém a conexão + $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, $fech); + $stmt = $conn->query($sql); // realiza a consulta + $result = $stmt->fetchall(); + TTransaction::close(); // fecha a transação. + return $result; + } + catch (Exception $e) { + error_log($e->getMessage()); + throw new Exception($e->getMessage()); + } + } + + public static function getArrayKeyValue($colunaChave,$colunaValor,$list) + { + $result = array(); + foreach ($list as $row) { + $result[$row[$colunaChave]]=$row[$colunaValor]; + } + return $result; + } + + public function getArrayKeyValueBySql($colunaChave,$colunaValor,$sql, $values = null) + { + $resultList = $this->executeSql($sql, $values); + $result = self::getArrayKeyValue($colunaChave,$colunaValor,$resultList); + return $result; + } + + public function selectByTCriteria(TCriteria $criteria, $repositoryName) + { + try { + $configConnect = $this->getConfigConnect(); + $database = $configConnect['database']; + $db = $configConnect['db']; + + TTransaction::open($database,$db); // abre uma transação + $repository = new TRepository($repositoryName); + $collections = $repository->load($criteria); + TTransaction::close(); // fecha a transação. + return $collections; + } + catch (Exception $e) { + error_log($e->getMessage()); + throw new Exception($e->getMessage()); + } + } + + public function selectCountByTCriteria(TCriteria $criteria, $repositoryName) + { + try { + $configConnect = $this->getConfigConnect(); + $database = $configConnect['database']; + $db = $configConnect['db']; + + TTransaction::open($database,$db); // abre uma transação + $repository = new TRepository($repositoryName); + $count = $repository->count($criteria); + TTransaction::close(); // fecha a transação. + return $count; + } + catch (Exception $e) { + error_log($e->getMessage()); + throw new Exception($e->getMessage()); + } + } +} diff --git a/FormDin5/tests/lib/widget/FormDin5/helpers/FormDinHelperTest.php b/FormDin5/tests/lib/widget/FormDin5/helpers/FormDinHelperTest.php index fde5b073..6342b917 100644 --- a/FormDin5/tests/lib/widget/FormDin5/helpers/FormDinHelperTest.php +++ b/FormDin5/tests/lib/widget/FormDin5/helpers/FormDinHelperTest.php @@ -52,7 +52,7 @@ class FormDinHelperTest extends TestCase { public function testVersion() { - $expected = '5.0.0-alpha7'; + $expected = '5.0.0-alpha8'; $result = FormDinHelper::version(); $this->assertEquals( $expected , $result); } diff --git a/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinDaoDbmsTest.php b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinDaoDbmsTest.php new file mode 100644 index 00000000..66ff7212 --- /dev/null +++ b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinDaoDbmsTest.php @@ -0,0 +1,90 @@ + + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Formdin. + * + * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuí1do na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licen?a Pública Geral GNU/LGPL em portugu?s + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ + +$path = __DIR__.'/../../../../../'; +//require_once $path.'tests/initTest.php'; + +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Error\Warning; + +class TFormDinDaoDbmsTest extends TestCase +{ + + private $classTest; + + /** + * Prepares the environment before running a test. + */ + protected function setUp(): void { + parent::setUp(); + $this->classTest = new TFormDinDaoDbms(null,TFormDinPdoConnection::DBMS_SQLITE); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown(): void { + $this->classTest = null; + parent::tearDown(); + } + + public function testSetType_fail() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->setType('xxx'); + } + + public function testGetType() + { + $type = TFormDinPdoConnection::DBMS_ORACLE; + $this->classTest->setType($type); + $result = $this->classTest->getType(); + $this->assertEquals($type, $result); + } + + public function testSetConnection_fail() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->setConnection('xxx'); + } + +} \ No newline at end of file diff --git a/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridColumnTest.php b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridColumnTest.php new file mode 100644 index 00000000..5212c1df --- /dev/null +++ b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridColumnTest.php @@ -0,0 +1,91 @@ + + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Formdin. + * + * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuí1do na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licen?a Pública Geral GNU/LGPL em portugu?s + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ + +require_once __DIR__.'/../../mockFormAdianti.php'; + +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Error\Notice; +use PHPUnit\Framework\Error\Warning; + +class TFormDinGridColumnTest extends TestCase +{ + + private $classTest; + + /** + * Prepares the environment before running a test. + */ + protected function setUp(): void { + parent::setUp(); + $this->classTest = new TFormDinGridColumn('TEST', 'TEST'); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown(): void { + $this->classTest = null; + parent::tearDown(); + } + + public function testTypeObje() + { + $result = $this->classTest->getAdiantiObj(); + $this->assertInstanceOf(TDataGridColumn::class, $result); + } + + public function testAlignCenter() + { + $column = new TFormDinGridColumn('TEST', 'TEST',null,'center'); + $result = $column->getAdiantiObj(); + $this->assertInstanceOf(TDataGridColumn::class, $result); + $this->assertEquals('center', $result->getAlign()); + } + + public function testAlignRight() + { + $column = new TFormDinGridColumn('TEST', 'TEST',null,'right'); + $result = $column->getAdiantiObj(); + $this->assertInstanceOf(TDataGridColumn::class, $result); + $this->assertEquals('right', $result->getAlign()); + } +} \ No newline at end of file diff --git a/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridTest.php b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridTest.php new file mode 100644 index 00000000..0c00dee0 --- /dev/null +++ b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinGridTest.php @@ -0,0 +1,161 @@ + + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Formdin. + * + * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuí1do na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licen?a Pública Geral GNU/LGPL em portugu?s + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ + +require_once __DIR__.'/../../mockFormAdianti.php'; + +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Error\Notice; +use PHPUnit\Framework\Error\Warning; + +class TFormDinGridTest extends TestCase +{ + + private $classTest; + + /** + * Prepares the environment before running a test. + */ + protected function setUp(): void { + parent::setUp(); + $mock = new StdClass; + $this->classTest = new TFormDinGrid($mock,'grid'); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown(): void { + $this->classTest = null; + parent::tearDown(); + } + + + public function testConstruct_Height() + { + $this->expectNotToPerformAssertions(); + $mock = new StdClass; + $grid = new TFormDinGrid($mock,'grid',null,null,700); + } + public function testConstruct_Width() + { + $this->expectNotToPerformAssertions(); + $mock = new StdClass; + $grid = new TFormDinGrid($mock,'grid',null,null,null,700); + } + public function testConstruct_FailOldScript() + { + $this->expectError(); + $grid = new TFormDinGrid('grid','grid'); + } + + public function testSetPanelGroupGrid_fail() + { + $this->expectException(InvalidArgumentException::class); + $item = new StdClass; + $result = $this->classTest->setPanelGroupGrid($item); + } + + public function testSetObjForm_empty() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->setObjForm(null); + } + + public function testSetObjForm_noObjectString() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->setObjForm('xxx'); + } + + public function testSetObjForm_noObjectArray() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->setObjForm(array('a'=>1)); + } + + public function testGetObjForm() + { + $objEntradaz = new mockFormDinComAdianti(); + $this->classTest->setObjForm($objEntradaz); + $objResult = $this->classTest->getObjForm(); + $this->assertInstanceOf(mockFormDinComAdianti::class, $objResult); + } + + public function testFooter() + { + $this->classTest->addFooter('xxx'); + $result = $this->classTest->getFooter(); + $this->assertInstanceOf(TElement::class, $result); + } + + public function testSetAdiantiObj_fail() + { + $this->expectException(InvalidArgumentException::class); + $item = new StdClass; + $this->classTest->setAdiantiObj($item); + } + + public function testGetWidth_fail() + { + $this->expectNotToPerformAssertions(); + $this->classTest->getWidth(); + } + + public function testSetWidth_fail() + { + $this->expectNotToPerformAssertions(); + $this->classTest->setWidth(100); + } + + public function testGetHeight_fail() + { + $this->expectNotToPerformAssertions(); + $this->classTest->getHeight(); + } + + public function testSetHeight_fail() + { + $this->expectNotToPerformAssertions(); + $this->classTest->setHeight(100); + } + +} \ No newline at end of file diff --git a/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinPdoConnectionTest.php b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinPdoConnectionTest.php new file mode 100644 index 00000000..80e0f759 --- /dev/null +++ b/FormDin5/tests/lib/widget/FormDin5/webform/TFormDinPdoConnectionTest.php @@ -0,0 +1,142 @@ + + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Formdin. + * + * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuí1do na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licen?a Pública Geral GNU/LGPL em portugu?s + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ + +$path = __DIR__.'/../../../../../'; +//require_once $path.'tests/initTest.php'; + +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Error\Warning; + +class TFormDinPdoConnectionTest extends TestCase +{ + + private $classTest; + + /** + * Prepares the environment before running a test. + */ + protected function setUp(): void { + parent::setUp(); + $this->classTest = new TFormDinPdoConnection(); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown(): void { + $this->classTest = null; + parent::tearDown(); + } + + + public function testSetType_null() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->setType(null); + } + public function testSetType_wrongType() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->setType('abc'); + } + public function testSetType_correctType() + { + $this->expectNotToPerformAssertions(); + $this->classTest->setType(TFormDinPdoConnection::DBMS_SQLITE); + } + + //--------------------------------------------- + public function testGetConfigConnect_null() + { + $this->expectException(InvalidArgumentException::class); + $this->classTest->getConfigConnect(); + } + + public function testGetConfigConnect_SetDatabase() + { + $database = 'formdin'; + $this->classTest->setDatabase($database); + $result = $this->classTest->getConfigConnect(); + + $this->assertCount(2, $result); + $this->assertEquals($database, $result['database']); + $this->assertEquals(null, $result['db']); + } + + public function testGetConfigConnect_nullDatabaseSetTypeOnly() + { + $this->expectException(InvalidArgumentException::class); + + $this->classTest->setType(TFormDinPdoConnection::DBMS_SQLITE); + $result = $this->classTest->getConfigConnect(); + } + + public function testGetConfigConnect_nullDatabaseGetDb() + { + $name = 'bdApoio.s3db'; + $this->classTest->setName($name); + $this->classTest->setType(TFormDinPdoConnection::DBMS_SQLITE); + $result = $this->classTest->getConfigConnect(); + + $this->assertCount(2, $result); + $this->assertEquals(null, $result['database']); + $this->assertCount(6, $result['db']); + $this->assertEquals(TFormDinPdoConnection::DBMS_SQLITE, $result['db']['type']); + $this->assertEquals($name, $result['db']['name']); + } + + public function testExecuteSql_sqllite() + { + $path = __DIR__.'/../../../../../'; + $name = $path.'database/bdApoio.s3db'; + $this->classTest->setName($name); + $this->classTest->setType(TFormDinPdoConnection::DBMS_SQLITE); + $sql = 'select * from dado_apoio order by seq_dado_apoio'; + $result = $this->classTest->executeSql($sql); + + $this->assertCount(3, $result); + $this->assertEquals(1, $result[0]['seq_dado_apoio']); + $this->assertEquals('Metro', $result[1]['tip_dado_apoio']); + } + + +} \ No newline at end of file diff --git a/FormDin5/tests/lib/widget/mockFormAdianti.php b/FormDin5/tests/lib/widget/mockFormAdianti.php new file mode 100644 index 00000000..e10ac2a4 --- /dev/null +++ b/FormDin5/tests/lib/widget/mockFormAdianti.php @@ -0,0 +1,10 @@ +assertEquals( $expected , $result); }