Passed
Push — master ( 5bc16f...da42c3 )
by Marek
36s
created

StringDateNormalizer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 10
c 0
b 0
f 0
wmc 8

1 Method

Rating   Name   Duplication   Size   Complexity  
C normalize() 0 23 8
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) || preg_match('/^\d{1,2}\.? [a-zA-Z]{3} \d{4}$/', $input)) {
34
            return (new \DateTime($input))->format('Y-m-d');
35
        }
36
37
        if (preg_match('/^\d{4}[\-|\/|\.]\d{2}[\-|\/|\.]\d{2}$/', $input)) {
38
            return str_replace('.', '-', $input);
39
        }
40
41
        if (preg_match('/^[a-zA-Z]{3} \d{4}$/', $input)) {
42
            return (new \DateTime($input))->format('Y-m') . '-00';
43
        }
44
45
        if (preg_match('/^\d{4}$/', $input)) {
46
            return $input . '-00-00';
47
        }
48
49
        throw new UnrecognizedDateFormat($input);
50
    }
51
}
52