GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

TimePeriodDataFetcher::fetch()   F
last analyzed

Complexity

Conditions 15
Paths 880

Size

Total Lines 68
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 43
c 0
b 0
f 0
nc 880
nop 1
dl 0
loc 68
rs 1.9166

How to fix   Long Method    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
namespace Odiseo\SyliusReportPlugin\DataFetcher;
6
7
use DateInterval;
8
use DateTime;
9
use Exception;
10
use InvalidArgumentException;
11
12
/**
13
 * Abstract class to provide time periods logic.
14
 *
15
 * @author Łukasz Chruściel <[email protected]>
16
 * @author Diego D'amico <[email protected]>
17
 */
18
abstract class TimePeriodDataFetcher extends BaseDataFetcher
19
{
20
    const PERIOD_DAY = 'day';
21
    const PERIOD_MONTH = 'month';
22
    const PERIOD_YEAR = 'year';
23
24
    public static function getPeriodChoices(): array
25
    {
26
        return [
27
            'odiseo_sylius_report.ui.daily' => self::PERIOD_DAY,
28
            'odiseo_sylius_report.ui.monthly' => self::PERIOD_MONTH,
29
            'odiseo_sylius_report.ui.yearly' => self::PERIOD_YEAR,
30
        ];
31
    }
32
33
    /**
34
     * @throws Exception
35
     */
36
    public function fetch(array $configuration): Data
37
    {
38
        $data = new Data();
39
40
        /** @var DateTime|null $endDate */
41
        $endDate = isset($configuration['timePeriod']['end']) ? $configuration['timePeriod']['end'] : null;
42
43
        //There is added 23 hours 59 minutes 59 seconds to the end date to provide records for whole end date
44
        $configuration['timePeriod']['end'] = $endDate !== null ? $endDate->add(new DateInterval('PT23H59M59S')) : null;
45
46
        switch ($configuration['timePeriod']['period']) {
47
            case self::PERIOD_DAY:
48
                $this->setExtraConfiguration($configuration, 'P1D', '%a', 'Y-m-d', ['date']);
49
                break;
50
            case self::PERIOD_MONTH:
51
                $this->setExtraConfiguration($configuration, 'P1M', '%m', 'F Y', ['month', 'year']);
52
                break;
53
            case self::PERIOD_YEAR:
54
                $this->setExtraConfiguration($configuration, 'P1Y', '%y', 'Y', ['year']);
55
                break;
56
            default:
57
                throw new InvalidArgumentException('Wrong data fetcher period');
58
        }
59
60
        $rawData = $this->getData($configuration);
61
62
        if ([] === $rawData) {
63
            return $data;
64
        }
65
66
        $labelsAux = array_keys($rawData[0]);
67
        $labels = [];
68
        foreach ($labelsAux as $label) {
69
            if (!in_array($label, ['MonthDate', 'YearDate', 'DateDate'], true)) {
70
                $labels[] = $label;
71
            }
72
        }
73
        $data->setLabels($labels);
74
75
        $fetched = [];
76
77
        if ($configuration['empty_records']) {
78
            $fetched = $this->fillEmptyRecords($fetched, $configuration);
79
        }
80
        foreach ($rawData as $row) {
81
            $rowFetched = [];
82
            foreach ($labels as $i => $label) {
83
                if ($i === 0) {
84
                    $date = new DateTime($row[$labels[0]]);
85
                    $rowFetched[] = $date->format($configuration['timePeriod']['presentationFormat']);
86
                } else {
87
                    $rowFetched[] = $row[$labels[$i]];
88
                }
89
            }
90
            $fetched[] = $rowFetched;
91
        }
92
93
        $data->setData($fetched);
94
95
        $labels = [];
96
        foreach ($labelsAux as $label) {
97
            if (!in_array($label, ['MonthDate', 'YearDate', 'DateDate'], true)) {
98
                $labels[] = preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', ' $0', (string)$label);
99
            }
100
        }
101
        $data->setLabels($labels);
102
103
        return $data;
104
    }
105
106
    protected function setExtraConfiguration(
107
        array &$configuration,
108
        string $interval,
109
        string $periodFormat,
110
        string $presentationFormat,
111
        array $groupBy
112
    ): void {
113
        $configuration['timePeriod']['interval'] = $interval;
114
        $configuration['timePeriod']['periodFormat'] = $periodFormat;
115
        $configuration['timePeriod']['presentationFormat'] = $presentationFormat;
116
        $configuration['groupBy'] = $groupBy;
117
        $configuration['empty_records'] = false;
118
    }
119
120
    private function fillEmptyRecords(array $fetched, array $configuration): array
121
    {
122
        /** @var DateTime $startDate */
123
        $startDate = $configuration['start'];
124
        /** @var DateTime $startDate */
125
        $endDate = $configuration['end'];
126
127
        try {
128
            $dateInterval = new DateInterval($configuration['interval']);
129
        } catch (Exception $e) {
130
            return $fetched;
131
        }
132
133
        $numberOfPeriods = $startDate->diff($endDate);
134
        $formattedNumberOfPeriods = $numberOfPeriods->format($configuration['periodFormat']);
135
136
        for ($i = 0; $i <= $formattedNumberOfPeriods; ++$i) {
137
            $fetched[$startDate->format($configuration['presentationFormat'])] = 0;
138
            $startDate = $startDate->add($dateInterval);
139
        }
140
141
        return $fetched;
142
    }
143
}
144