Passed
Push — master ( 176280...4c9570 )
by Xavier
01:42
created

DateHelper   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 13
dl 0
loc 61
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A countObjectParts() 0 5 2
A dateFromDateParts() 0 9 2
A dateFromPubDate() 0 13 4
A dateFromParseableFormat() 0 3 1
A getPubDateMonth() 0 9 3
A formatForParts() 0 9 1
1
<?php
2
3
namespace PubPeerFoundation\PublicationDataExtractor\Support;
4
5
use Carbon\Carbon;
6
7
class DateHelper
8
{
9
    public static function dateFromDateParts(array $parts)
10
    {
11
        if (empty($parts)) {
12
            return '';
13
        }
14
15
        return static::formatForParts(
16
            Carbon::createFromDate(...array_merge($parts, [1, 1, 1])),
0 ignored issues
show
Bug introduced by
array_merge($parts, array(1, 1, 1)) is expanded, but the parameter $year of Carbon\Carbon::createFromDate() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

16
            Carbon::createFromDate(/** @scrutinizer ignore-type */ ...array_merge($parts, [1, 1, 1])),
Loading history...
17
            count($parts)
18
        );
19
    }
20
21
    public static function dateFromParseableFormat($formattedDate)
22
    {
23
        return Carbon::parse($formattedDate)->format('Y-m-d');
24
    }
25
26
    public static function dateFromPubDate($pubDateObject)
27
    {
28
        if (! isset($pubDateObject->Year) || empty($pubDateObject->Year)) {
29
            return '';
30
        }
31
32
        $month = static::getPubDateMonth($pubDateObject);
33
34
        return static::formatForParts(Carbon::create(
35
            (int) $pubDateObject->Year,
36
            (int) $month,
37
            isset($pubDateObject->Day) ? (int) $pubDateObject->Day : 1
38
        ), static::countObjectParts($pubDateObject));
39
    }
40
41
    protected static function getPubDateMonth($pubDateObject)
42
    {
43
        if (! isset($pubDateObject->Month)) {
44
            return 1;
45
        }
46
47
        return ! is_numeric((string) $pubDateObject->Month)
48
            ? Carbon::createFromFormat('M', (string) $pubDateObject->Month)->format('n')
49
            : $pubDateObject->Month;
50
    }
51
52
    protected static function formatForParts($date, $count)
53
    {
54
        $partsToFormat = [
55
            1 => 'Y',
56
            2 => 'Y-m',
57
            3 => 'Y-m-d',
58
        ];
59
60
        return $date->format($partsToFormat[$count]);
61
    }
62
63
    protected static function countObjectParts($pubDateObject)
64
    {
65
        return array_reduce(['Year', 'Month', 'Day'], function ($carry, $datePart) use ($pubDateObject) {
66
            return isset($pubDateObject->$datePart) ? $carry + 1 : $carry;
67
        }, 0);
68
    }
69
}
70