findEntitiesBasedOnOrCreated()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 2
eloc 6
nc 2
nop 3
1
<?php
2
/**
3
 * Copyright (c) 2014 - Arno van Rossum <[email protected]>
4
 *
5
 * Permission is hereby granted, free of charge, to any person obtaining a copy
6
 * of this software and associated documentation files (the "Software"), to deal
7
 * in the Software without restriction, including without limitation the rights
8
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the Software is
10
 * furnished to do so, subject to the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be included in
13
 * all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
 * THE SOFTWARE.
22
 */
23
24
namespace OCA\ocUsageCharts\Entity\Storage;
25
26
use OCP\AppFramework\Db\Mapper;
27
use \OCP\IDb;
28
29
/**
30
 * @author Arno van Rossum <[email protected]>
31
 */
32
class StorageUsageRepository extends Mapper
33
{
34
    /**
35
     * @param IDb $db
36
     */
37
    public function __construct(IDb $db) {
38
        parent::__construct($db, 'uc_storageusage', '\OCA\ocUsageCharts\Entity\Storage\StorageUsage');
39
    }
40
41
    /**
42
     * Save a storage usage entity to the database
43
     *
44
     * @param StorageUsage $usage
45
     * @return boolean
46
     */
47
    public function save(StorageUsage $usage)
48
    {
49
        $query = $this->db->prepareQuery('INSERT INTO *PREFIX*uc_storageusage (created, username, `usage`) VALUES (?,?,?)');
50
        $result = $query->execute(Array($usage->getDate()->format('Y-m-d H:i:s'), $usage->getUsername(), $usage->getUsage()));
51
        /*
52
         * $query->execute could return integer or OC_DB_StatementWrapper or false
53
         * I am expecting an integer with number 1
54
         */
55
        if ( is_int($result) && $result === 1 )
56
        {
57
            return true;
58
        }
59
        return false;
60
    }
61
62
    /**
63
     * @param string $userName
64
     * @param integer $limit
65
     * @return array
66
     */
67
    public function find($userName, $limit = 30) {
68
        $sql = 'SELECT * FROM `*PREFIX*uc_storageusage` WHERE `username` = ? ORDER BY created DESC LIMIT ' . $limit;
69
        return $this->findEntities($sql, array($userName));
70
    }
71
72
    /**
73
     * This method retrieves per username the latest storage usage with a limit of given
74
     *
75
     * @param integer $limit
76
     * @return array
77
     */
78
    public function findAllWithLimit($limit = 30)
79
    {
80
        return $this->findAll($limit);
81
82
    }
83
84
    /**
85
     * This method retrieves per username the latest storage usage from date given
86
     *
87
     * @param \DateTime $created
88
     * @return array
89
     */
90
    public function findAllAfterCreated(\DateTime $created)
91
    {
92
        return $this->findAll(30, $created);
93
    }
94
95
    /**
96
     * This method retrieves all usernames,
97
     * and gets the latest storage usage for them
98
     *
99
     * Limit is bogus when $afterCreated is used
100
     *
101
     * @param integer $limit
102
     * @param \DateTime $afterCreated
103
     *
104
     * @return array
105
     */
106
    private function findAll($limit = 30, \DateTime $afterCreated = null)
107
    {
108
        $sql = 'SELECT username FROM `*PREFIX*uc_storageusage` WHERE `usage` > 0 GROUP BY username';
109
        $query = $this->db->prepareQuery($sql);
110
        $result = $query->execute();
111
        $entities = array();
112
        while($row = $result->fetch()){
113
            if ( empty($entities[$row['username']]) )
114
            {
115
                $entities[$row['username']] = array();
116
            }
117
118
            $entities[$row['username']] = array_merge(
119
                $entities[$row['username']],
120
                $this->findEntitiesBasedOnOrCreated($row['username'], $limit, $afterCreated)
121
            );
122
        }
123
        return $entities;
124
    }
125
126
    /**
127
     * @param string $username
128
     * @param integer $limit
129
     * @param \DateTime $afterCreated
130
     * @return array
131
     */
132
    private function findEntitiesBasedOnOrCreated($username, $limit, \DateTime $afterCreated = null)
133
    {
134
        if ( !is_null($afterCreated) )
135
        {
136
            $return = $this->findAfterCreated($username, $afterCreated);
137
        }
138
        else
139
        {
140
            $return = $this->find($username, $limit);
141
        }
142
143
        return $return;
144
    }
145
146
    /**
147
     * @param string $userName
148
     * @param \DateTime $created
149
     * @return array
150
     */
151
    public function findAfterCreated($userName, \DateTime $created) {
152
        $sql = 'SELECT * FROM `*PREFIX*uc_storageusage` WHERE `username` = ? AND `created` > ? ORDER BY created DESC';
153
        return $this->findEntities($sql, array($userName, $created->format('Y-m-d H:i:s')));
154
    }
155
156
    /**
157
     * Find all storage usages grouped by username and month
158
     * When username supplied, only for that user
159
     * With a maximum of going back 1 year
160
     *
161
     * @param string $username
162
     * @return array
163
     */
164
    public function findAllPerMonth($username = '')
165
    {
166
        $created = new \DateTime();
167
        $created->sub(new \DateInterval('P1Y'));
168
        // When no username supplied, search for all information
169
        $sql = '
170
            SELECT
171
            DISTINCT CONCAT(
172
                extract(MONTH from created), \' \', extract(YEAR from created)
173
              ) as month,
174
              avg(`usage`) as average,
175
              username
176
              FROM *PREFIX*uc_storageusage';
177
        $whereClause = ' WHERE `usage` > 0 AND created > ? GROUP BY username, month';
178
179
        $params = array();
180
181
        // Username is supplied, get results only for that user
182
        if ( $username !== '' )
183
        {
184
            $whereClause = ' WHERE `usage` > 0 AND username = ? AND created > ? GROUP BY month';
185
            $params = array($username);
186
        }
187
        $params[] = $created->format('Y-m-d H:I:s');
188
        $query = $this->db->prepareQuery($sql . $whereClause);
189
        $result = $query->execute($params);
190
191
        return $this->parsePerMonthEntities($result);
192
    }
193
194
    /**
195
     * Parse the results from the per month entities found
196
     *
197
     * @param \OC_DB_StatementWrapper $result
198
     * @return array
199
     */
200
    private function parsePerMonthEntities($result)
201
    {
202
        $entities = array();
203
        while($row = $result->fetch()){
204
            if ( !isset($entities[$row['username']]))
205
            {
206
                $entities[$row['username']] = array();
207
            }
208
            $date = explode(' ', $row['month']);
209
            $dateTime = new \Datetime();
210
            $dateTime->setDate($date[1], $date[0], 1);
211
212
            $entities[$row['username']] = array_merge(
213
                $entities[$row['username']],
214
                array(new StorageUsage($dateTime, $row['average'], $row['username']))
215
            );
216
        }
217
218
219
        return $entities;
220
    }
221
}