StringDateNormalizer::normalize()   B
last analyzed

Complexity

Conditions 10
Paths 7

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 15
c 2
b 0
f 0
dl 0
loc 30
rs 7.6666
cc 10
nc 7
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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