1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @package: chapi |
4
|
|
|
* |
5
|
|
|
* @author: msiebeneicher |
6
|
|
|
* @since: 2015-07-31 |
7
|
|
|
* |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Chapi\Component\DatePeriod; |
11
|
|
|
|
12
|
|
|
use Chapi\Entity\DatePeriod\Iso8601Entity; |
13
|
|
|
use Chapi\Exception\DatePeriodException; |
14
|
|
|
|
15
|
|
|
class DatePeriodFactory implements DatePeriodFactoryInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var Iso8601Entity[] |
19
|
|
|
*/ |
20
|
|
|
private static $iso8601Entity = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param string $iso8601 |
24
|
|
|
* @return Iso8601Entity |
25
|
|
|
* @throws DatePeriodException |
26
|
|
|
*/ |
27
|
9 |
|
public function createIso8601Entity($iso8601) |
28
|
|
|
{ |
29
|
9 |
|
$key = md5($iso8601); // class cache key |
30
|
|
|
|
31
|
|
|
// return instance |
32
|
9 |
|
if (isset(self::$iso8601Entity[$key])) { |
33
|
4 |
|
return self::$iso8601Entity[$key]; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
// init instance |
37
|
|
|
try { |
38
|
6 |
|
return self::$iso8601Entity[$key] = new Iso8601Entity($iso8601); |
39
|
2 |
|
} catch (\InvalidArgumentException $exception) { |
40
|
2 |
|
throw new DatePeriodException(sprintf("Can't init Iso8601Entity for '%s' iso 8601 string.", $iso8601), 1, $exception); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param $iso8601 |
46
|
|
|
* @param string $timezone |
47
|
|
|
* @return \DatePeriod |
48
|
|
|
*/ |
49
|
4 |
|
public function createDatePeriod($iso8601, $timezone = '') |
50
|
|
|
{ |
51
|
4 |
|
$iso8601Entity = $this->createIso8601Entity($iso8601); |
52
|
|
|
|
53
|
3 |
View Code Duplication |
if (!empty($timezone)) { |
54
|
2 |
|
$dateStart = new \DateTime(str_replace('Z', '', $iso8601Entity->startTime), new \DateTimeZone($timezone)); |
55
|
|
|
} else { |
56
|
|
|
// todo: use a defined chronos time zone here? |
57
|
2 |
|
$dateStart = new \DateTime($iso8601Entity->startTime); |
58
|
|
|
} |
59
|
|
|
|
60
|
3 |
|
$dateInterval = new \DateInterval($iso8601Entity->interval); |
61
|
3 |
|
$dateEnd = new \DateTime(); |
62
|
|
|
|
63
|
3 |
|
$dateStart->sub($dateInterval); |
64
|
3 |
|
$dateEnd->add($dateInterval); |
65
|
|
|
|
66
|
3 |
|
return new \DatePeriod($dateStart, $dateInterval, $dateEnd); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|