Passed
Push — master ( 912bd1...0b1a33 )
by Marcel
06:53
created

ReportService::index()   B

Complexity

Conditions 10
Paths 36

Size

Total Lines 40
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 25
c 1
b 0
f 0
nc 36
nop 0
dl 0
loc 40
rs 7.6666

How to fix   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
 * 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\ReportMapper;
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\ITagManager;
23
use Psr\Log\LoggerInterface;
24
25
class ReportService
26
{
27
    private $userId;
28
    private $logger;
29
    private $tagManager;
30
    private $ShareService;
31
    private $DatasetService;
32
    private $StorageMapper;
33
    private $ReportMapper;
34
    private $ThresholdService;
35
    private $DataloadMapper;
36
    private $ActivityManager;
37
    private $rootFolder;
38
    private $VariableService;
39
40
    public function __construct(
41
        $userId,
42
        LoggerInterface $logger,
43
        ITagManager $tagManager,
44
        ShareService $ShareService,
45
        DatasetService $DatasetService,
46
        StorageMapper $StorageMapper,
47
        ReportMapper $ReportMapper,
48
        ThresholdService $ThresholdService,
49
        DataloadMapper $DataloadMapper,
50
        ActivityManager $ActivityManager,
51
        IRootFolder $rootFolder,
52
        VariableService $VariableService
53
    )
54
    {
55
        $this->userId = $userId;
56
        $this->logger = $logger;
57
        $this->tagManager = $tagManager;
58
        $this->ShareService = $ShareService;
59
        $this->DatasetService = $DatasetService;
60
        $this->ThresholdService = $ThresholdService;
61
        $this->StorageMapper = $StorageMapper;
62
        $this->ReportMapper = $ReportMapper;
63
        $this->DataloadMapper = $DataloadMapper;
64
        $this->ActivityManager = $ActivityManager;
65
        $this->rootFolder = $rootFolder;
66
        $this->VariableService = $VariableService;
67
    }
68
69
    /**
70
     * get all reports
71
     *
72
     * @return DataResponse
73
     */
74
    public function index()
75
    {
76
        $ownReports = $this->ReportMapper->index();
77
78
        // get dataload indicators for icons shown in the advanced screen
79
        $dataloads = $this->DataloadMapper->getAllDataloadMetadata();
80
        foreach ($dataloads as $dataload) {
81
            $key = array_search($dataload['dataset'], array_column($ownReports, 'dataset'));
82
            if ($key !== '') {
83
                if ($dataload['schedules'] !== '' and $dataload['schedules'] !== null) {
84
                    $dataload['schedules'] = 1;
85
                } else {
86
                    $dataload['schedules'] = 0;
87
                }
88
                $ownReports[$key]['dataloads'] = $dataload['dataloads'];
89
                $ownReports[$key]['schedules'] = $dataload['schedules'];
90
            }
91
        }
92
93
        // get shared reports and remove doublicates
94
        $sharedReports = $this->ShareService->getSharedReports();
95
        foreach ($sharedReports as $sharedReport) {
96
            if (!array_search($sharedReport['id'], array_column($ownReports, 'id'))) {
97
                $sharedReport['type'] = '99';
98
                $sharedReport['parrent'] = '0';
99
                array_push($ownReports, $sharedReport);
100
            }
101
        }
102
103
        $favorites = $this->tagManager->load('analytics')->getFavorites();
104
        foreach ($ownReports as &$ownReport) {
105
            $hasTag = 0;
106
            if (is_array($favorites) and in_array($ownReport['id'], $favorites)) {
107
                $hasTag = 1;
108
            }
109
            $ownReport['favorite'] = $hasTag;
110
            $ownReport = $this->VariableService->replaceTextVariables($ownReport);
111
        }
112
113
        return new DataResponse($ownReports);
114
    }
115
116
    /**
117
     * get own report details
118
     *
119
     * @param int $reportId
120
     * @return array
121
     */
122
    public function read(int $reportId)
123
    {
124
        $ownReport = $this->ReportMapper->read($reportId);
125
        if (!empty($ownReport)) {
126
            $ownReport['permissions'] = \OCP\Constants::PERMISSION_UPDATE;
127
        }
128
        return $ownReport;
129
    }
130
131
    /**
132
     * get own report details
133
     *
134
     * @param int $reportId
135
     * @param string|null $user_id
136
     * @return array
137
     */
138
    public function getOwnReport(int $reportId, string $user_id = null)
139
    {
140
        $ownReport = $this->ReportMapper->read($reportId, $user_id);
141
        if (!empty($ownReport)) {
142
            $ownReport['permissions'] = \OCP\Constants::PERMISSION_UPDATE;
143
            $ownReport = $this->VariableService->replaceTextVariables($ownReport);
144
        }
145
        return $ownReport;
146
    }
147
148
    /**
149
     * get own reports which are marked as favorites
150
     *
151
     * @return array|bool
152
     */
153
    public function getOwnFavoriteReports()
154
    {
155
        $ownReports = $this->ReportMapper->index();
156
        $favorits = $this->tagManager->load('analytics')->getFavorites();
157
        $sharedReports = $this->ShareService->getSharedReports();
158
159
        foreach ($favorits as $favorite) {
160
            if (array_search($favorite, array_column($ownReports, 'id')) === false
161
                && array_search($favorite, array_column($sharedReports, 'id')) === false) {
162
                unset($favorits[$favorite]);
163
                $this->tagManager->load('analytics')->removeFromFavorites($favorite);
164
            }
165
        }
166
167
        return $favorits;
168
    }
169
170
    /**
171
     * create new report
172
     *
173
     * @param string $file
174
     * @return int
175
     */
176
    public function create($file = '')
177
    {
178
        $this->ActivityManager->triggerEvent(0, ActivityManager::OBJECT_DATASET, ActivityManager::SUBJECT_DATASET_ADD);
179
        $reportId = $this->ReportMapper->create();
180
181
        if ($file !== '') {
182
            $name = explode('.', end(explode('/', $file)))[0];
183
            $subheader = $file;
184
            $parent = 0;
185
            $type = DatasourceController::DATASET_TYPE_FILE;
186
            $link = $file;
187
            $visualization = 'table';
188
            $chart = 'line';
189
            $this->update($reportId, $name, $subheader, $parent, $type, $link, $visualization, $chart, '', '');
0 ignored issues
show
Bug introduced by
$link of type string is incompatible with the type integer expected by parameter $dataset of OCA\Analytics\Service\ReportService::update(). ( Ignorable by Annotation )

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

189
            $this->update($reportId, $name, $subheader, $parent, $type, /** @scrutinizer ignore-type */ $link, $visualization, $chart, '', '');
Loading history...
Bug introduced by
The call to OCA\Analytics\Service\ReportService::update() has too few arguments starting with dataoptions. ( Ignorable by Annotation )

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

189
            $this->/** @scrutinizer ignore-call */ 
190
                   update($reportId, $name, $subheader, $parent, $type, $link, $visualization, $chart, '', '');

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
190
        }
191
        return $reportId;
192
    }
193
194
    /**
195
     * update report details
196
     *
197
     * @param int $reportId
198
     * @param $name
199
     * @param $subheader
200
     * @param int $parent
201
     * @param int $type
202
     * @param int $dataset
203
     * @param $link
204
     * @param $visualization
205
     * @param $chart
206
     * @param $chartoptions
207
     * @param $dataoptions
208
     * @param null $dimension1
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $dimension1 is correct as it would always require null to be passed?
Loading history...
209
     * @param null $dimension2
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $dimension2 is correct as it would always require null to be passed?
Loading history...
210
     * @param null $value
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
Loading history...
211
     * @return bool
212
     * @throws \OCP\DB\Exception
213
     */
214
    public function update(int $reportId, $name, $subheader, int $parent, int $type, int $dataset, $link, $visualization, $chart, $chartoptions, $dataoptions, $dimension1 = null, $dimension2 = null, $value = null)
215
    {
216
        if ($type === DatasourceController::DATASET_TYPE_GROUP) {
217
            $parent = 0;
218
        }
219
        if ($dataset === 0) { // New dataset
220
            $dataset = $this->DatasetService->create($name, $dimension1, $dimension2, $value);
221
        }
222
        return $this->ReportMapper->update($reportId, $name, $subheader, $parent, $type, $dataset, $link, $visualization, $chart, $chartoptions, $dataoptions, $dimension1, $dimension2, $value);
223
    }
224
225
    /**
226
     * set/remove the favorite flag for a report
227
     *
228
     * @param int $reportId
229
     * @param string $favorite
230
     * @return bool
231
     */
232
    public function setFavorite(int $reportId, string $favorite)
233
    {
234
        if ($favorite === 'true') {
235
            $return = $this->tagManager->load('analytics')->addToFavorites($reportId);
236
        } else {
237
            $return = $this->tagManager->load('analytics')->removeFromFavorites($reportId);
238
        }
239
        return $return;
240
    }
241
242
    /**
243
     * Import Report from File
244
     *
245
     * @param string|null $path
246
     * @param string|null $raw
247
     * @return int
248
     * @throws \OCP\Files\NotFoundException
249
     * @throws \OCP\Files\NotPermittedException
250
     */
251
    public function import(string $path = null, string $raw = null)
252
    {
253
        if ($path !== '') {
254
            $file = $this->rootFolder->getUserFolder($this->userId)->get($path);
255
            $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

255
            /** @scrutinizer ignore-call */ 
256
            $data = $file->getContent();
Loading history...
256
        } else if ($raw !== null) {
257
            $data = $raw;
258
        } else {
259
            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...
260
        }
261
        $data = json_decode($data, true);
262
263
        $dataset = $data['dataset'];
264
        isset($dataset['name']) ? $name = $dataset['name'] : $name = '';
265
        isset($dataset['subheader']) ? $subheader = $dataset['subheader'] : $subheader = '';
266
        $parent = 0;
267
        isset($dataset['type']) ? $type = $dataset['type'] : $type = null;
268
        isset($dataset['link']) ? $link = $dataset['link'] : $link = null;
269
        isset($dataset['visualization']) ? $visualization = $dataset['visualization'] : $visualization = null;
270
        isset($dataset['chart']) ? $chart = $dataset['chart'] : $chart = null;
271
        isset($dataset['chartoptions']) ? $chartoptions = $dataset['chartoptions'] : $chartoptions = null;
272
        isset($dataset['dataoptions']) ? $dataoptions = $dataset['dataoptions'] : $dataoptions = null;
273
        isset($dataset['filteroptions']) ? $filteroptions = $dataset['filteroptions'] : $filteroptions = null;
274
        isset($dataset['dimension1']) ? $dimension1 = $dataset['dimension1'] : $dimension1 = null;
275
        isset($dataset['dimension2']) ? $dimension2 = $dataset['dimension2'] : $dimension2 = null;
276
        isset($dataset['value']) ? $value = $dataset['value'] : $value = null;
277
278
        $reportId = $this->ReportMapper->create();
279
        $this->ReportMapper->update($reportId, $name, $subheader, $parent, $type, $link, $visualization, $chart, $chartoptions, $dataoptions, $dimension1, $dimension2, $value, $filteroptions);
280
281
        foreach ($data['dataload'] as $dataload) {
282
            isset($dataload['datasource']) ? $datasource = $dataload['datasource'] : $datasource = null;
283
            isset($dataload['name']) ? $name = $dataload['name'] : $name = null;
284
            isset($dataload['option']) ? $option = $dataload['option'] : $option = null;
285
            $schedule = null;
286
287
            /**todo**/
288
            $dataloadId = $this->DataloadMapper->create($reportId, $datasource);
289
            $this->DataloadMapper->update($dataloadId, $name, $option, $schedule);
290
        }
291
292
        foreach ($data['threshold'] as $threshold) {
293
            isset($threshold['dimension1']) ? $dimension1 = $threshold['dimension1'] : $dimension1 = null;
294
            isset($threshold['value']) ? $value = $threshold['value'] : $value = null;
295
            isset($threshold['option']) ? $option = $threshold['option'] : $option = null;
296
            isset($threshold['severity']) ? $severity = $threshold['severity'] : $severity = null;
297
            $this->ThresholdService->create($reportId, $dimension1, $option, $value, $severity);
298
        }
299
300
        foreach ($data['data'] as $dData) {
301
            isset($dData[0]) ? $dimension1 = $dData[0] : $dimension1 = null;
302
            isset($dData[1]) ? $dimension2 = $dData[1] : $dimension2 = null;
303
            isset($dData[2]) ? $value = $dData[2] : $value = null;
304
            $this->StorageMapper->create($reportId, $dimension1, $dimension2, $value);
305
        }
306
307
        if (isset($data['favorite'])) {
308
            $this->setFavorite($reportId, $data['favorite']);
309
        }
310
311
        return $reportId;
312
    }
313
314
    /**
315
     * Export Report
316
     *
317
     * @param int $reportId
318
     * @return DataDownloadResponse
319
     */
320
    public function export(int $reportId)
321
    {
322
        /**todo**/
323
        $result = array();
324
        $result['dataset'] = $this->ReportMapper->read($reportId);
325
        $result['dataload'] = $this->DataloadMapper->read($datasetId);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $datasetId seems to be never defined.
Loading history...
326
        $result['threshold'] = $this->ThresholdService->read($reportId);
327
        $result['favorite'] = '';
328
329
        if ($result['dataset']['type'] === DatasourceController::DATASET_TYPE_INTERNAL_DB) {
330
            $result['data'] = $this->StorageMapper->read($datasetId);
331
        }
332
333
        unset($result['dataset']['id'], $result['dataset']['user_id'], $result['dataset']['user_id'], $result['dataset']['parent']);
334
        $data = json_encode($result);
335
        return new DataDownloadResponse($data, $result['dataset']['name'] . '.export.txt', 'text/plain; charset=utf-8');
336
    }
337
338
    /**
339
     * Delete Dataset and all depending objects
340
     *
341
     * @param int $reportId
342
     * @return bool
343
     */
344
    public function delete(int $reportId)
345
    {
346
        $this->ShareService->deleteShareByReport($reportId);
347
        $this->StorageMapper->deleteByDataset($reportId);
348
        /**todo**/
349
        $this->ReportMapper->delete($reportId);
350
        $this->ThresholdService->deleteThresholdByReport($reportId);
351
        $this->DataloadMapper->deleteDataloadByDataset($reportId);
352
        $this->ActivityManager->triggerEvent(0, ActivityManager::OBJECT_DATASET, ActivityManager::SUBJECT_DATASET_DELETE);
353
        $this->setFavorite($reportId, 'false');
354
        return true;
355
    }
356
357
    /**
358
     * Update report options
359
     *
360
     * @param int $reportId
361
     * @param $chartoptions
362
     * @param $dataoptions
363
     * @param $filteroptions
364
     * @return bool
365
     */
366
    public function updateOptions(int $reportId, $chartoptions, $dataoptions, $filteroptions)
367
    {
368
        return $this->ReportMapper->updateOptions($reportId, $chartoptions, $dataoptions, $filteroptions);
369
    }
370
371
    /**
372
     * get report refresh options
373
     *
374
     * @NoAdminRequired
375
     * @param int $reportId
376
     * @param $refresh
377
     * @return bool
378
     */
379
    public function updateRefresh(int $reportId, $refresh)
380
    {
381
        return $this->ReportMapper->updateRefresh($reportId, $refresh);
382
    }
383
384
    /**
385
     * search for reports
386
     *
387
     * @param string $searchString
388
     * @return array
389
     */
390
    public function search(string $searchString)
391
    {
392
        return $this->ReportMapper->search($searchString);
393
    }
394
395
}