|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ddeboer\DataImport\ValueConverter; |
|
4
|
|
|
|
|
5
|
|
|
use \Ddeboer\DataImport\Exception\UnexpectedValueException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Convert an date string into another date string |
|
9
|
|
|
* Eg. You want to change the format of a string OR |
|
10
|
|
|
* If no output specified, return DateTime instance |
|
11
|
|
|
* |
|
12
|
|
|
* @author David de Boer <[email protected]> |
|
13
|
|
|
*/ |
|
14
|
|
|
class DateTimeValueConverter |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Date time format |
|
18
|
|
|
* |
|
19
|
|
|
* @var string |
|
20
|
|
|
* |
|
21
|
|
|
* @see http://php.net/manual/en/datetime.createfromformat.php |
|
22
|
|
|
*/ |
|
23
|
|
|
protected $inputFormat; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Date time format |
|
27
|
|
|
* |
|
28
|
|
|
* @var string |
|
29
|
|
|
* |
|
30
|
|
|
* @see http://php.net/manual/en/datetime.createfromformat.php |
|
31
|
|
|
*/ |
|
32
|
|
|
protected $outputFormat; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param string $inputFormat |
|
36
|
|
|
* @param string $outputFormat |
|
37
|
|
|
*/ |
|
38
|
9 |
|
public function __construct($inputFormat = null, $outputFormat = null) |
|
39
|
|
|
{ |
|
40
|
9 |
|
$this->inputFormat = $inputFormat; |
|
41
|
9 |
|
$this->outputFormat = $outputFormat; |
|
42
|
9 |
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Convert string to date time object then convert back to a string |
|
46
|
|
|
* using specified format |
|
47
|
|
|
* |
|
48
|
|
|
* If no output format specified then return |
|
49
|
|
|
* the \DateTime instance |
|
50
|
|
|
* |
|
51
|
|
|
* @param mixed $input |
|
52
|
|
|
* @return \DateTime|string |
|
53
|
|
|
* @throws UnexpectedValueException |
|
54
|
|
|
*/ |
|
55
|
8 |
|
public function __invoke($input) |
|
56
|
|
|
{ |
|
57
|
8 |
|
if (!$input) { |
|
58
|
1 |
|
return; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
7 |
|
if ($this->inputFormat) { |
|
62
|
3 |
|
$date = \DateTime::createFromFormat($this->inputFormat, $input); |
|
63
|
3 |
|
if (false === $date) { |
|
64
|
1 |
|
throw new UnexpectedValueException( |
|
65
|
1 |
|
$input . ' is not a valid date/time according to format ' . $this->inputFormat |
|
66
|
1 |
|
); |
|
67
|
|
|
} |
|
68
|
2 |
|
} else { |
|
69
|
4 |
|
$date = new \DateTime($input); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
6 |
|
if ($this->outputFormat) { |
|
73
|
2 |
|
return $date->format($this->outputFormat); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
//if no output format specified we just return the \DateTime instance |
|
77
|
4 |
|
return $date; |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|