Passed
Push — main ( f05cfd...29a9c1 )
by Stefan
02:38
created

FormTime::buildValue()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 15
c 0
b 0
f 0
nc 8
nop 0
dl 0
loc 23
rs 8.4444
1
<?php
2
declare(strict_types=1);
3
4
namespace SKien\Formgenerator;
5
6
/**
7
 * Input field for time value.
8
 * - size always 10
9
 * - field will be added to JS form validation
10
 *
11
 * #### History
12
 * - *2020-05-12*   initial version
13
 * - *2021-01-07*   PHP 7.4
14
 *
15
 * @package Formgenerator
16
 * @version 1.1.0
17
 * @author Stefanius <[email protected]>
18
 * @copyright MIT License - see the LICENSE file for details
19
 */
20
class FormTime extends FormInput
21
{
22
    /**
23
     * Creates input field for time values.
24
     * @param string $strName
25
     * @param int $wFlags
26
     */
27
    public function __construct(string $strName, int $wFlags = 0) 
28
    {
29
        parent::__construct($strName, 10, $wFlags);
30
        $this->strValidate = 'aTime';
31
    }
32
    
33
    /**
34
     * Accept date value from Formgenerator-data as <ul>
35
     * <li> DateTime - object </li>
36
     * <li> unix timestamp (int) </li>
37
     * <li> English textual datetime description readable by <b>strtotime</b> <br/>
38
     *      can be a DATE, DATETIME or TIMESTAMP value from a DB query
39
     * </li></ul>
40
     * The displayed format can be configured with the <i>'FormTime.Format'</i> parameter
41
     * as strftime-compatible format string (default settings: '%H:%M) 
42
     * {@inheritDoc}
43
     * @see \SKien\Formgenerator\FormElement::buildValue()
44
     * @link https://www.php.net/manual/en/function.strftime.php
45
     */
46
    protected function buildValue() : string
47
    {
48
        $date = $this->oFG->getData()->getValue($this->strName);
49
        $strDateFormat = $this->oFG->getConfig()->getString('Time.Format', '%H:%M');
50
        
51
        $strValue = '';
52
        if (is_object($date) && get_class($date) == 'DateTime') {
53
            // DateTime-object
54
            $strValue = strftime($strDateFormat, $date->getTimestamp());
55
        } else if (is_numeric($date)) {
56
            $strValue = strftime($strDateFormat, $date);
57
        } else {
58
            $unixtime = strtotime($date);
59
            if ($unixtime !== false) {
60
                $strValue = strftime($strDateFormat, $unixtime);
61
            }
62
        }
63
        
64
        $strHTML = '';
65
        if (!$this->oFlags->isSet(FormFlags::NO_ZERO) || ($strValue != 0 && $strValue != '0')) {
66
            $strHTML = ' value="' . str_replace('"', '&quot;', $strValue) . '"';
67
        }
68
        return $strHTML;
69
    }
70
}
71