Passed
Push — master ( 78321f...a5654d )
by Paul
06:56
created

StatsService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 2
c 1
b 1
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Devpri\Tinre\Services;
4
5
use Carbon\Carbon;
6
use Exception;
7
use Illuminate\Support\Facades\DB;
8
9
class StatsService
10
{
11
    protected $driver;
12
13
    public function __construct()
14
    {
15
        $connection = config('database.default');
16
        $this->driver = config("database.connections.{$connection}.driver");
17
    }
18
19
    public function getClicks(int $urlId, array $date): array
20
    {
21
        $dates = DB::table('clicks')
22
            ->select(DB::raw("{$this->getDateFromat($date)} as label"), DB::raw('count(*) as value'))
23
            ->where('url_id', $urlId)
24
            ->whereBetween('created_at', $date)
25
            ->groupBy('label')
26
            ->get()
27
            ->toArray();
28
29
        return $dates;
30
    }
31
32
    public function getData(string $column, int $urlId, array $date): object
33
    {
34
        $dbFunction = $this->driver === 'pgsql' ? 'COALESCE' : 'IFNULL';
35
36
        $data = DB::table('clicks')->where('url_id', $urlId)
37
            ->select(DB::raw("{$dbFunction}({$column}, 'UNK') as label"), DB::raw('count(*) as value'))
38
            ->whereBetween('created_at', $date)
39
            ->groupBy('label')
40
            ->orderBy('value', 'DESC')
41
            ->paginate(10);
42
43
        return $data;
44
    }
45
46
    protected function getDateFromat(array $date): string
47
    {
48
        $startDate = Carbon::parse($date[0]);
49
        $endDate = Carbon::parse($date[1]);
50
51
        $diff = $startDate->diffInDays($endDate);
52
53
        $dateFormat = '%Y-%m-%d';
54
        $pgsqlDateFormat = 'YYYY-MM-DD';
55
56
        if ($diff === 0) {
57
            $dateFormat = '%Y-%m-%d %H:00';
58
            $pgsqlDateFormat = 'YYYY-MM-DD HH24:00';
59
        }
60
61
        if ($diff > 90) {
62
            $dateFormat = '%Y-%m';
63
            $pgsqlDateFormat = 'YYYY-MM';
64
        }
65
66
        if ($diff > 1092) {
67
            $dateFormat = '%Y';
68
            $pgsqlDateFormat = 'YYYY';
69
        }
70
71
        switch ($this->driver) {
72
            case 'mysql':
73
                return "DATE_FORMAT(created_at, '{$dateFormat}')";
74
            case 'pgsql':
75
                return "to_char(created_at, '{$pgsqlDateFormat}')";
76
            case 'sqlite':
77
                return "strftime('{$dateFormat}', created_at)";
78
            default:
79
                throw new Exception('Unsupported driver.');
80
        }
81
    }
82
}
83