Completed
Pull Request — master (#268)
by
unknown
01:26
created

Xhgui_Storage_Abstract::getDateTimeFromString()   C

Complexity

Conditions 12
Paths 31

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 6.9666
c 0
b 0
f 0
cc 12
nc 31
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
4
class Xhgui_Storage_Abstract
5
{
6
7
    /**
8
     * Try to get date from Y-m-d H:i:s or from timestamp
9
     *
10
     * @param string|int $date
11
     * @param string $direction
12
     * @return \DateTime
13
     */
14
    protected function getDateTimeFromString($date, $direction = 'start')
15
    {
16
        try {
17
            $datetime = \DateTime::createFromFormat('Y-m-d H:i:s', $date);
18
            if (!empty($datetime) && $datetime instanceof \DateTime) {
19
                return $datetime;
20
            }
21
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
22
        }
23
24
        // try without time
25
        try {
26
            $datetime = \DateTime::createFromFormat('Y-m-d', $date);
27
            if (!empty($datetime) && $datetime instanceof \DateTime) {
28
29
                if ($direction === 'start') {
30
                    $datetime->setTime(0,0,0);
31
                } elseif ($direction === 'end') {
32
                    $datetime->setTime(23,59,59);
33
                }
34
35
                return $datetime;
36
            }
37
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
38
        }
39
40
        // try using timestamp
41
        try {
42
            $datetime = \DateTime::createFromFormat('U', $date);
43
            if (!empty($datetime) && $datetime instanceof \DateTime) {
44
                return $datetime;
45
            }
46
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
47
        }
48
49
        throw new \InvalidArgumentException('Unable to parse date');
50
    }
51
}
52