Completed
Push — master ( 83d4b9...196498 )
by Artem
59s
created

getDatesFromDateRangeAsArrayOfObjects()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 3
nc 2
nop 1
1
<?php
2
/*
3
 * This file is part of the DateTime library.
4
 *
5
 * (c) Artem Henvald <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Fresh\DateTime;
14
15
/**
16
 * DateTimeHelper.
17
 *
18
 * @author Artem Henvald <[email protected]>
19
 */
20
class DateTimeHelper
21
{
22
    private const INTERNAL_DATE_FORMAT = 'Y-m-d';
23
24
    /**
25
     * @param \DateTimeZone|null $timeZone
26
     *
27
     * @return \DateTime
28
     */
29
    public function getCurrentDatetime(?\DateTimeZone $timeZone = null): \DateTime
30
    {
31
        return new \DateTime('now', $timeZone);
32
    }
33
34
    /**
35
     * @param \DateTimeZone|null $timeZone
36
     *
37
     * @return \DateTimeImmutable
38
     */
39
    public function getCurrentDatetimeImmutable(?\DateTimeZone $timeZone = null): \DateTimeImmutable
40
    {
41
        return new \DateTimeImmutable('now', $timeZone);
42
    }
43
44
    /**
45
     * @param DateRange $dateRange
46
     *
47
     * @return \DateTimeImmutable[]
48
     */
49
    public function getDatesFromDateRangeAsArrayOfObjects(DateRange $dateRange): array
50
    {
51
        $datesAsObjects = [];
52
53
        if ($dateRange->getSince()->format(self::INTERNAL_DATE_FORMAT) !== $dateRange->getTill()->format(self::INTERNAL_DATE_FORMAT)) {
54
            $till = new \DateTime('now', $dateRange->getTill()->getTimezone());
55
            $till->setTimestamp($till->getTimestamp());
56
            $till->modify('+1 day'); // Hook to include last day to the period
57
58
            $period = new \DatePeriod($dateRange->getSince(), new \DateInterval('P1D'), $till);
59
60
            /** @var \DateTime $date */
61
            foreach ($period as $date) {
62
                $datesAsObjects[] = $date;
63
            }
64
        } else {
65
            // If since and till dates are equal, then only one date in range
66
            $datesAsObjects[] = $dateRange->getSince();
67
        }
68
69
        return $datesAsObjects;
70
    }
71
72
    /**
73
     * @param DateRange $dateRange
74
     *
75
     * @return string[]
76
     */
77
    public function getDatesFromDateRangeAsArrayOfString(DateRange $dateRange): array
78
    {
79
        $datesAsObjects = $this->getDatesFromDateRangeAsArrayOfObjects($dateRange);
80
81
        $datesAsStrings = [];
82
        foreach ($datesAsObjects as $datesAsObject) {
83
            $datesAsStrings[] = $datesAsObject->format(self::INTERNAL_DATE_FORMAT);
84
        }
85
86
        return $datesAsStrings;
87
    }
88
}
89