DateTime::processDateTime()   B
last analyzed

Complexity

Conditions 11
Paths 28

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 11

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 20
c 1
b 0
f 0
nc 28
nop 2
dl 0
loc 33
ccs 18
cts 18
cp 1
crap 11
rs 7.3166

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
declare(strict_types=1);
4
5
/**
6
 * This file is part of Wszetko Sitemap.
7
 *
8
 * (c) Paweł Kłopotek-Główczewski <[email protected]>
9
 *
10
 * This source file is subject to the MIT license that is bundled
11
 * with this source code in the file LICENSE.
12
 */
13
14
namespace Wszetko\Sitemap\Traits;
15
16
use DateTimeInterface;
17
use InvalidArgumentException;
18
19
/**
20
 * Trait DateTime.
21
 *
22
 * @package Wszetko\Sitemap\Traits
23
 */
24
trait DateTime
25
{
26
    /**
27
     * Get date and format it to proper format. Throws exceptions if is not valid date and is required.
28
     *
29
     * @param DateTimeInterface|string $dateTime
30
     * @param bool                     $required
31
     *
32
     * @return null|string
33
     *
34
     * @throws \InvalidArgumentException
35
     */
36 82
    private function processDateTime($dateTime, $required = false): ?string
37
    {
38 82
        if (is_string($dateTime)) {
39 18
            $dateTime = date_create($dateTime);
40
        }
41
42
        if (
43 82
            ($dateTime instanceof DateTimeInterface
44 74
            && (int) $dateTime->format('Y') <= 0)
45 82
            || false === $dateTime
46
        ) {
47 6
            $dateTime = null;
48
        }
49
50 82
        if ($dateTime instanceof DateTimeInterface) {
51
            if (
52 70
                0 == $dateTime->format('H') &&
53 70
                0 == $dateTime->format('i') &&
54 70
                0 == $dateTime->format('s')
55
            ) {
56 66
                $dateTime = $dateTime->format('Y-m-d');
57
            } else {
58 70
                $dateTime = $dateTime->format(\DateTime::W3C);
59
            }
60 12
        } elseif ($required) {
61 4
            throw new InvalidArgumentException('Invalid date parameter.');
62
        }
63
64 78
        if (!is_string($dateTime)) {
65 8
            $dateTime = null;
66
        }
67
68 78
        return $dateTime;
69
    }
70
}
71