Passed
Pull Request — master (#71)
by ignace nyamagana
01:37
created

Datepoint::create()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 5
nop 1
dl 0
loc 21
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * League.Period (https://period.thephpleague.com).
5
 *
6
 * (c) Ignace Nyamagana Butera <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace League\Period;
15
16
use DateTime;
17
use DateTimeImmutable;
18
use DateTimeInterface;
19
use TypeError;
20
use function filter_var;
21
use function get_class;
22
use function gettype;
23
use function is_object;
24
use function is_string;
25
use function sprintf;
26
use const FILTER_VALIDATE_INT;
27
28
/**
29
 * League Period Datepoint.
30
 *
31
 * @package League.period
32
 * @author  Ignace Nyamagana Butera <[email protected]>
33
 * @since   4.2.0
34
 */
35
final class Datepoint
36
{
37
    /**
38
     * @codeCoverageIgnore
39
     */
40
    private function __construct()
41
    {
42
    }
43
44
    /**
45
     * Returns a position in time expressed as a DateTimeImmutable object.
46
     *
47
     * A datepoint can be
48
     * <ul>
49
     * <li>a DateTimeInterface object
50
     * <li>a integer interpreted as a timestamp
51
     * <li>a string parsable by DateTime::__construct
52
     * </ul>
53
     *
54
     * @param mixed $datepoint a position in time
55
     */
56
    public static function create($datepoint): DateTimeImmutable
57
    {
58
        if ($datepoint instanceof DateTimeImmutable) {
59
            return $datepoint;
60
        }
61
62
        if ($datepoint instanceof DateTime) {
63
            return DateTimeImmutable::createFromMutable($datepoint);
64
        }
65
66
        if (false !== ($timestamp = filter_var($datepoint, FILTER_VALIDATE_INT))) {
67
            return new DateTimeImmutable('@'.$timestamp);
68
        }
69
70
        if (is_string($datepoint)) {
71
            return new DateTimeImmutable($datepoint);
72
        }
73
74
        throw new TypeError(sprintf(
75
            'The datepoint must be expressed using an integer, a string or a DateTimeInterface object %s given',
76
            is_object($datepoint) ? get_class($datepoint) : gettype($datepoint)
77
        ));
78
    }
79
}
80