Passed
Push — master ( 4c07a1...a9aa4a )
by Marcel
03:21 queued 12s
created

VariableService   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 165
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 85
c 4
b 0
f 0
dl 0
loc 165
rs 10
wmc 27

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
B replaceTextVariables() 0 31 11
B parseFilter() 0 65 9
A parseFormat() 0 6 2
A replaceFilterVariables() 0 15 4
1
<?php
2
/**
3
 * Analytics
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the LICENSE.md file.
7
 *
8
 * @author Marcel Scherello <[email protected]>
9
 * @copyright 2021 Marcel Scherello
10
 */
11
12
namespace OCA\Analytics\Service;
13
14
use OCA\Analytics\Db\DatasetMapper;
15
use OCP\IDateTimeFormatter;
16
use Psr\Log\LoggerInterface;
17
18
class VariableService
19
{
20
    private $logger;
21
    private $DatasetMapper;
22
    private $IDateTimeFormatter;
23
24
    public function __construct(
25
        LoggerInterface $logger,
26
        DatasetMapper $DatasetMapper,
27
        IDateTimeFormatter $IDateTimeFormatter
28
    )
29
    {
30
        $this->logger = $logger;
31
        $this->DatasetMapper = $DatasetMapper;
32
        $this->IDateTimeFormatter = $IDateTimeFormatter;
33
    }
34
35
    /**
36
     * replace %*% text variables in name and subheader
37
     *
38
     * @param array $datasetMetadata
39
     * @return array
40
     */
41
    public function replaceTextVariables($datasetMetadata)
42
    {
43
        $fields = ['name', 'subheader'];
44
        foreach ($fields as $field) {
45
            isset($datasetMetadata[$field]) ? $name = $datasetMetadata[$field] : $name = '';
46
47
            preg_match_all("/%.*?%/", $name, $matches);
48
            if (count($matches[0]) > 0) {
49
                foreach ($matches[0] as $match) {
50
                    $replace = null;
51
                    if ($match === '%currentDate%') {
52
                        $replace = $this->IDateTimeFormatter->formatDate(time(), 'short');
53
                    } elseif ($match === '%currentTime%') {
54
                        $replace = $this->IDateTimeFormatter->formatTime(time(), 'short');
55
                    } elseif ($match === '%lastUpdateDate%') {
56
                        $timestamp = $this->DatasetMapper->getLastUpdate($datasetMetadata['dataset']);
57
                        $replace = $this->IDateTimeFormatter->formatDate($timestamp, 'short');
58
                    } elseif ($match === '%lastUpdateTime%') {
59
                        $timestamp = $this->DatasetMapper->getLastUpdate($datasetMetadata['dataset']);
60
                        $replace = $this->IDateTimeFormatter->formatTime($timestamp, 'short');
61
                    } elseif ($match === '%owner%') {
62
                        $owner = $this->DatasetMapper->getOwner($datasetMetadata['dataset']);
63
                        $replace = $owner;
64
                    }
65
                    if ($replace !== null) {
66
                        $datasetMetadata[$field] = preg_replace('/' . $match . '/', $replace, $datasetMetadata[$field]);
67
                    }
68
                }
69
            }
70
        }
71
        return $datasetMetadata;
72
    }
73
74
    /**
75
     * replace variables in filters and apply format
76
     *
77
     * @param $reportMetadata
78
     * @return array
79
     */
80
    public function replaceFilterVariables($reportMetadata)
81
    {
82
        $filteroptions = json_decode($reportMetadata['filteroptions'], true);
83
        if (isset($filteroptions['filter'])) {
84
            foreach ($filteroptions['filter'] as $key => $value) {
85
                $parsed = $this->parseFilter($value['value'], $value['option']);
86
                $format = $this->parseFormat($value['value']);
87
88
                if (!$parsed) break;
89
                $filteroptions['filter'][$key]['option'] = $parsed['option'];
90
                $filteroptions['filter'][$key]['value'] = date($format, $parsed['value']);
91
            }
92
        }
93
        $reportMetadata['filteroptions'] = json_encode($filteroptions);
94
        return $reportMetadata;
95
    }
96
97
    /**
98
     * parsing of %*% variables
99
     *
100
     * @param $filter
101
     * @param $option
102
     * @return array|bool
103
     */
104
    private function parseFilter($filter, $option) {
105
        preg_match_all("/(?<=%).*(?=%)/", $filter, $matches);
106
        if (count($matches[0]) > 0) {
107
            $filter = $matches[0][0];
108
            preg_match('/(last|next|current|to|yester)?/', $filter, $directionMatch);
109
            preg_match('/[0-9]+/', $filter, $offsetMatch);
110
            preg_match('/(day|days|week|weeks|month|months|year|years)$/', $filter, $unitMatch);
111
112
            if (!$directionMatch[0] || !$unitMatch[0]) {
113
                return false;
114
            }
115
116
            !$offsetMatch[0] ? $offset = 1: $offset = $offsetMatch[0];
117
118
            // remove s to unify e.g. weeks => week
119
            $unit = rtrim($unitMatch[0], 's');
120
121
            if ($directionMatch[0] === "last" || $directionMatch[0] === "yester") {
122
                $direction = '-';
123
                //$directionWord = $directionMatch[0];
124
            } elseif ($directionMatch[0] === "next") {
125
                $direction = '+';
126
                //$directionWord = $directionMatch[0];
127
            } else { // current
128
                $direction = '+';
129
                $offset = 0;
130
                //$directionWord = 'this';
131
            }
132
133
            $timestring = $direction . $offset . ' ' . $unit;
134
            $baseDate = strtotime($timestring);
135
136
            if ($unit === 'day') {
137
                $startString = 'today';
138
                //$endString = 'yesterday';
139
            } else {
140
                $startString = 'first day of this ' . $unit;
141
                //$endString = 'last day of ' . $directionWord . ' ' . $unit;
142
            }
143
            $startTS = strtotime($startString, $baseDate);
144
            $start = date("Y-m-d", $startTS);
145
            //$endTS = strtotime($endString);
146
            //$end = date("Y-m-d", $endTS);
147
148
            $return = [
149
                'value' => $startTS,
150
                'option' => 'GT',
151
                '1$filter' => $filter,
152
                '2$timestring' => $timestring,
153
                '3$target' => $baseDate,
154
                '4$target_clean' => date("Y-m-d", $baseDate),
155
                '5$startString' => $startString,
156
                '6$startDate' => $start,
157
                '7$startTS' => $startTS,
158
                //'8$endString' => $endString,
159
                //'9$endDate' => $end,
160
                //'9$endTS' => $endTS,
161
           ];
162
        } else {
163
            $return = [
164
                'value' => $filter,
165
                'option' => $option
166
            ];
167
        }
168
        return $return;
169
    }
170
171
    /**
172
     * parsing of ( ) format instructions
173
     *
174
     * @param $filter
175
     * @return string
176
     */
177
    private function parseFormat($filter) {
178
        preg_match_all("/(?<=\().*(?=\))/", $filter, $matches);
179
        if (count($matches[0]) > 0) {
180
            return $matches[0][0];
181
        } else {
182
            return 'Y-m-d H:m:s';
183
        }
184
    }
185
}