Passed
Push — master ( b84320...92b80c )
by Marcel
02:37
created

DatasetService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 10
c 2
b 0
f 0
nc 1
nop 10
dl 0
loc 23
rs 9.9332

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\Activity\ActivityManager;
15
use OCA\Analytics\Controller\DatasourceController;
16
use OCA\Analytics\Db\DataloadMapper;
17
use OCA\Analytics\Db\DatasetMapper;
18
use OCA\Analytics\Db\StorageMapper;
19
use OCP\AppFramework\Http\DataDownloadResponse;
20
use OCP\AppFramework\Http\DataResponse;
21
use OCP\Files\IRootFolder;
22
use OCP\ILogger;
23
use OCP\ITagManager;
24
25
class DatasetService
26
{
27
    private $userId;
28
    private $logger;
29
    private $tagManager;
30
    private $ShareService;
31
    private $StorageMapper;
32
    private $DatasetMapper;
33
    private $ThresholdService;
34
    private $DataloadMapper;
35
    private $ActivityManager;
36
    private $rootFolder;
37
38
    public function __construct(
39
        $userId,
40
        ILogger $logger,
41
        ITagManager $tagManager,
42
        ShareService $ShareService,
43
        StorageMapper $StorageMapper,
44
        DatasetMapper $DatasetMapper,
45
        ThresholdService $ThresholdService,
46
        DataloadMapper $DataloadMapper,
47
        ActivityManager $ActivityManager,
48
        IRootFolder $rootFolder
49
    )
50
    {
51
        $this->userId = $userId;
52
        $this->logger = $logger;
53
        $this->tagManager = $tagManager;
54
        $this->ShareService = $ShareService;
55
        $this->ThresholdService = $ThresholdService;
56
        $this->StorageMapper = $StorageMapper;
57
        $this->DatasetMapper = $DatasetMapper;
58
        $this->DataloadMapper = $DataloadMapper;
59
        $this->ActivityManager = $ActivityManager;
60
        $this->rootFolder = $rootFolder;
61
    }
62
63
    /**
64
     * get all datasets
65
     *
66
     * @return DataResponse
67
     */
68
    public function index()
69
    {
70
        $ownDatasets = $this->DatasetMapper->index();
71
72
        // get dataload indicators for icons shown in the advanced screen
73
        $dataloads = $this->DataloadMapper->getAllDataloadMetadata();
74
        foreach ($dataloads as $dataload) {
75
            $key = array_search($dataload['dataset'], array_column($ownDatasets, 'id'));
76
            if ($key !== '') {
77
                if ($dataload['schedules'] !== '' and $dataload['schedules'] !== null) {
78
                    $dataload['schedules'] = 1;
79
                } else {
80
                    $dataload['schedules'] = 0;
81
                }
82
                $ownDatasets[$key]['dataloads'] = $dataload['dataloads'];
83
                $ownDatasets[$key]['schedules'] = $dataload['schedules'];
84
            }
85
        }
86
87
        // get shared datasets and remove doublicates
88
        $sharedDatasets = $this->ShareService->getSharedDatasets();
89
        foreach ($sharedDatasets as $sharedDataset) {
90
            if (!array_search($sharedDataset['id'], array_column($ownDatasets, 'id'))) {
91
                $sharedDataset['type'] = '99';
92
                $sharedDataset['parrent'] = '0';
93
                array_push($ownDatasets, $sharedDataset);
94
            }
95
        }
96
97
        $favorites = $this->tagManager->load('analytics')->getFavorites();
98
        foreach ($ownDatasets as &$ownDataset) {
99
            $hasTag = 0;
100
            if (is_array($favorites) and in_array($ownDataset['id'], $favorites)) {
101
                $hasTag = 1;
102
            }
103
            $ownDataset['favorite'] = $hasTag;
104
        }
105
106
        return new DataResponse($ownDatasets);
107
    }
108
109
    /**
110
     * get own dataset details
111
     *
112
     * @param int $datasetId
113
     * @return array
114
     */
115
    public function read(int $datasetId)
116
    {
117
        return $this->getOwnDataset($datasetId);
118
    }
119
120
    /**
121
     * get own dataset details
122
     *
123
     * @param int $datasetId
124
     * @param string|null $user_id
125
     * @return array
126
     */
127
    public function getOwnDataset(int $datasetId, string $user_id = null)
128
    {
129
        $ownDataset = $this->DatasetMapper->read($datasetId, $user_id);
130
        if (!empty($ownDataset)) {
131
            $ownDataset['permissions'] = \OCP\Constants::PERMISSION_UPDATE;
132
        }
133
        return $ownDataset;
134
    }
135
136
    /**
137
     * get own datasets which are marked as favorites
138
     *
139
     * @return array|bool
140
     */
141
    public function getOwnFavoriteDatasets()
142
    {
143
        $ownDatasets = $this->DatasetMapper->index();
144
        $favorits = $this->tagManager->load('analytics')->getFavorites();
145
        $sharedDatasets = $this->ShareService->getSharedDatasets();
146
147
        foreach ($favorits as $favorite) {
148
            if (!array_search($favorite, array_column($ownDatasets, 'id'))
149
                && !array_search($favorite, array_column($sharedDatasets, 'id'))) {
150
                unset($favorits[$favorite]);
151
                $this->tagManager->load('analytics')->removeFromFavorites($favorite);
152
            }
153
        }
154
155
        return $favorits;
156
    }
157
158
    /**
159
     * create new dataset
160
     *
161
     * @param string $file
162
     * @return int
163
     */
164
    public function create($file = '')
165
    {
166
        $this->ActivityManager->triggerEvent(0, ActivityManager::OBJECT_DATASET, ActivityManager::SUBJECT_DATASET_ADD);
167
        $datasetId = $this->DatasetMapper->create();
168
169
        if ($file !== '') {
170
            $name = explode('.', end(explode('/', $file)))[0];
171
            $subheader = $file;
172
            $parent = 0;
173
            $type = DatasourceController::DATASET_TYPE_FILE;
174
            $link = $file;
175
            $visualization = 'table';
176
            $chart = 'line';
177
            $this->update($datasetId, $name, $subheader, $parent, $type, $link, $visualization, $chart, '', '');
178
        }
179
        return $datasetId;
180
    }
181
182
    /**
183
     * get dataset details
184
     *
185
     * @param int $datasetId
186
     * @param $name
187
     * @param $subheader
188
     * @param int $parent
189
     * @param int $type
190
     * @param $link
191
     * @param $visualization
192
     * @param $chart
193
     * @param $chartoptions
194
     * @param $dataoptions
195
     * @param $dimension1
196
     * @param $dimension2
197
     * @param $value
198
     * @return bool
199
     */
200
    public function update(int $datasetId, $name, $subheader, int $parent, int $type, $link, $visualization, $chart, $chartoptions, $dataoptions, $dimension1 = null, $dimension2 = null, $value = null)
201
    {
202
        if ($type === DatasourceController::DATASET_TYPE_GROUP) {
203
            $parent = 0;
204
        }
205
        return $this->DatasetMapper->update($datasetId, $name, $subheader, $parent, $type, $link, $visualization, $chart, $chartoptions, $dataoptions, $dimension1, $dimension2, $value);
206
    }
207
208
    /**
209
     * set/remove the favorite flag for a report
210
     *
211
     * @param int $datasetId
212
     * @param string $favorite
213
     * @return bool
214
     */
215
    public function setFavorite(int $datasetId, string $favorite)
216
    {
217
        if ($favorite === 'true') {
218
            $return = $this->tagManager->load('analytics')->addToFavorites($datasetId);
219
        } else {
220
            $return = $this->tagManager->load('analytics')->removeFromFavorites($datasetId);
221
        }
222
        return $return;
223
    }
224
225
    /**
226
     * Import Dataset from File
227
     *
228
     * @param string|null $path
229
     * @param string|null $raw
230
     * @return int
231
     * @throws \OCP\Files\NotFoundException
232
     * @throws \OCP\Files\NotPermittedException
233
     */
234
    public function import(string $path = null, string $raw = null)
235
    {
236
        if ($path !== '') {
237
            $file = $this->rootFolder->getUserFolder($this->userId)->get($path);
238
            $data = $file->getContent();
0 ignored issues
show
Bug introduced by
The method getContent() does not exist on OCP\Files\Node. It seems like you code against a sub-type of OCP\Files\Node such as OCP\Files\File. ( Ignorable by Annotation )

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

238
            /** @scrutinizer ignore-call */ 
239
            $data = $file->getContent();
Loading history...
239
        } else if ($raw !== null) {
240
            $data = $raw;
241
        } else {
242
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
243
        }
244
        $data = json_decode($data, true);
245
246
        $dataset = $data['dataset'];
247
        isset($dataset['name']) ? $name = $dataset['name'] : $name = '';
248
        isset($dataset['subheader']) ? $subheader = $dataset['subheader'] : $subheader = '';
249
        $parent = 0;
250
        isset($dataset['type']) ? $type = $dataset['type'] : $type = null;
251
        isset($dataset['link']) ? $link = $dataset['link'] : $link = null;
252
        isset($dataset['visualization']) ? $visualization = $dataset['visualization'] : $visualization = null;
253
        isset($dataset['chart']) ? $chart = $dataset['chart'] : $chart = null;
254
        isset($dataset['chartoptions']) ? $chartoptions = $dataset['chartoptions'] : $chartoptions = null;
255
        isset($dataset['dataoptions']) ? $dataoptions = $dataset['dataoptions'] : $dataoptions = null;
256
        isset($dataset['filteroptions']) ? $filteroptions = $dataset['filteroptions'] : $filteroptions = null;
257
        isset($dataset['dimension1']) ? $dimension1 = $dataset['dimension1'] : $dimension1 = null;
258
        isset($dataset['dimension2']) ? $dimension2 = $dataset['dimension2'] : $dimension2 = null;
259
        isset($dataset['value']) ? $value = $dataset['value'] : $value = null;
260
261
        $datasetId = $this->DatasetMapper->create();
262
        $this->DatasetMapper->update($datasetId, $name, $subheader, $parent, $type, $link, $visualization, $chart, $chartoptions, $dataoptions, $dimension1, $dimension2, $value, $filteroptions);
263
264
        foreach ($data['dataload'] as $dataload) {
265
            isset($dataload['datasource']) ? $datasource = $dataload['datasource'] : $datasource = null;
266
            isset($dataload['name']) ? $name = $dataload['name'] : $name = null;
267
            isset($dataload['option']) ? $option = $dataload['option'] : $option = null;
268
            $schedule = null;
269
270
            $dataloadId = $this->DataloadMapper->create($datasetId, $datasource);
271
            $this->DataloadMapper->update($dataloadId, $name, $option, $schedule);
272
        }
273
274
        foreach ($data['threshold'] as $threshold) {
275
            isset($threshold['dimension1']) ? $dimension1 = $threshold['dimension1'] : $dimension1 = null;
276
            isset($threshold['value']) ? $value = $threshold['value'] : $value = null;
277
            isset($threshold['option']) ? $option = $threshold['option'] : $option = null;
278
            isset($threshold['severity']) ? $severity = $threshold['severity'] : $severity = null;
279
            $this->ThresholdService->create($datasetId, $dimension1, $option, $value, $severity);
280
        }
281
282
        foreach ($data['data'] as $dData) {
283
            isset($dData[0]) ? $dimension1 = $dData[0] : $dimension1 = null;
284
            isset($dData[1]) ? $dimension2 = $dData[1] : $dimension2 = null;
285
            isset($dData[2]) ? $value = $dData[2] : $value = null;
286
            $this->StorageMapper->create($datasetId, $dimension1, $dimension2, $value);
287
        }
288
289
        if (isset($data['favorite'])) {
290
            $this->setFavorite($datasetId, $data['favorite']);
291
        }
292
293
        return $datasetId;
294
    }
295
296
    /**
297
     * Export Dataset
298
     *
299
     * @param int $datasetId
300
     * @return DataDownloadResponse
301
     */
302
    public function export(int $datasetId)
303
    {
304
        $result = array();
305
        $result['dataset'] = $this->DatasetMapper->read($datasetId);
306
        $result['dataload'] = $this->DataloadMapper->read($datasetId);
307
        $result['threshold'] = $this->ThresholdService->read($datasetId);
308
        $result['favorite'] = '';
309
310
        if ($result['dataset']['type'] === DatasourceController::DATASET_TYPE_INTERNAL_DB) {
311
            $result['data'] = $this->StorageMapper->read($datasetId);
312
        }
313
314
        unset($result['dataset']['id'], $result['dataset']['user_id'], $result['dataset']['user_id'], $result['dataset']['parent']);
315
        $data = json_encode($result);
316
        return new DataDownloadResponse($data, $result['dataset']['name'] . '.export.txt', 'text/plain; charset=utf-8');
317
    }
318
319
    /**
320
     * Delete Dataset and all depending objects
321
     *
322
     * @param int $datasetId
323
     * @return bool
324
     */
325
    public function delete(int $datasetId)
326
    {
327
        $this->ShareService->deleteShareByDataset($datasetId);
328
        $this->StorageMapper->deleteByDataset($datasetId);
329
        $this->DatasetMapper->delete($datasetId);
330
        $this->ThresholdService->deleteThresholdByDataset($datasetId);
331
        $this->DataloadMapper->deleteDataloadByDataset($datasetId);
332
        $this->ActivityManager->triggerEvent(0, ActivityManager::OBJECT_DATASET, ActivityManager::SUBJECT_DATASET_DELETE);
333
        $this->setFavorite($datasetId, 'false');
334
        return true;
335
    }
336
337
    /**
338
     * get dataset details
339
     *
340
     * @param int $datasetId
341
     * @param $chartoptions
342
     * @param $dataoptions
343
     * @param $filteroptions
344
     * @return bool
345
     */
346
    public function updateOptions(int $datasetId, $chartoptions, $dataoptions, $filteroptions)
347
    {
348
        return $this->DatasetMapper->updateOptions($datasetId, $chartoptions, $dataoptions, $filteroptions);
349
    }
350
351
    /**
352
     * search for datasets
353
     *
354
     * @param string $searchString
355
     * @return array
356
     */
357
    public function search(string $searchString)
358
    {
359
        return $this->DatasetMapper->search($searchString);
360
    }
361
362
}