Passed
Push — master ( 359a20...4078c2 )
by Ruben
01:46
created

Persistence::countFrom()   A

Complexity

Conditions 6
Paths 15

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 15
nop 3
dl 0
loc 18
rs 9.2222
c 0
b 0
f 0
1
<?php
2
/**
3
 *
4
 * (c) Ruben Dorado <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
namespace SiteAnalyzer;
10
11
use Exception;
12
use PDO;
13
14
/**
15
 * class SiteAnalyzer
16
 *
17
 * @package   SiteAnalyzer
18
 * @author    Ruben Dorado <[email protected]>
19
 * @copyright 2018 Ruben Dorado
20
 * @license   http://www.opensource.org/licenses/MIT The MIT License
21
 */
22
class Persistence
23
{
24
25
    /*
26
     * @param Configuration $config
27
     *
28
     * @return PDO
29
     */
30
    public static function getPDO($config) {
31
        $options = array(
32
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
33
        );
34
        
35
        if ($config->getDsn()) {
36
            try {
37
                return new PDO($config->getDsn(), $config->getUser(), $config->getPassword(), $options);
38
            } catch (Exception $e) {                
39
                if (!$config->getUseOnMemoryDB()) {
40
                    throw new Exception("Could not create a db connection. Check permissions, configuration, and documentation. ".$e->getMessage());
41
                }
42
            }
43
        }
44
        
45
        if ($config->getUseOnMemoryDB()) {
46
            try {
47
                return new PDO("sqlite::memory:", null, null, $options);
48
            } catch (Exception $e) {
49
                throw new Exception("Could not create a db connection. Check permissions, configuration, and documentation. ".$e->getMessage());                
50
            }
51
        }
52
        throw new Exception("Error when trying to obtain a connection to a database. Check the configuration. ");
53
54
    }
55
56
57
    /*
58
     * @param $pdo PDO
59
     * @param $config Configuration
60
     *
61
     */
62
    public static function crateDatabase($pdo, $config) {
63
        try {
64
            $db_hit_table = $config->getHitTableName();
65
            $db_options_table = $config->getOptionsTableName();           
66
            $db_from_table = $config->getFromTableName();
67
            $db_url_table = $config->getUrlTableName();
68
69
            $stmt = $pdo->prepare("CREATE TABLE $db_hit_table (id VARCHAR(255), count INT)");
70
            $stmt->execute();
71
            $stmt = $pdo->prepare("CREATE TABLE $db_options_table (id VARCHAR(255), time TIMESTAMP, user VARCHAR(255))");
72
            $stmt->execute();
73
            $stmt = $pdo->prepare("CREATE TABLE $db_from_table (id VARCHAR(255), from_id VARCHAR(255), count INT)");
74
            $stmt->execute();
75
            $stmt = $pdo->prepare("CREATE TABLE $db_url_table (id VARCHAR(255), url VARCHAR(255), count INT)");
76
            $stmt->execute();
77
        } catch (Exception $e) {
78
            throw new Exception("Could not create the database. ".$e->getMessage());
79
        }        
80
        return true;
81
    }
82
83
84
    /*
85
     * @param $pdo PDO
86
     * @param $config Configuration
87
     *
88
     */
89
    public static function deleteDatabase($pdo, $config) {
90
        $resp = true;
91
        
92
        $db_hit_table = $config->getHitTableName();
93
        $db_options_table = $config->getOptionsTableName();
94
        $db_from_table = $config->getFromTableName();
95
        $db_url_table = $config->getUrlTableName();
96
        
97
        $resp = $resp && Persistence::dropTable($pdo, $db_hit_table);
98
        $resp = $resp && Persistence::dropTable($pdo, $db_options_table);
99
        $resp = $resp && Persistence::dropTable($pdo, $db_from_table);
100
        $resp = $resp && Persistence::dropTable($pdo, $db_url_table);
101
        
102
        return $resp;
103
    }
104
105
106
    /*
107
     * @param $pdo PDO
108
     * @param $config Configuration
109
     *
110
     */
111
    private static function dropTable($pdo, $tableName) {
112
        try {            
113
            $stmt = $pdo->prepare("DROP TABLE $tableName");
114
            $stmt->execute();
115
           
116
        } catch (Exception $e) {
117
            throw new Exception("Problem deleting the table $tableName. ".$e->getMessage());
118
        }
119
        return true;
120
    }
121
    
122
123
    /*
124
     * @param $pdo PDO
125
     * @param $config Configuration
126
     *
127
     */
128
    public static function checkTables($pdo, $config) {
129
        $resp = true;      
130
        try {
131
            
132
            $resp = $resp && Persistence::checkHitTable($pdo, $config);
133
            $resp = $resp && Persistence::checkOptionsTable($pdo, $config);
134
            $resp = $resp && Persistence::checkFromTable($pdo, $config);
135
            $resp = $resp && Persistence::checkUrlTable($pdo, $config);
136
        } catch (Exception $e) {
137
            return false;
138
        }        
139
        return $resp;
140
141
    }
142
143
    /*
144
     * @param $pdo PDO
145
     * @param $config Configuration
146
     */
147
    public static function checkFromTable($pdo, $config) {
148
        try {
149
            $db_from_table = $config->getFromTableName();
150
            $stmt = $pdo->prepare("SELECT * FROM $db_from_table WHERE 1==0");
151
            $stmt->execute();
152
        } catch (Exception $e) {
153
            return false;
154
        }
155
        return true;
156
    }
157
        
158
    /*
159
     * @param $pdo PDO
160
     * @param $config Configuration
161
     */
162
    public static function checkUrlTable($pdo, $config) {
163
        try {
164
            $db_url_table = $config->getUrlTableName();
165
            $stmt = $pdo->prepare("SELECT * FROM $db_url_table WHERE 1==0");
166
            $stmt->execute();            
167
        } catch (Exception $e) {
168
            return false;
169
        }
170
        return true;
171
    }
172
    
173
   
174
    
175
    /*
176
     * @param $pdo PDO
177
     * @param $config Configuration
178
     */
179
    public static function checkOptionsTable($pdo, $config) {
180
        try {
181
            $db_options_table = $config->getOptionsTableName();
182
            $stmt = $pdo->prepare("SELECT * FROM $db_options_table WHERE 1==0");
183
            $stmt->execute();
184
        } catch (Exception $e) {
185
            return false;
186
        }
187
        return true;
188
    }
189
    
190
    /*
191
     * @param $pdo PDO
192
     * @param $config Configuration
193
     */
194
    public static function checkHitTable($pdo, $config) {
195
        try {
196
            $db_hit_table = $config->getHitTableName();
197
            $stmt = $pdo->prepare("SELECT * FROM $db_hit_table WHERE 1==0");
198
            $stmt->execute();            
199
        } catch (Exception $e) {
200
            return false;
201
        }
202
        return true;        
203
    }
204
     
205
    /*
206
     * @param $pdo PDO
207
     * @param $config Configuration
208
     *
209
     */
210
    public static function countHit($pdo, $config, $options = []) {
211
        if (array_key_exists('url', $options)) {
212
            $url = $options['url'];
213
        } else if (array_key_exists('HTTP_HOST', $_SERVER)) {
214
            $url = "http://".$_SERVER['HTTP_HOST'];
215
            if (array_key_exists('REQUEST_URI', $_SERVER)) {
216
                $url = $url.$_SERVER['REQUEST_URI'];
217
            }               
218
        } else {
219
            $url = "No Info";
220
        }
221
222
        if ($config->getRemoveQueryString()) {
223
            $url = preg_replace('/\?.*/', '', $url);
224
        }
225
        
226
        if (array_key_exists('id', $options)) {
227
            $id = $options['id'];
228
        } else {
229
            $id = $url;
230
        }
231
232
        $stmt = $pdo->prepare("UPDATE $db_hit_table SET count = count + 1 WHERE id = ?");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $db_hit_table seems to be never defined.
Loading history...
233
        $stmt->execute([$id]);
234
        if ($stmt->rowCount()==0) {
235
            $stmt = $pdo->prepare("INSERT INTO $db_hit_table (id, count) VALUES (?, 1)");
236
            $stmt->execute([$id]);
237
        }
238
239
        $stmt = $pdo->prepare("UPDATE $db_url_table SET count = count + 1 WHERE id = ? and url = ?");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $db_url_table seems to be never defined.
Loading history...
240
        $stmt->execute([$id, $url]);
241
        if ($stmt->rowCount()==0) {
242
            $stmt = $pdo->prepare("INSERT INTO $db_url_table (id, url, count) VALUES (?, ?, 1)");
243
            $stmt->execute([$id, $url]);
244
        }
245
        
246
    }
247
    
248
    /*
249
     * @param $pdo PDO
250
     * @param $config Configuration
251
     *
252
     */
253
    public static function countFrom($pdo, $config, $options = []) {
254
        if (array_key_exists('from_id', $options)) {
255
            $ids = [$options['from_id']];
256
        } else {
257
            $from_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'No referer info';
258
            $ids = Persistence::findHitIdsByUrl($pdo, $config, $from_url); 
259
            if (count($ids)==0) {
260
                $stmt = $pdo->prepare("INSERT INTO $db_url_table (id, url, count) VALUES (?, ?, 1)");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $db_url_table seems to be never defined.
Loading history...
261
                $stmt->execute([$from_url, $from_url]);
262
                $ids = [$from_url];
263
            }
264
        }
265
        foreach ($ids as $from_id) {
266
            $stmt = $pdo->prepare("UPDATE $db_from_table SET count = count + 1 WHERE id = ? and from_id = ?");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $db_from_table seems to be never defined.
Loading history...
267
            $stmt->execute([$id, $from_id]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id does not exist. Did you maybe mean $ids?
Loading history...
268
            if ($stmt->rowCount()==0) {
269
                $stmt = $pdo->prepare("INSERT INTO $db_from_table (id, from_id, count) VALUES (?, ?, 1)");
270
                $stmt->execute([$id, $from_id]);
271
            }
272
        }
273
    }
274
    
275
    /*
276
     * @param $pdo PDO
277
     * @param $config Configuration
278
     *
279
     */
280
    public static function countOptions($pdo, $config, $options = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $config 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

280
    public static function countOptions($pdo, /** @scrutinizer ignore-unused */ $config, $options = []) {

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...
281
        $user = null;
282
        if ($store_user) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $store_user seems to be never defined.
Loading history...
283
            if (array_key_exists('user', $options)) {
284
                $user = $options['user'];
285
            }    
286
        }
287
        
288
        if ($store_time || $store_user) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $store_time seems to be never defined.
Loading history...
289
            $stmt = $pdo->prepare("INSERT INTO $db_options_table (id, time, user) VALUES (?, ?, ?)");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $db_options_table does not exist. Did you maybe mean $options?
Loading history...
290
            $stmt->execute([$id, time(), $user]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id seems to be never defined.
Loading history...
291
        }        
292
    }
293
    
294
    /*
295
     * @param $pdo PDO
296
     * @param $config Configuration
297
     *
298
     */
299
    public static function updateCount($pdo, $config, $options = []) {
300
301
        $db_hit_table = $config->getHitTableName();
0 ignored issues
show
Unused Code introduced by
The assignment to $db_hit_table is dead and can be removed.
Loading history...
302
        $db_options_table = $config->getOptionsTableName();
0 ignored issues
show
Unused Code introduced by
The assignment to $db_options_table is dead and can be removed.
Loading history...
303
        $db_from_table = $config->getFromTableName();
0 ignored issues
show
Unused Code introduced by
The assignment to $db_from_table is dead and can be removed.
Loading history...
304
        $db_url_table = $config->getUrlTableName();
0 ignored issues
show
Unused Code introduced by
The assignment to $db_url_table is dead and can be removed.
Loading history...
305
306
        $store_from = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $store_from is dead and can be removed.
Loading history...
307
        $store_time = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $store_time is dead and can be removed.
Loading history...
308
        $store_user = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $store_user is dead and can be removed.
Loading history...
309
        
310
        Persistence::countHit($pdo, $config, $options);
311
        Persistence::countFrom($pdo, $config, $options);           
312
        Persistence::countOptions($pdo, $config, $options); 
313
                       
314
315
        
316
        return true;
317
    }
318
319
    /*
320
     * @param $pdo PDO
321
     * @param $config Configuration
322
     *
323
     */
324
    public static function findHitIdsByUrl($pdo, $config, $url) {
325
        $resp = [];
326
        try {
327
            
328
            $dbtable = $config->getUrlTableName();
329
            $stmt = $pdo->prepare("SELECT id,url,count FROM $dbtable WHERE url = '$url'");
330
            if ($stmt->execute()) {
331
                while ($row = $stmt->fetch()) {
332
                    $resp[] = $row['id'];
333
                }
334
            }
335
        } catch (Exception $e) {
336
            throw new Exception("Error executing function 'findHitsByUrl'. ".$e->getMessage());
337
        }
338
        return $resp;        
339
    }
340
341
    
342
    /*
343
     * @param $pdo PDO
344
     * @param $config Configuration
345
     *
346
     */
347
    public static function getAllHits($pdo, $config) {
348
        $resp = [];
349
        try {
350
            $dbtable = $config->getHitTableName();
351
            $stmt = $pdo->prepare("SELECT id,count FROM $dbtable");
352
            if ($stmt->execute()) {
353
                while ($row = $stmt->fetch()) {
354
                    $resp[] = [$row['id'], $row['count']];
355
                }
356
            }
357
            
358
        } catch (Exception $e) {
359
            throw new Exception("Error executing function 'getAllHits'. ".$e->getMessage());
360
        }
361
        return $resp;        
362
    }
363
364
    
365
    /*
366
     * @param $pdo PDO
367
     * @param $config Configuration
368
     *
369
     */
370
    public static function findUrls($pdo, $config, $by = []) {
371
        $resp = [];
372
        try {
373
            $dbtable = $config->getUrlTableName();
374
            $qdata = [];
375
            $tquery = [];
376
            if (array_key_exists('id', $by)) {
377
                $qdata[] = $by['id'];
378
                $tquery[] = "id = ?";
379
            }
380
            
381
            if (array_key_exists('url', $by)) {
382
                $qdata[] = $by['url'];
383
                $tquery[] = "url = ?";
384
            }
385
            
386
            $sql = "SELECT id,url,count FROM $dbtable";
387
            if (count($tquery) > 0) {
388
                $sql = $sql." WHERE ".join(" AND ", $tquery);
389
            }
390
            
391
            $stmt = $pdo->prepare($sql);
392
            if ($stmt->execute($qdata)) {
393
                while ($row = $stmt->fetch()) {
394
                    $resp[] = [$row['id'], $row['url'], $row['count']];
395
                }
396
            }
397
            
398
        } catch (Exception $e) {
399
            throw new Exception("Error executing function 'getAllUrls'. ".$e->getMessage());
400
        }
401
        return $resp;
402
    }
403
404
    /*
405
     * @param $pdo PDO
406
     * @param $config Configuration
407
     *
408
     */
409
    public static function findIdByTimeUser($pdo, $config, $by = []) {
410
        $resp = [];
411
        try {
412
            $dbtable = $config->getOptionsTableName();
413
            $qdata = [];
414
            $tquery = [];
415
            if (array_key_exists('from', $by)) {
416
                $qdata[] = $by['from'];
417
                $tquery[] = "time >= ?";
418
            }
419
            
420
            if (array_key_exists('to', $by)) {
421
                $qdata[] = $by['to'];
422
                $tquery[] = "time <= ?";
423
            }
424
            
425
            if (array_key_exists('user', $by)) {
426
                $qdata[] = $by['user'];
427
                $tquery[] = "user = ?";
428
            }
429
            
430
            $sql = "SELECT id,time,user FROM $dbtable";
431
            if (count($tquery) > 0) {
432
                $sql = $sql." WHERE ".join(" AND ", $tquery);
433
            }
434
            
435
            $stmt = $pdo->prepare($sql);
436
            if ($stmt->execute($qdata)) {
437
                while ($row = $stmt->fetch()) {
438
                    $resp[] = [$row['id'], $row['time'], $row['user']];
439
                }
440
            }
441
            
442
        } catch (Exception $e) {
443
            throw new Exception("Error executing function 'getAllUrls'. ".$e->getMessage());
444
        }
445
        return $resp;
446
    }
447
    
448
449
    /*
450
     * @param $pdo PDO
451
     * @param $config Configuration
452
     *
453
     */
454
    public static function findByFrom($pdo, $config, $by = []) {
455
        $resp = [];
456
        try {
457
            $dbFromtable = $config->getFromTableName();
458
            $dbUrltable = $config->getUrlTableName();
459
            $qdata = [];
460
            $tquery = [];
461
            
462
            if (array_key_exists('url', $by) && array_key_exists('id', $by)) {
463
                $qdata = [$by['url'], $by['id']];
464
                $tquery = "SELECT f.* FROM  $dbFromtable f,$dbUrltable u WHERE (f.from_id = u.id and f.url = ?) or f.from_id = ?";                
465
            } else if (array_key_exists('url', $by)) {
466
                $qdata = [$by['url']];
467
                $tquery = "SELECT f.* FROM $dbFromtable f,$dbUrltable u where f.from_id = u.id and u.url = ?";
468
            } else if (array_key_exists('id', $by)) {
469
                $qdata = [$by['id']];
470
                $tquery = "SELECT f.* FROM $dbFromtable f where f.from_id = ?";
471
            } else {
472
                $qdata = [];
473
                $tquery = "SELECT f.* FROM $dbFromtable f";
474
            }
475
                                    
476
            $stmt = $pdo->prepare($tquery);
477
            if ($stmt->execute($qdata)) {
478
                while ($row = $stmt->fetch()) {
479
                    $resp[] = [$row['id'], $row['from_id'], $row['count']];
480
                }
481
            }
482
            
483
        } catch (Exception $e) {
484
            throw new Exception("Error executing function 'findByFrom'. ".$e->getMessage());
485
        }
486
        return $resp;
487
    }
488
    
489
    
490
    
491
    /*
492
     * @param $pdo PDO
493
     * @param $config Configuration
494
     *
495
     */
496
    public static function getCounts($pdo, $config)
497
    {
498
        $resp = [];
499
        try {
500
501
            $dbHitTable = $config->getHitTableName();
502
            $dbUrlTable = $config->getUrlTableName();
503
            $stmt = $pdo->prepare("SELECT h.id, u.url, h.count FROM $dbHitTable h, $dbUrlTable u WHERE h.id=u.id");
504
            if ($stmt->execute()) {
505
                while ($row = $stmt->fetch()) {
506
                    $resp[] = [$row[0], $row[1], $row[2]];
507
                }
508
            }
509
            
510
        } catch (Exception $e) {
511
            throw new Exception("Error reading the database. Method getCounts().".$e->getMessage());
512
        }        
513
        return $resp;
514
    }
515
516
    
517
    /*
518
     * @param $pdo PDO
519
     * @param $config Configuration
520
     *
521
     */
522
    public static function getHitsWithOptions($pdo, $config) {
523
        $resp = [];
524
        try {
525
            
526
            $dbOptionsTable = $config->getOptionsTableName();
527
            $stmt = $pdo->prepare("SELECT o.id, o.time, o.user FROM $dbOptionsTable o");
528
            if ($stmt->execute()) {
529
                while ($row = $stmt->fetch()) {
530
                    $resp[] = ['id'=>$row[0], 'time'=>$row[1], 'user'=>$row[2]];
531
                }
532
            }
533
            
534
        } catch (Exception $e) {
535
            throw new Exception("Error reading the database. Method getCounts().".$e->getMessage());
536
        }
537
        return $resp;
538
    }
539
    
540
    /*
541
     * @param $pdo PDO
542
     * @param $config Configuration
543
     *
544
     */    
545
    public static function getCountsById($pdo, $config) {
0 ignored issues
show
Unused Code introduced by
The parameter $pdo 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

545
    public static function getCountsById(/** @scrutinizer ignore-unused */ $pdo, $config) {

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...
Unused Code introduced by
The parameter $config 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

545
    public static function getCountsById($pdo, /** @scrutinizer ignore-unused */ $config) {

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...
546
        return "Works";
547
    }
548
}
549
550
551
            
552