Passed
Push — master ( 9179ab...b51dc7 )
by Marcel
02:24
created

StorageService::deleteSimulate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 3
rs 10
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\StorageMapper;
15
use OCP\IRequest;
16
use Psr\Log\LoggerInterface;
17
18
class StorageService
19
{
20
    private $logger;
21
    private $StorageMapper;
22
    private $ThresholdService;
23
    private $DatasetService;
24
25
    public function __construct(
26
        LoggerInterface $logger,
27
        StorageMapper $StorageMapper,
28
        DatasetService $DatasetService,
29
        ThresholdService $ThresholdService
30
    )
31
    {
32
        $this->logger = $logger;
33
        $this->StorageMapper = $StorageMapper;
34
        $this->DatasetService = $DatasetService;
35
        $this->ThresholdService = $ThresholdService;
36
    }
37
38
    /**
39
     * Get the items for the selected category
40
     *
41
     * @NoAdminRequired
42
     * @param $datasetId
43
     * @param $options
44
     * @return array
45
     * @throws \OCP\DB\Exception
46
     */
47
    public function read($datasetId, $options)
48
    {
49
        $availableDimensions = array();
50
        $header = array();
51
        $datasetMetadata = $this->DatasetService->read($datasetId);
52
53
        if (!empty($datasetMetadata)) {
54
            $this->logger->error('dataset: '.$datasetMetadata);
0 ignored issues
show
Bug introduced by
Are you sure $datasetMetadata of type array|boolean can be used in concatenation? ( Ignorable by Annotation )

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

54
            $this->logger->error('dataset: './** @scrutinizer ignore-type */ $datasetMetadata);
Loading history...
55
56
            // output the dimensions available for filtering of this dataset
57
            // this needs to map the technical name to its display name in the report
58
            $availableDimensions['dimension1'] = $datasetMetadata['dimension1'];
59
            $availableDimensions['dimension2'] = $datasetMetadata['dimension2'];
60
61
            // return the header texts of the data being transferred according to the current drilldown state selected by user
62
            $options = json_decode($options, true);
63
            if (!isset($options['drilldown']['dimension1'])) $header[0] = $datasetMetadata['dimension1'];
64
            if (!isset($options['drilldown']['dimension2'])) $header[1] = $datasetMetadata['dimension2'];
65
            $header[6] = $datasetMetadata['value'];
66
            $header = array_values($header);
67
68
            $data = $this->StorageMapper->read($datasetMetadata['id'], $options);
69
            $data = array_values($data);
70
            foreach ($data as $key => $value) {
71
                $data[$key] = array_values($value);
72
            }
73
        }
74
75
        return empty($data) ? [
76
            'dimensions' => $availableDimensions,
77
            'status' => 'nodata',
78
            'error' => 0
79
        ] : [
80
            'header' => $header,
81
            'dimensions' => $availableDimensions,
82
            'data' => $data,
83
            'error' => 0
84
        ];
85
    }
86
87
    /**
88
     * Get the items for the selected category
89
     *
90
     * @NoAdminRequired
91
     * @param int $datasetId
92
     * @param $dimension1
93
     * @param $dimension2
94
     * @param $value
95
     * @param string|null $user_id
96
     * @param $bulkInsert
97
     * @return array
98
     * @throws \Exception
99
     */
100
    public function update(int $datasetId, $dimension1, $dimension2, $value, string $user_id = null, $bulkInsert = null)
101
    {
102
        TODO:
103
        //dates in both columns
104
        $dimension2 = $this->convertGermanDateFormat($dimension2);
105
        //convert date into timestamp
106
        //$timestamp = $this->convertGermanDateFormat($timestamp);
107
        $value = $this->floatvalue($value);
108
        $validate = '';
109
        $insert = $update = $error = $action = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $action is dead and can be removed.
Loading history...
110
111
        if ($value !== false) {
112
            try {
113
                $action = $this->StorageMapper->create($datasetId, $dimension1, $dimension2, $value, $user_id, null, $bulkInsert);
114
            } catch (\Exception $e) {
115
                $error = 1;
116
            }
117
            if ($action === 'insert') $insert = 1;
118
            elseif ($action === 'update') $update = 1;
119
        } else {
120
            $error = 1;
121
        }
122
123
        if ($error === 0) $validate = $this->ThresholdService->validate($datasetId, $dimension1, $dimension2, $value);
124
125
        return [
126
            'insert' => $insert,
127
            'update' => $update,
128
            'error' => $error,
129
            'validate' => $validate
130
        ];
131
    }
132
133
    /**
134
     * delete data
135
     *
136
     * @NoAdminRequired
137
     * @param int $datasetId
138
     * @param $dimension1
139
     * @param $dimension2
140
     * @return bool
141
     */
142
    public function delete(int $datasetId, $dimension1, $dimension2, string $user_id = null)
143
    {
144
        return $this->StorageMapper->delete($datasetId, $dimension1, $dimension2, $user_id);
145
    }
146
147
    /**
148
     * Simulate delete data
149
     *
150
     * @NoAdminRequired
151
     * @param int $datasetId
152
     * @param $dimension1
153
     * @param $dimension2
154
     * @return array
155
     */
156
    public function deleteSimulate(int $datasetId, $dimension1, $dimension2)
157
    {
158
        return $this->StorageMapper->deleteSimulate($datasetId, $dimension1, $dimension2);
159
    }
160
161
    private function floatvalue($val)
162
    {
163
        $val = str_replace(",", ".", $val);
164
        $val = preg_replace('/\.(?=.*\.)/', '', $val);
165
        $val = preg_replace('/[^0-9-.]+/', '', $val);
166
        if (is_numeric($val)) {
167
            return number_format(floatval($val), 2, '.', '');
168
        } else {
169
            return false;
170
        }
171
    }
172
173
    private function convertGermanDateFormat($val)
174
    {
175
        $fullString = explode(' ', $val);
176
        $dateLength = strlen($fullString[0]);
177
        $dateParts = explode('.', $fullString[0]);
178
179
        if ($dateLength >= 6 && $dateLength <= 10 && count($dateParts) === 3) {
180
            // is most likely a german date format 20.02.2020
181
            $fullString[0] = $dateParts[2] . '-' . sprintf('%02d', $dateParts[1]) . '-' . sprintf('%02d', $dateParts[0]);
182
            $val = implode(' ', $fullString);
183
        }
184
        return $val;
185
    }
186
}