Completed
Push — master ( 1d95ec...eb6b30 )
by Vojta
02:03
created

AccessLogChartLine::loadData()   C

Complexity

Conditions 10
Paths 103

Size

Total Lines 62
Code Lines 36

Duplication

Lines 5
Ratio 8.06 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 5
loc 62
rs 6.348
cc 10
eloc 36
nc 103
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
2
3
namespace VojtaSvoboda\UserAccessLog\ReportWidgets;
4
5
use App;
6
use ApplicationException;
7
use Carbon\Carbon;
8
use Exception;
9
use Backend\Classes\ReportWidgetBase;
10
use VojtaSvoboda\UserAccessLog\Models\AccessLog;
11
use RainLab\User\Models\User;
12
13
/**
14
 * Demands count overview widget.
15
 *
16
 * @package namespace VojtaSvoboda\UserAccessLog\ReportWidgets
17
 */
18
class AccessLogChartLine extends ReportWidgetBase
19
{
20
    /**
21
     * Renders the widget.
22
     */
23
    public function render()
24
    {
25
        try {
26
            $this->vars['all'] = $this->loadData()['all'];
27
            $this->vars['rows'] = $this->loadData()['user_rows'];
28
            $this->vars['users'] = $this->loadData()['users'];
29
30
        } catch (Exception $ex) {
31
            $this->vars['error'] = $ex->getMessage();
32
            $this->vars['all'] = 0;
33
            $this->vars['users'] = [];
34
            $this->vars['rows'] = [];
35
        }
36
37
        return $this->makePartial('widget');
38
    }
39
40 View Code Duplication
	public function defineProperties()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
41
	{
42
		return [
43
			'title' => [
44
                'title' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.chartline.title',
45
                'default' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.chartline.title_default',
46
				'type' => 'string',
47
				'validationPattern' => '^.+$',
48
				'validationMessage' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.chartline.title_validation',
49
			],
50
            'days' => [
51
                'title' => 'vojtasvoboda.useraccesslog::lang.reportwidgets.chartline.days_title',
52
                'default' => '30',
53
                'type' => 'string',
54
                'validationPattern' => '^[0-9]+$',
55
            ]
56
		];
57
	}
58
59
    protected function loadData()
60
    {
61
        $days = $this->property('days');
62
        if (!$days) {
63
            throw new ApplicationException('Invalid days value: ' . $days);
64
        }
65
66
        // all accesses for last month
67
        $items = AccessLog::where('created_at', '>=', Carbon::now()->subDays($days)->format('Y-m-d'))->get();
68
69
        // parse data
70
        $all = [];
71
        $users = [];
72
        $user_rows = [];
73
        foreach ($items as $item)
74
        {
75
            // user
76
            $user_id = $item->user_id ? $item->user_id : 0;
77
            $users[$user_id] = $user_id > 0 ? User::find($user_id) : $this->getDeletedFakeUser();
78
79
            // date
80
            $timestamp = strtotime($item->created_at) * 1000;
81
            $day = Carbon::createFromFormat('Y-m-d H:i:s', $item->created_at)->format('Y-m-d');
82
83
            if (isset($user_rows[$user_id][$day])) {
84
                $user_rows[$user_id][$day][1]++;
85
            } else {
86
                $user_rows[$user_id][$day] = [$timestamp, 1];
87
            }
88
89 View Code Duplication
            if (isset($all[$day])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
                $all[$day][1]++;
91
            } else {
92
                $all[$day] = [$timestamp, 1];
93
            }
94
        }
95
96
        // transform user line to json
97
        foreach ($user_rows as $key => $user_row) {
98
            $rows = [];
99
            foreach($user_row as $row) {
100
                $rows[] = [
101
                    $row[0],
102
                    $row[1],
103
                ];
104
            }
105
            $user_rows[$key] = str_replace('"', '', substr(substr(json_encode($rows), 1), 0, -1));
106
        }
107
108
        // count all
109
        $all_render = [];
110
        foreach ($all as $a) {
111
            $all_render[] = [$a[0], $a[1]];
112
        }
113
        $all = str_replace('"', '', substr(substr(json_encode($all_render), 1), 0, -1));
114
115
        return [
116
            'all' => $all,
117
            'user_rows' => $user_rows,
118
            'users' => $users,
119
        ];
120
    }
121
122
    /**
123
     * Get fake User object for deleted users
124
     *
125
     * @return \stdClass
126
     */
127
    public function getDeletedFakeUser()
128
    {
129
        $user = new \stdClass();
130
        $user->username = 'Deleted users';
131
        $user->name = 'Deleted';
132
133
        return $user;
134
    }
135
136
}
137