DateTime   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 45
ccs 18
cts 18
cp 1
rs 10
wmc 11

1 Method

Rating   Name   Duplication   Size   Complexity  
B processDateTime() 0 33 11
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