Completed
Push — master ( 611fe2...a133f4 )
by Mars
01:48
created

Base::throwException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
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
     * @throws \Exception
91
     * @return string
92
     */
93
    public static function getUnit(string $target, $unit = 'default')
94
    {
95
        if (isset(self::$_options['unit'][$target])) {
96
            return !isset(self::$_options['unitMap'][$unit]) ? self::$_options['unit'][$target] : self::$_options['unitMap'][$unit];
97
        } else {
98
            throw new \Exception('Error Target: ' . $target, 400);
99
        }
100
    }
101
102
    /**
103
     * If neet filter datetime : Set option
104
     * 
105
     * 1. Scope: Global
106
     * 2. If you do not want to filter the datetime format, set it to false.  
107
     * 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.
108
     * 4. Effect function: filter(), validate()
109
     * 
110
     * @param bool $bool
111
     * @return $this
112
     */
113
    public static function setFilterDatetime($bool)
114
    {
115
        self::$_options['filter']['isDatetime'] = !!$bool;
116
117
        return new static();
118
    }
119
120
    /**
121
     * If neet filter datetime : Get option
122
     * 
123
     * @return bool
124
     */
125
    public static function getFilterDatetime()
126
    {
127
        return self::$_options['filter']['isDatetime'];
128
    }
129
130
    /**
131
     * Auto sort out $timePeriods : Set option
132
     *
133
     * 1. Scope: Global
134
     * 2. Before the function is processed, union() will be used to organize $timePeriods format.
135
     * 
136
     * @param bool $bool default true
137
     * @return $this
138
     */
139
    public static function setSortOut($bool = true)
140
    {
141
        self::$_options['sortOut'] = !!$bool;
142
143
        return new static();
144
    }
145
146
    /**
147
     * Auto sort out $timePeriods : Get option
148
     *
149
     * @return bool
150
     */
151
    public static function getSortOut()
152
    {
153
        return self::$_options['sortOut'];
154
    }
155
156
157
    /**
158
     * ********************************************
159
     * ************** Tools Function **************
160
     * ********************************************
161
     */
162
163
    /**
164
     * Check datetime fast
165
     * 
166
     * Only check format,no check for reasonableness
167
     * 
168
     * @param string $datetime
169
     * @return boolean
170
     */
171
    public static function isDatetime(string $datetime)
172
    {
173
        return (bool) preg_match('|^[0-9]{4}\-[0-9]{2}\-[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}$|', $datetime);
174
    }
175
176
    /**
177
     * Time format convert
178
     * 
179
     * format:Y-m-d H:i:s
180
     * When the length is insufficient, it will add the missing
181
     * 
182
     * @param string $datetime
183
     * @param string $unit Time unit, if default,use self::$_options setting
184
     * @return string
185
     */
186
    public static function timeFormatConv(string $datetime, $unit = 'default')
187
    {
188
        // fill format
189
        $strlen = strlen($datetime);
190
        $datetime .= substr(' 00:00:00', $strlen - 10);
191
192
        // replace
193
        $unit = self::getUnit('format', $unit);
194
        if ($unit == 'minute') {
195
            $datetime = substr_replace($datetime, "00", 17, 2);
196
        } elseif ($unit == 'hour') {
197
            $datetime = substr_replace($datetime, "00:00", 14, 5);
198
        }
199
200
        return $datetime;
201
    }
202
203
    /**
204
     * Extend time
205
     * 
206
     * @param string $datetime
207
     * @param int $timeLen 
208
     * @return string
209
     */
210
    public static function extendTime(String $datetime, $timeLen)
211
    {
212
        $tout = date('Y-m-d H:i:s', strtotime($datetime) + $timeLen);
213
        return substr($tout, 0, strlen($datetime));
214
    }
215
216
    /**
217
     * Time Conversion frm unit to second
218
     * 
219
     * @param number $time
220
     * @param string $unit Time unit, if default,use self::$_options setting
221
     * @return int
222
     */
223
    public static function time2Second($time, $unit = 'default')
224
    {
225
        // Convert
226
        $unit = self::getUnit('time', $unit);
227
        switch ($unit) {
228
            case 'minute':
229
                $time = $time * 60;
230
                break;
231
            case 'hour':
232
                $time = $time * 3600;
233
                break;
234
        }
235
236
        return (int) $time;
237
    }
238
239
    /**
240
     * Throw Exception by function 
241
     * 
242
     * In order to remove the if statement:
243
     * - if (true/false) { throw new \Exception($msg, $code); }
244
     * - true/false || throw new \Exception($msg, $code);    <= Error
245
     * - true/false || self::throwException($msg, $code);    <= Good
246
     * 
247
     * @param string $msg
248
     * @param int $code
249
     * @return void
250
     */
251
    protected static function throwException($msg, $code) {
252
        throw new \Exception($msg, $code);
253
        return true;
0 ignored issues
show
Unused Code introduced by
return true is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
254
    }
255
}
256