AccessLogStatistics::defineProperties()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php namespace VojtaSvoboda\UserAccessLog\ReportWidgets;
2
3
use App;
4
use ApplicationException;
5
use Exception;
6
use Backend\Classes\ReportWidgetBase;
7
use VojtaSvoboda\UserAccessLog\Models\AccessLog;
8
9
/**
10
 * AccessLogStatistics overview widget.
11
 *
12
 * @package \VojtaSvoboda\UserAccessLog\ReportWidgets
13
 */
14
class AccessLogStatistics extends ReportWidgetBase
15
{
16
    /**
17
     * Renders the widget.
18
     */
19
    public function render()
20
    {
21
        try {
22
            $this->vars['all'] = $this->getCounts()['all'];
23
            $this->vars['counts'] = $this->getCounts()['counts'];
24
25
        } catch (Exception $ex) {
26
            $this->vars['error'] = $ex->getMessage();
27
            $this->vars['all'] = 0;
28
            $this->vars['counts'] = [];
29
        }
30
31
        return $this->makePartial('widget');
32
    }
33
34
    /**
35
     * Define widget properties
36
     *
37
     * @return array
38
     */
39
    public function defineProperties()
40
    {
41
        return [
42
            'title' => [
43
                'title' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.statistics.title',
44
                'default' => 'Access statistics',
45
                'type' => 'string',
46
                'validationPattern' => '^.+$',
47
                'validationMessage' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.statistics.title_validation'
48
            ],
49
        ];
50
    }
51
52
    /**
53
     * Get data for widget
54
     *
55
     * @return array
56
     */
57
    public function getCounts()
58
    {
59
        $log = AccessLog::all()->groupBy('user_id');
60
61
        $counts = [];
62
        $all = 0;
63
        foreach ($log as $l) {
64
            $first = $l[0];
65
            $user = $first->user ? $first->user : $this->getDeletedFakeUser();
66
            $size = sizeof($l);
67
            $counts[] = [
68
                'size' => $size,
69
                'id' => $first->user_id,
70
                'name' => $user->username
71
            ];
72
            $all += $size;
73
        }
74
75
        return [
76
            'all' => $all,
77
            'counts' => $counts
78
        ];
79
    }
80
81
    /**
82
     * Get fake User object for deleted users
83
     *
84
     * @return \stdClass
85
     */
86
    public function getDeletedFakeUser()
87
    {
88
        $user = new \stdClass();
89
        $user->username = 'Deleted users';
90
        $user->name = 'Deleted';
91
92
        return $user;
93
    }
94
}
95