Issues (1)

src/classes/Base.php (1 issue)

1
<?php
2
3
namespace marsapp\helper\timeperiod\classes;
4
5
/**
6
 * Base class for Time Period Helper
7
 * 
8
 * @author Mars Hung <[email protected]>
9
 * @see https://github.com/marshung24/TimePeriodHelper
10
 */
11
class Base
12
{
13
    /**
14
     * Option set
15
     * @var array
16
     */
17
    private static $_options = [
18
        'unit' => [
19
            // Time calculate unit - hour, minute, second(default)
20
            'time' => 'second',
21
            // Format unit - hour, minute, second(default)
22
            'format' => 'second',
23
        ],
24
        'unitMap' => [
25
            'hour' => 'hour',
26
            'hours' => 'hour',
27
            'h' => 'hour',
28
            'minute' => 'minute',
29
            'minutes' => 'minute',
30
            'i' => 'minute',
31
            'm' => 'minute',
32
            'second' => 'second',
33
            'seconds' => 'second',
34
            's' => 'second',
35
        ],
36
        'filter' => [
37
            'isDatetime' => true
38
        ],
39
        // Default sort out $timePeriods
40
        'sortOut' => true,
41
    ];
42
43
    /**
44
     * **********************************************
45
     * ************** Options Function **************
46
     * **********************************************
47
     */
48
49
50
    /**
51
     * Specify the minimum unit of calculation
52
     * 
53
     * 1. Scope: Global
54
     * 2. hour,minute,second
55
     * 
56
     * @param string $unit time unit. e.g. hour, minute, second.
57
     * @param string $target Specify function,or all functions
58
     * @throws \Exception
59
     * @return $this
60
     */
61
    public static function setUnit(string $unit, string $target = 'all')
62
    {
63
        /*** Arguments prepare ***/
64
        if (!isset(self::$_options['unitMap'][$unit])) {
65
            throw new \Exception('Error Unit: ' . $unit, 400);
66
        }
67
        // conv unit
68
        $unit = self::$_options['unitMap'][$unit];
69
70
        if ($target != 'all' && !isset(self::$_options['unit'][$target])) {
71
            throw new \Exception('Error Target: ' . $target, 400);
72
        }
73
74
        /* Setting */
75
        if ($target != 'all') {
76
            self::$_options['unit'][$target] = $unit;
77
        } else {
78
            foreach (self::$_options['unit'] as $tar => &$value) {
79
                $value = $unit;
80
            }
81
        }
82
83
        return new static();
84
    }
85
86
    /**
87
     * Get the unit used by the specified function
88
     * 
89
     * @param string $target Specify function's unit
90
     * @param string $unit Time unit, if default,use self::$_options setting(set by setUnit())
91
     * @throws \Exception
92
     * @return string
93
     */
94
    public static function getUnit(string $target, $unit = 'default')
95
    {
96
        if (isset(self::$_options['unit'][$target])) {
97
            return !isset(self::$_options['unitMap'][$unit]) ? self::$_options['unit'][$target] : self::$_options['unitMap'][$unit];
98
        } else {
99
            throw new \Exception('Error Target: ' . $target, 400);
100
        }
101
    }
102
103
    /**
104
     * If neet filter datetime : Set option
105
     * 
106
     * 1. Scope: Global
107
     * 2. If you do not want to filter the datetime format, set it to false.  
108
     * 3. Maybe the time format is not Y-m-d H:i:s (such as Y-m-d H:i), you need to close it.
109
     * 4. Effect function: filter(), validate()
110
     * 
111
     * @param bool $bool
112
     * @return $this
113
     */
114
    public static function setFilterDatetime($bool)
115
    {
116
        self::$_options['filter']['isDatetime'] = !!$bool;
117
118
        return new static();
119
    }
120
121
    /**
122
     * If neet filter datetime : Get option
123
     * 
124
     * @return bool
125
     */
126
    public static function getFilterDatetime()
127
    {
128
        return self::$_options['filter']['isDatetime'];
129
    }
130
131
    /**
132
     * Auto sort out $timePeriods : Set option
133
     *
134
     * 1. Scope: Global
135
     * 2. Before the function is processed, union() will be used to organize $timePeriods format.
136
     * 
137
     * @param bool $bool default true
138
     * @return $this
139
     */
140
    public static function setSortOut($bool = true)
141
    {
142
        self::$_options['sortOut'] = !!$bool;
143
144
        return new static();
145
    }
146
147
    /**
148
     * Auto sort out $timePeriods : Get option
149
     *
150
     * @return bool
151
     */
152
    public static function getSortOut()
153
    {
154
        return self::$_options['sortOut'];
155
    }
156
157
158
    /**
159
     * ********************************************
160
     * ************** Tools Function **************
161
     * ********************************************
162
     */
163
164
    /**
165
     * Check datetime fast
166
     * 
167
     * Only check format,no check for reasonableness
168
     * 
169
     * @param string $datetime
170
     * @return boolean
171
     */
172
    public static function isDatetime(string $datetime)
173
    {
174
        return (bool) preg_match('|^[0-9]{4}\-[0-9]{2}\-[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}$|', $datetime);
175
    }
176
177
    /**
178
     * Time format convert
179
     * 
180
     * format:Y-m-d H:i:s
181
     * When the length is insufficient, it will add the missing
182
     * 
183
     * @param string $datetime
184
     * @param string $unit Time unit, if default,use self::$_options setting(set by setUnit())
185
     * @return string
186
     */
187
    public static function timeFormatConv(string $datetime, $unit = 'default')
188
    {
189
        // fill format
190
        $strlen = strlen($datetime);
191
        $datetime .= substr(' 00:00:00', $strlen - 10);
192
193
        // replace
194
        $unit = self::getUnit('format', $unit);
195
        if ($unit == 'minute') {
196
            $datetime = substr_replace($datetime, "00", 17, 2);
197
        } elseif ($unit == 'hour') {
198
            $datetime = substr_replace($datetime, "00:00", 14, 5);
199
        }
200
201
        return $datetime;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $datetime also could return the type array which is incompatible with the documented return type string.
Loading history...
202
    }
203
204
    /**
205
     * Extend time
206
     * 
207
     * @param string $datetime
208
     * @param int $timeLen 
209
     * @return string
210
     */
211
    public static function extendTime(String $datetime, $timeLen)
212
    {
213
        $tout = date('Y-m-d H:i:s', strtotime($datetime) + $timeLen);
214
        return substr($tout, 0, strlen($datetime));
215
    }
216
217
    /**
218
     * Time Conversion frm unit to second
219
     * 
220
     * @param number $time
221
     * @param string $unit Time unit, if default,use self::$_options setting(set by setUnit())
222
     * @return int
223
     */
224
    public static function time2Second($time, $unit = 'default')
225
    {
226
        // Convert
227
        $unit = self::getUnit('time', $unit);
228
        switch ($unit) {
229
            case 'minute':
230
                $time = $time * 60;
231
                break;
232
            case 'hour':
233
                $time = $time * 3600;
234
                break;
235
        }
236
237
        return (int) $time;
238
    }
239
240
    /**
241
     * Throw Exception by function 
242
     * 
243
     * In order to remove the if statement:
244
     * - if (true/false) { throw new \Exception($msg, $code); }
245
     * - true/false || throw new \Exception($msg, $code);    <= Error
246
     * - true/false || self::throwException($msg, $code);    <= Good
247
     * 
248
     * @param string $msg
249
     * @param int $code
250
     * @return void
251
     */
252
    protected static function throwException($msg, $code) {
253
        throw new \Exception($msg, $code);
254
    }
255
}
256