|
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\Exception\UnrecognizedDateFormat; |
|
17
|
|
|
|
|
18
|
|
|
final class StringDateNormalizer |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @param string $input |
|
22
|
|
|
* |
|
23
|
|
|
* @throws UnrecognizedDateFormat |
|
24
|
|
|
* |
|
25
|
|
|
* @return string |
|
26
|
|
|
*/ |
|
27
|
|
|
public function normalize(string $input): string |
|
28
|
|
|
{ |
|
29
|
|
|
if (preg_match('/^\d{4}[\-][0]{2}[\-][0]{2}$/', $input) || preg_match('/^\d{4}[\-]\d{2}[\-][0]{2}$/', $input)) { |
|
30
|
|
|
return $input; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
if (preg_match('/^\d{4}[\-|\/]\d{2}[\-|\/]\d{2}$/', $input) || |
|
34
|
|
|
preg_match('/^\d{1,2}\.? [a-zA-Z]{3,} \d{4}$/', $input) || |
|
35
|
|
|
preg_match('/^[a-zA-Z]{3,} \d{1,2}, \d{4}$/', $input) |
|
36
|
|
|
) { |
|
37
|
|
|
return (new \DateTime($input))->format('Y-m-d'); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
if (preg_match('/^\d{4}[\-|\/|\.]\d{2}[\-|\/|\.]\d{2}$/', $input)) { |
|
41
|
|
|
return str_replace('.', '-', $input); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (preg_match('/^\d{4}[\-|\/|\.]\d{2}$/', $input)) { |
|
45
|
|
|
return str_replace('/', '-', str_replace('.', '-', $input)) . '-00'; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
if (preg_match('/^[A-Z][a-z]* \d{4}$/', $input)) { |
|
49
|
|
|
return (new \DateTime($input))->format('Y-m') . '-00'; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
if (preg_match('/^\d{4}$/', $input)) { |
|
53
|
|
|
return $input . '-00-00'; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
throw new UnrecognizedDateFormat($input); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|