1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of RoughDate library. |
5
|
|
|
* |
6
|
|
|
* (c) Marek Matulka <[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 Mareg\RoughDate\Helper; |
15
|
|
|
|
16
|
|
|
use Mareg\RoughDate\RoughDate; |
17
|
|
|
use Mareg\RoughDate\Exception\UnrecognizedDateFormat; |
18
|
|
|
|
19
|
|
|
final class StringDateFormatter |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var string |
23
|
|
|
*/ |
24
|
|
|
private $date; |
25
|
|
|
|
26
|
|
|
private function __construct() {} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $date |
30
|
|
|
* |
31
|
|
|
* @throws UnrecognizedDateFormat |
32
|
|
|
* |
33
|
|
|
* @return StringDateFormatter |
34
|
|
|
*/ |
35
|
|
|
public static function fromString(string $date): StringDateFormatter |
36
|
|
|
{ |
37
|
|
|
self::validateDateFormat($date); |
38
|
|
|
|
39
|
|
|
$stringDateFormatter = new StringDateFormatter(); |
40
|
|
|
$stringDateFormatter->date = $date; |
41
|
|
|
|
42
|
|
|
return $stringDateFormatter; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param string $format |
47
|
|
|
* |
48
|
|
|
* @return string |
49
|
|
|
*/ |
50
|
|
|
public function format(string $format = RoughDate::DEFAULT_DATE_FORMAT): string |
51
|
|
|
{ |
52
|
|
|
if ($format != RoughDate::DEFAULT_DATE_FORMAT) { |
53
|
|
|
return $this->formatDateToString($format); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $this->date; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param string $format |
61
|
|
|
* |
62
|
|
|
* @return string |
63
|
|
|
*/ |
64
|
|
|
private function formatDateToString(string $format): string |
65
|
|
|
{ |
66
|
|
|
$dateParts = explode('-', $this->date); |
67
|
|
|
|
68
|
|
|
if ('00' === $dateParts[1] && '00' === $dateParts[2]) { |
69
|
|
|
$date = \DateTime::createFromFormat('Y', $dateParts[0]); |
70
|
|
|
$format = preg_replace('/[^L|^Y|^y|^ |^\.|^\,]/', '', $format); |
71
|
|
|
} elseif ('00' === $dateParts[2]) { |
72
|
|
|
$date = \DateTime::createFromFormat('Y-m', join('-', array_slice($dateParts, 0, 2))); |
73
|
|
|
$format = preg_replace('/[^F|^m|^M|^n|^t|^L|^Y|^y|^ |^\.|^\,]/', '', $format); |
74
|
|
|
} else { |
75
|
|
|
$date = \DateTime::createFromFormat(RoughDate::DEFAULT_DATE_FORMAT, $this->date); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $date->format($format); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @param string $date |
83
|
|
|
* |
84
|
|
|
* @throws UnrecognizedDateFormat |
85
|
|
|
*/ |
86
|
|
|
private static function validateDateFormat(string $date) |
87
|
|
|
{ |
88
|
|
|
if (!preg_match('/^\d{4}[\-|\/]\d{2}[\-|\/]\d{2}$/', $date)) { |
89
|
|
|
throw new UnrecognizedDateFormat($date); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|