Completed
Push — master ( 41402d...8d67df )
by Vojta
02:16
created

AccessLogStatistics::getDeletedFakeUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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