Passed
Push — master ( 6f5156...1a5867 )
by Marcel
02:22
created

StorageMapper   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 169
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 78
dl 0
loc 169
rs 10
c 2
b 0
f 0
wmc 20

7 Methods

Rating   Name   Duplication   Size   Complexity  
A createData() 0 20 3
A __construct() 0 11 1
A deleteDataByDataset() 0 6 1
A deleteDataSimulate() 0 8 1
A deleteData() 0 8 1
A sqlWhere() 0 13 6
B getData() 0 46 7
1
<?php
2
/**
3
 * Data 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 2020 Marcel Scherello
10
 */
11
12
namespace OCA\Analytics\Db;
13
14
use OCP\DB\QueryBuilder\IQueryBuilder;
15
use OCP\IDbConnection;
16
use OCP\IL10N;
17
use OCP\ILogger;
18
19
class StorageMapper
20
{
21
    private $userId;
22
    private $l10n;
23
    private $db;
24
    private $logger;
25
26
    public function __construct(
27
        $userId,
28
        IL10N $l10n,
29
        IDbConnection $db,
30
        ILogger $logger
31
    )
32
    {
33
        $this->userId = $userId;
34
        $this->l10n = $l10n;
35
        $this->db = $db;
36
        $this->logger = $logger;
37
    }
38
39
    /**
40
     * Get file id for single track
41
     * @param int $dataset
42
     * @param array $options
43
     * @return array
44
     */
45
    public function getData(int $dataset, $options)
46
    {
47
        $sql = $this->db->getQueryBuilder();
48
        $sql->from('*PREFIX*analytics_facts');
49
        $sql->where($sql->expr()->eq('dataset', $sql->createNamedParameter($dataset)));
50
        $sql->addgroupBy('dataset');
51
52
        $drilldownColumns = array('dimension1' => 'true', 'dimension2' => 'true');
53
        // derive if a column should be removed from drilldown by user input
54
        if (isset($options['drilldown'])) {
55
            $drilldownColumns = array_intersect_key($options['drilldown'], $drilldownColumns) + $drilldownColumns;
56
        }
57
58
        // Add the colunns to the select statement
59
        // $this->logger->debug('StorageMapper 68: '. json_encode($drilldownColumns));
60
        // $this->logger->debug('StorageMapper 69: '. json_encode($options['drilldown']));
61
        foreach ($drilldownColumns as $key => $value) {
62
            if ($value !== 'false') {
63
                $sql->addSelect($key);
64
                $sql->addGroupBy($key);
65
                $sql->addOrderBy($key, 'ASC');
66
            }
67
        }
68
69
        // value column deeds to be at the last position in the select. So it needs to be after the dynamic selects
70
        $sql->addSelect($sql->func()->sum('dimension3'));
71
72
        // add the where clauses to the select
73
        foreach ($options['filter'] as $key => $value) {
74
            $columnName = $key;
75
            if ($value['enabled'] === 'true') {
76
                $this->sqlWhere($sql, $columnName, $value['option'], $value['value']);
77
            }
78
        }
79
80
        $this->logger->debug('StorageMapper 79: ' . $sql->getSQL());
81
        $this->logger->debug('StorageMapper 79: ' . json_encode($sql->getParameters()));
82
        $statement = $sql->execute();
83
        $rows = $statement->fetchAll();
84
        $statement->closeCursor();
85
86
        // reindex result to get rid of the column headers as the frontend works incremental
87
        foreach ($rows as &$row) {
88
            $row = array_values($row);
89
        }
90
        return $rows;
91
    }
92
93
    /**
94
     * Add where statements to a query builder matching the given notification
95
     *
96
     * @param IQueryBuilder $sql
97
     * @param $column
98
     * @param $option
99
     * @param $value
100
     */
101
    protected function sqlWhere(IQueryBuilder $sql, $column, $option, $value)
102
    {
103
        if ($option === 'EQ') {
104
            $sql->andWhere($sql->expr()->eq($column, $sql->createNamedParameter($value)));
105
        } elseif ($option === 'GT') {
106
            $sql->andWhere($sql->expr()->gt($column, $sql->createNamedParameter($value)));
107
        } elseif ($option === 'LT') {
108
            $sql->andWhere($sql->expr()->lt($column, $sql->createNamedParameter($value)));
109
        } elseif ($option === 'IN') {
110
            $sql->andWhere($sql->expr()->in($column, $sql->createParameter('inValues')));
111
            $sql->setParameter('inValues', explode(',', $value), IQueryBuilder::PARAM_STR_ARRAY);
112
        } elseif ($option === 'LIKE') {
113
            $sql->andWhere($sql->expr()->like($column, $sql->createNamedParameter('%' . $value . '%')));
114
        }
115
    }
116
117
    /**
118
     * delete data
119
     */
120
    public function deleteData(int $datasetId, $dimension1, $dimension2)
121
    {
122
        $dimension1 = str_replace('*', '%', $dimension1);
123
        $dimension2 = str_replace('*', '%', $dimension2);
124
        $SQL = 'DELETE FROM `*PREFIX*analytics_facts` WHERE `user_id` = ? AND `dataset` = ? AND `dimension1` like ? AND `dimension2` like ?';
125
        $stmt = $this->db->prepare($SQL);
126
        $stmt->execute(array($this->userId, $datasetId, $dimension1, $dimension2));
127
        return true;
128
    }
129
130
    /**
131
     * Simulate delete data
132
     * @param int $datasetId
133
     * @param $dimension1
134
     * @param $dimension2
135
     * @param $dimension3
136
     * @return array
137
     */
138
    public function deleteDataSimulate(int $datasetId, $dimension1, $dimension2, $dimension3)
0 ignored issues
show
Unused Code introduced by
The parameter $dimension3 is not used and could be removed. ( Ignorable by Annotation )

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

138
    public function deleteDataSimulate(int $datasetId, $dimension1, $dimension2, /** @scrutinizer ignore-unused */ $dimension3)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
139
    {
140
        $dimension1 = str_replace('*', '%', $dimension1);
141
        $dimension2 = str_replace('*', '%', $dimension2);
142
        $SQL = 'select count(*) as `count` FROM `*PREFIX*analytics_facts` WHERE `user_id` = ? AND `dataset` = ? AND `dimension1` like ? AND `dimension2` like ?';
143
        $stmt = $this->db->prepare($SQL);
144
        $stmt->execute(array($this->userId, $datasetId, $dimension1, $dimension2));
145
        return $stmt->fetch();
146
    }
147
148
    /**
149
     * delete all data of a dataset
150
     */
151
    public function deleteDataByDataset(int $datasetId)
152
    {
153
        $SQL = 'DELETE FROM `*PREFIX*analytics_facts` WHERE `user_id` = ? AND `dataset` = ?';
154
        $stmt = $this->db->prepare($SQL);
155
        $stmt->execute(array($this->userId, $datasetId));
156
        return true;
157
    }
158
159
    /**
160
     * create data
161
     * @param int $datasetId
162
     * @param $dimension1
163
     * @param $dimension2
164
     * @param $dimension3
165
     * @param string|null $user_id
166
     * @return string
167
     */
168
    public function createData(int $datasetId, $dimension1, $dimension2, $dimension3, string $user_id = null)
169
    {
170
        $dimension1 = str_replace('*', '', $dimension1);
171
        $dimension2 = str_replace('*', '', $dimension2);
172
        if ($user_id) $this->userId = $user_id;
173
        $SQL = 'SELECT `id` FROM `*PREFIX*analytics_facts` WHERE `user_id` = ? AND `dataset` = ? AND `dimension1` = ? AND `dimension2` = ?';
174
        $stmt = $this->db->prepare($SQL);
175
        $stmt->execute(array($this->userId, $datasetId, $dimension1, $dimension2));
176
        $row = $stmt->fetch();
177
        if ($row) {
178
            $SQL = 'UPDATE `*PREFIX*analytics_facts` SET `dimension3` = ? WHERE `user_id` = ? AND `dataset` = ? AND `dimension1` = ? AND `dimension2` = ?';
179
            $stmt = $this->db->prepare($SQL);
180
            $stmt->execute(array($dimension3, $this->userId, $datasetId, $dimension1, $dimension2));
181
            //$stmt->fetch();
182
            return 'update';
183
        } else {
184
            $SQL = 'INSERT INTO `*PREFIX*analytics_facts` (`user_id`,`dataset`,`dimension1`,`dimension2`,`dimension3`) VALUES(?,?,?,?,?)';
185
            $stmt = $this->db->prepare($SQL);
186
            $stmt->execute(array($this->userId, $datasetId, $dimension1, $dimension2, $dimension3));
187
            return 'insert';
188
        }
189
    }
190
}