Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 187
TNumber
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 21
9702
0.00% covered (danger)
0.00%
0 / 187
 __construct
0.00% covered (danger)
0.00%
0 / 1
72
0.00% covered (danger)
0.00%
0 / 18
 show
0.00% covered (danger)
0.00%
0 / 1
240
0.00% covered (danger)
0.00%
0 / 41
 setMaxValue
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getMaxValue
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setMinValue
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getMinValue
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setDecimalPlaces
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getDecimalPlaces
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setFormatInteger
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getFormatInteger
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setDirection
0.00% covered (danger)
0.00%
0 / 1
72
0.00% covered (danger)
0.00%
0 / 15
 getDirection
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setAllowZero
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getAllowZero
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setAllowNull
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getAllowNull
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 getAsNumber
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 4
 validate
0.00% covered (danger)
0.00%
0 / 1
552
0.00% covered (danger)
0.00%
0 / 41
 getMask
0.00% covered (danger)
0.00%
0 / 1
42
0.00% covered (danger)
0.00%
0 / 13
 setValue
0.00% covered (danger)
0.00%
0 / 1
240
0.00% covered (danger)
0.00%
0 / 29
 getValue
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 4
1<?php
2/*
3 * Formdin Framework
4 * Copyright (C) 2012 Ministério do Planejamento
5 * Criado por Luís Eugênio Barbosa
6 * Essa versão é um Fork https://github.com/bjverde/formDin
7 *
8 * ----------------------------------------------------------------------------
9 * This file is part of Formdin Framework.
10 *
11 * Formdin Framework is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License version 3
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public License version 3
21 * along with this program; if not,  see <http://www.gnu.org/licenses/>
22 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
23 * Fifth Floor, Boston, MA  02110-1301, USA.
24 * ----------------------------------------------------------------------------
25 * Este arquivo é parte do Framework Formdin.
26 *
27 * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou
28 * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação
29 * do Software Livre (FSF).
30 *
31 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
32 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
33 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português
34 * para maiores detalhes.
35 *
36 * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
37 * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/>
38 * ou escreva para a Fundação do Software Livre (FSF) Inc.,
39 * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
40 */
41
42class TNumber extends TEdit
43{
44    private $minValue;
45    private $maxValue;
46    private $decimalPlaces;
47    private $formatInteger;
48    private $direction;
49    private $allowZero;
50    private $allowNull;
51    /**
52     * @param string $name
53     * @param string $value
54     * @param boolean $required
55     * @param integer $decimalPlaces
56     * @param string $minValue
57     * @param string $maxValue
58     * @param boolean $formatInteger
59     * @param boolean $allowZero
60     * @param boolean $allowNull
61     */
62    public function __construct(string $strName
63                              ,string $strValue=null
64                              ,$intMaxLength
65                              ,$boolRequired=null,$intDecimalPlaces=null,$strMinValue=null,$strMaxValue=null,$boolFormatInteger=null,$strDirection=null,$boolAllowZero=null,$boolAllowNull=null)
66    {
67        parent::__construct($strName,null,$intMaxLength,$boolRequired);
68        $this->setFieldType('number');
69        $this->setAllowZero($boolAllowZero);
70        $this->setAllowNull($boolAllowNull);
71        $this->setMinValue($strMinValue);
72        $this->setMaxValue($strMaxValue);
73        $this->setDecimalPlaces($intDecimalPlaces);
74        $this->setFormatInteger($boolFormatInteger);
75        $this->setDirection($strDirection);
76        if( !isset($_POST[ $this->getId() ] ) )
77        {
78            if( !is_null( $strValue ) )
79            {
80                $this->setValue($strValue);
81            }
82            if( ! $this->getValue())
83            {
84                // inicializar com o valor minimo se tiver valor inválido
85                if( $this->getMinValue() && $this->getValue() < $this->getMinValue())
86                {
87
88                    if( !$this->getAllowZero() && !$this->getAllowNull())
89                    {
90                        $this->value = $this->getMinValue();
91                    }
92                }
93            }
94        }
95        else
96        {
97            $this->setValue( $_POST[ $this->getId() ] );
98        }
99    }
100    //--------------------------------------------------------------------------
101    public function show($print=true)
102    {
103        // definir a direção do texto durante a entrada de dados
104        switch($this->getDirection())
105        {
106            case 'rtl':
107                $this->setCss('text-align','right');
108                break;
109            case 'ltr':
110                $this->setCss('text-align','left');
111                break;
112            case 'c':
113                $this->setCss('text-align','center');
114                break;
115        }
116
117        //$this->setProperty('dir',$this->getDirection()); retirei porque o sina de negativo fica a direita com rtl
118        // não utilizar formatCurrency(this,...) porque dá erro quando o campos tem decimal=0
119        $js = new TElement('script');
120        $js->setProperty('type',"text/javascript");
121        if( (int) $this->getDecimalPlaces() == 0)
122        {
123            $this->addEvent('onKeyUp' ,'fwFormatarInteiro(this,"'. ( ($this->getFormatInteger())?'S':'N').'")');
124            //$js->add('jQuery("#'.$this->getId().'").bind("keyup",function(){ fwFormatarInteiro(this,"'. ( ($this->getFormatInteger())?'S':'N').'") }');
125        }
126        else
127        {
128            $limit = $this->getMaxLenght();
129            if( $limit - $this->getDecimalPlaces() < 2 )
130            {
131                $this->setMaxLenght( $limit + 2 );
132                $this->setSize($this->getMaxLenght());
133                $limit = $this->getMaxLenght();
134            }
135            $this->getMask(); // ajustar size e maxlenght
136            $js->add('jQuery("#'.$this->getId().'").priceFormat({ prefix: "",centsSeparator: ",", thousandsSeparator: ".","allowNull":'.$this->getAllowNull().',centsLimit:'.$this->getDecimalPlaces().',limit:'.$limit.'});');
137            // aumentar o tamanho do campo para a função preice format funcionar
138            $this->setMaxLenght(($this->getMaxLenght()+1));
139            $this->setSize($this->getMaxLenght());
140        }
141        if(    $this->getMinValue() || $this->getMaxValue())
142        {
143            $minValue = null;
144            if( !empty($minValue) ){
145                $minValue = str_replace(',','.',$this->getMinValue());
146            }
147            $minValue = (is_numeric($minValue) ? $minValue : "Number.NaN");
148            $maxValue = null;
149            if( !empty($maxValue) ){
150                $maxValue = str_replace(',','.',$this->getMaxValue());
151            }
152            $maxValue = (is_numeric( $maxValue ) ? $maxValue : "Number.NaN");
153            $stringFuncaoJs = "fwChkMinMax(".$minValue.",".$maxValue.",'".$this->getName()."',".$this->getDecimalPlaces().",".$this->getAllowZero().",".$this->getAllowNull().")";
154            $this->addEvent('onBlur',$stringFuncaoJs);
155        }
156        if( $this->getEvents() )
157        {
158            foreach($this->getEvents() as $eventName=>$event)
159            {
160                $eventName = preg_replace('/^on/i','',strtolower($eventName));
161                   $js->add('jQuery("#'.$this->getId().'").bind("'.$eventName.'",function(){ '.$event.' })');
162            }
163            $this->clearEvents();
164        }
165        $this->add($js);
166        return parent::show($print);
167    }
168    //---------------------------------------------------------------------------
169    public function setMaxValue($numNewValue=null)
170    {
171        $this->maxValue = $numNewValue;
172    }
173    //---------------------------------------------------------------------------
174    public function getMaxValue()
175    {
176        return $this->maxValue;
177    }
178    //---------------------------------------------------------------------------
179    public function setMinValue($strNewValue=null)
180    {
181        $this->minValue = $strNewValue;
182    }
183    //---------------------------------------------------------------------------
184    public function getMinValue()
185    {
186        return $this->minValue;
187    }
188    //----------------------------------------------------------------------------
189    public function setDecimalPlaces($numNewDecimalPlaces)
190    {
191        $this->decimalPlaces = $numNewDecimalPlaces;
192    }
193    //----------------------------------------------------------------------------
194    public function getDecimalPlaces()
195    {
196        return (int)$this->decimalPlaces;
197    }
198    //-----------------------------------------------------------------------------
199    public function setFormatInteger($boolNewValue=null)
200    {
201        $boolNewValue = $boolNewValue===null ? false : $boolNewValue;
202        $this->formatInteger=(bool) $boolNewValue;
203    }
204    //-----------------------------------------------------------------------------
205    public function getFormatInteger()
206    {
207        return (bool) $this->formatInteger;
208    }
209    public function setDirection($strDirection=null)
210    {
211        switch($strDirection)
212        {
213            case 'R';
214            case 'r';
215                $this->direction = 'rtl';
216            break;
217            case 'L';
218            case 'l';
219                $this->direction = 'ltr';
220            break;
221            case 'C';
222            case 'c';
223                $this->direction = 'c';
224            break;
225            //--------------------------------
226            default:
227                $this->direction = 'rtl';
228        }
229    }
230    //------------------------------------------------
231    public function getDirection()
232    {
233        return $this->direction;
234    }
235    //------------------------------------------------
236    public function setAllowZero($boolNewValue=null)
237    {
238        $boolNewValue = is_null($boolNewValue) ? false : $boolNewValue;
239        $this->allowZero = $boolNewValue;
240    }
241    //------------------------------------------------
242    public function getAllowZero()
243    {
244        return $this->allowZero ? 1 : 0;
245    }
246    public function setAllowNull($boolNewValue=null)
247    {
248        $boolNewValue = is_null($boolNewValue) ? false : $boolNewValue;
249        $this->allowNull = $boolNewValue;
250    }
251    //------------------------------------------------
252    public function getAllowNull()
253    {
254        return $this->allowNull ? 1 : 0;
255    }
256    //-------------------------------------------------
257    public function getAsNumber($strNumber=null)
258    {
259        $strNumber = is_null($strNumber) ? $this->getValue() : $strNumber;
260        if($this->getDecimalPlaces()>0)
261        {
262            return (double) str_replace(',','.',str_replace('.','',$strNumber));
263        }
264        else
265        {
266            return (int) str_replace(',','.',str_replace('.','',$strNumber));
267        }
268    }
269    //---------------------------------------------------
270    public function validate()
271    {
272        if( parent::validate() )
273        {
274            $zero     = (double) ($this->getDecimalPlaces()>0) ? '0.'.str_repeat('0',$this->getDecimalPlaces()) : "0";
275            if( $this->getValue() == '' || is_null($this->getValue()))
276            {
277                if($this->getAllowNull())
278                {
279                    return true;
280                }
281            }
282            else if( $this->getAsNumber() == $zero && $this->getAllowZero())
283            {
284                return true;
285            }
286            // validar valor minimo
287            if($this->getMinValue())
288            {
289                $min = $this->getAsNumber($this->getMinValue());
290                $val = $this->getAsNumber();
291                $msg = '';
292                if($val < $min  )
293                {
294                    if( $this->getMaxValue())
295                    {
296                        $msg = 'Valor deve estar entre '.$this->getMinValue().' e '.$this->getMaxValue();
297                    }
298                    else
299                    {
300                        $msg = 'Valor deve ser MAIOR ou IGUAL a '.$this->getMinValue();
301                    }
302                }
303                if($msg != '')
304                {
305                    if( $this->getAllowZero())
306                    {
307                        $msg .= ' ou zero';
308                    }
309                    if( $this->getAllowNull())
310                    {
311                        $msg .= ' ou em branco';
312                    }
313                    $this->addError($msg );
314                }
315            }
316            // validar valor maximo
317            if($this->getMaxValue())
318            {
319                $max = $this->getAsNumber($this->getMaxValue());
320                $val = $this->getAsNumber();
321                $msg = '';
322                if( $val > $max  )
323                {
324                    if( $this->getMinValue())
325                    {
326                        $msg = 'Valor deve estar entre '.$this->getMinValue().' e '.$this->getMaxValue();
327                    }
328                    else
329                    {
330                        $msg = 'Valor deve ser MENOR ou IGUAL a '.$this->getMaxValue();
331                    }
332                }
333                if( $msg != '' )
334                {
335                    if( $this->getAllowZero())
336                    {
337                        $msg .= ' ou zero';
338                    }
339                    if( $this->getAllowNull())
340                    {
341                        $msg .= ' ou em branco';
342                    }
343                    $this->addError($msg );
344                }
345            }
346            if($this->getRequired())
347            {
348                if( $this->getAsNumber() == $zero )
349                {
350                    $this->addError('Campo obrigatório');
351                }
352            }
353        }
354        if( !$result = ( (string)$this->getError()==="" )) {
355            $this->setCss('border','1px solid #ff0000'); //#176 relacionado com FormDin4.js
356            //$this->setClass('fwFieldRequiredBoarder');
357        }
358        return $result;
359    }
360    /**
361    * Criar a máscara de formatação para entrada de dados numérica com casas decimais
362    */
363    public function getMask()
364    {
365        $d         = (int) $this->getDecimalPlaces();
366        $d         +=  $d > 0 ? 1 : 0 ;
367        $qtd9     = $this->getMaxLenght()-$d;
368        $int     = '';
369        for($i=0;$i<$qtd9;$i++)
370        {
371            if( $i%3==0 && $i>0)
372            {
373                $int = ','.$int;
374            }
375            $int = '9'.$int;
376        }
377        $dec = str_repeat('9',(int)$this->getDecimalPlaces());
378        $int .= $dec ? '.' : '';
379        $this->setMaxLenght(strlen($int.$dec));
380        $this->setSize($this->getMaxLenght());
381        return $int.$dec;
382    }
383    public function setValue($newValue=null)
384    {
385        parent::setValue($newValue);
386        $newValue = $this->value;
387        if( FormDinHelper::pregMatch('/[1-9]/',$newValue)==0 && ! $this->getAllowZero() ) {
388            if( $this->getAllowNull() ){
389                $this->value = '';
390                return;
391            }
392          }
393        if( $this->getDecimalPlaces() > 0 ){
394            $posComma = strpos($newValue,',');
395            $posPoint = strpos($newValue,'.');
396            $posComma = !$posComma ? 0 : $posComma;
397            $posPoint = !$posPoint ? 0 : $posPoint;
398            if( $posComma && $posPoint ){
399                if( $posComma>$posPoint){
400                    $newValue = preg_replace('/\./','',$newValue);
401                } else {
402                    $newValue = preg_replace('/,/','',$newValue);
403                    $newValue = preg_replace('/\./',',',$newValue);
404                }
405            }else if( $posPoint ){
406                $newValue = preg_replace('/\./',',',$newValue);
407            }
408            //completar casas decimais
409            if ( FormDinHelper::pregMatch('/,/',$newValue)==0){
410                $newValue.=',0'; // deve ter pelo menos uma casa decimal
411            }
412            $aParts = explode(',',$newValue);
413            if( isset( $aParts[1] ) ){
414                if( strlen($aParts[1]) < $this->getDecimalPlaces()){
415                    $aParts[1] = str_pad($aParts[1], $this->getDecimalPlaces(),'0',STR_PAD_RIGHT );
416                }
417                else if( strlen($aParts[1]) > $this->getDecimalPlaces())
418                {
419                    $aParts[1] = substr($aParts[1],0,$this->getDecimalPlaces());
420                }
421                $newValue = $aParts[0].','.$aParts[1];
422            }
423            parent::setValue($newValue);
424        }
425    }
426    public function getValue()
427    {
428        parent::getValue();
429        if( $this->value == '')
430        {
431            $this->value=null;
432        }
433        return $this->value;
434    }
435}
436//return;
437//$val = new TNumber('val_salario','100,20',20,true,2);
438//$val->setDirection('c');
439//$val->setDirection('L');
440/*$val->validate();
441$val->setValue('0,00');
442$val->validate();
443$val->setAllowZero(true);
444$val->validate();
445// teste min value
446$val->setMinValue('5,50');
447$val->validate();
448$val->setValue(2);
449$val->validate();
450$val->setValue('5,4');
451$val->validate();
452*/
453// teste max value
454//print '<br>'.$val->getValue();
455//$val->setMaxValue('10,87');
456//$val->validate();
457//$val->setValue('10,88');
458//$val->validate();
459//$val->setValue('11,88');
460//$val->validate();
461//$val->show();
462?>