AccessLogChartLine::loadData()   F
last analyzed

Complexity

Conditions 12
Paths 341

Size

Total Lines 87

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 87
rs 3.7803
c 0
b 0
f 0
cc 12
nc 341
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace VojtaSvoboda\UserAccessLog\ReportWidgets;
2
3
use App;
4
use ApplicationException;
5
use Carbon\Carbon;
6
use Exception;
7
use Backend\Classes\ReportWidgetBase;
8
use VojtaSvoboda\UserAccessLog\Models\AccessLog;
9
use RainLab\User\Models\User;
10
11
/**
12
 * AccessLogChartLine overview widget.
13
 *
14
 * @package namespace VojtaSvoboda\UserAccessLog\ReportWidgets
15
 */
16
class AccessLogChartLine extends ReportWidgetBase
17
{
18
    /**
19
     * Renders the widget.
20
     */
21
    public function render()
22
    {
23
        try {
24
            $this->vars['all'] = $this->loadData()['all'];
25
            $this->vars['rows'] = $this->loadData()['user_rows'];
26
            $this->vars['users'] = $this->loadData()['users'];
27
28
        } catch (Exception $ex) {
29
            $this->vars['error'] = $ex->getMessage();
30
            $this->vars['all'] = 0;
31
            $this->vars['users'] = [];
32
            $this->vars['rows'] = [];
33
        }
34
35
        return $this->makePartial('widget');
36
    }
37
38
	public function defineProperties()
39
	{
40
		return [
41
			'title' => [
42
                'title' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.chartline.title',
43
                'default' => 'Access statistics in time each user',
44
				'type' => 'string',
45
				'validationPattern' => '^.+$',
46
				'validationMessage' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.chartline.title_validation',
47
			],
48
            'days' => [
49
                'title' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.chartline.days_title',
50
                'default' => '30',
51
                'type' => 'string',
52
                'validationPattern' => '^[0-9]+$',
53
            ]
54
		];
55
	}
56
57
    protected function loadData()
58
    {
59
        $days = $this->property('days');
60
        if (!$days) {
61
            throw new ApplicationException('Invalid days value: ' . $days);
62
        }
63
64
        // all accesses for last month
65
        $items = AccessLog::where('created_at', '>=', Carbon::now()->subDays($days)->format('Y-m-d'))->get();
66
67
        // parse data
68
        $all = [];
69
        $users = [];
70
        $user_rows = [];
71
        foreach ($items as $item)
72
        {
73
            // user
74
            $user_id = $item->user_id ? $item->user_id : 0;
75
            $users[$user_id] = $user_id > 0 ? User::find($user_id) : $this->getDeletedFakeUser();
76
77
            // date
78
            $timestamp = strtotime($item->created_at) * 1000;
79
            $day = Carbon::createFromFormat('Y-m-d H:i:s', $item->created_at)->format('Y-m-d');
80
81
            if (isset($user_rows[$user_id][$day])) {
82
                $user_rows[$user_id][$day][1]++;
83
            } else {
84
                $user_rows[$user_id][$day] = [$timestamp, 1];
85
            }
86
87
            // init empty day
88
            if (!isset($all[$day])) {
89
                $all[$day] = [
90
                    'timestamp' => $timestamp,
91
                    'date' => $day,
92
                    'count' => 0,
93
                ];
94
            }
95
96
            // increase count
97
            $all[$day]['count']++;
98
        }
99
100
        // we need at least two days, to display chart
101
        if (sizeof($all) == 1) {
102
            $day = reset($all);
103
            $date = Carbon::createFromFormat('Y-m-d', $day['date'])->subDays(1);
104
            $dateFormated = $date->format('Y-m-d');
105
            $all[$dateFormated] = [
106
                'timestamp' => $date->timestamp * 1000,
107
                'date' => $dateFormated,
108
                'count' => 0,
109
            ];
110
        }
111
112
        // transform user line to json
113
        foreach ($user_rows as $key => $user_row)
114
        {
115
            $rows = [];
116
            foreach($user_row as $row) {
117
                $rows[] = [
118
                    $row[0],
119
                    $row[1],
120
                ];
121
            }
122
123
            // we need at least two days, to display chart
124
            if (sizeof($rows) == 1) {
125
                $first = reset($rows);
126
                $rows[] = [$first[0] - 86400000, 0];
127
            }
128
129
            $user_rows[$key] = $rows;
130
        }
131
132
        // count all
133
        $all_render = [];
134
        foreach ($all as $a) {
135
            $all_render[] = [$a['timestamp'], $a['count']];
136
        }
137
138
        return [
139
            'all' => $all_render,
140
            'user_rows' => $user_rows,
141
            'users' => $users,
142
        ];
143
    }
144
145
    /**
146
     * Get fake User object for deleted users
147
     *
148
     * @return \stdClass
149
     */
150
    public function getDeletedFakeUser()
151
    {
152
        $user = new \stdClass();
153
        $user->username = 'Deleted users';
154
        $user->name = 'Deleted';
155
156
        return $user;
157
    }
158
}
159