SessionsActivityComponent   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 170
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 10

Importance

Changes 0
Metric Value
wmc 12
c 0
b 0
f 0
lcom 2
cbo 10
dl 0
loc 170
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 6 1
B startup() 0 29 3
B getOnlineUsers() 0 45 3
A getOnlineStatus() 0 17 2
A getOnlineSessionsForUser() 0 17 3
1
<?php
2
namespace App\Controller\Component;
3
4
use App\Model\Entity\User;
5
use Cake\Controller\Component;
6
use Cake\Event\Event;
7
use Cake\I18n\Time;
8
use Cake\ORM\Entity;
9
use Cake\ORM\TableRegistry;
10
11
class SessionsActivityComponent extends Component
12
{
13
14
    /**
15
     * Request object
16
     *
17
     * @var \Cake\Network\Request
18
     */
19
    protected $_request;
20
21
    /**
22
     * Instance of the Session object
23
     *
24
     * @return void
25
     */
26
    protected $_session;
27
28
    /**
29
     * Initialize properties.
30
     *
31
     * @param array $config The config data.
32
     *
33
     * @return void
34
     */
35
    public function initialize(array $config)
36
    {
37
        $controller = $this->_registry->getController();
38
        $this->_request = $controller->request;
0 ignored issues
show
Documentation Bug introduced by
It seems like $controller->request of type object<Cake\Http\ServerRequest> is incompatible with the declared type object<Cake\Network\Request> of property $_request.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
39
        $this->_session = $controller->request->session();
40
    }
41
42
    /**
43
     * Startup event to trace the user on the website.
44
     *
45
     * @param Event $event The event that was fired.
46
     *
47
     * @return void
48
     */
49
    public function startup(Event $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
50
    {
51
        if (empty($this->_session->id())) {
52
            $this->_session->start();
53
54
            return;
55
        }
56
        $sessions = TableRegistry::get('Sessions');
57
58
        $prefix = isset($this->_request['prefix']) ? $this->_request['prefix'] . '/' : '';
59
        $controller = $prefix . $this->_request['controller'];
60
        $action = $this->_request['action'];
61
        $params = serialize($this->_request->pass);
62
        $expires = time() + ini_get('session.gc_maxlifetime');
63
64
        //@codingStandardsIgnoreStart
65
        $user_id = $this->_session->read('Auth.User.id');
66
        $user_agent = $this->_request->env('HTTP_USER_AGENT');
67
        $user_ip = $this->_request->clientIp();
68
        $full_url = $this->_request->url;
69
        //@codingStandardIgnoreEnd
70
71
        $modified = new Time();
72
73
        $record = compact('controller', 'action', 'params', 'expires', 'user_id', 'user_agent', 'user_ip', 'full_url', 'modified');
74
75
        $record[$sessions->primaryKey()] = $this->_session->id();
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\Table::primaryKey() has been deprecated with message: 3.4.0 Use setPrimaryKey()/getPrimaryKey() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
76
        $sessions->save(new Entity($record));
77
    }
78
79
    /**
80
     * Get the list of the users online.
81
     *
82
     * @return array
83
     */
84
    public function getOnlineUsers()
85
    {
86
        $sessions = TableRegistry::get('Sessions');
87
88
        $output = [
89
            'guests' => 0,
90
            'members' => 0,
91
        ];
92
93
        $records = $sessions
94
            ->find('expires')
95
            ->contain([
96
                'Users' => function ($q) {
97
                    return $q->select([
98
                        'id',
99
                        'username'
100
                    ]);
101
                },
102
                'Users.Groups' => function ($q) {
103
                    return $q->select(['css', 'is_member']);
104
                },
105
            ])
106
            ->select(['Sessions.user_id', 'Sessions.expires'])
107
            ->group('Sessions.user_id')
108
            ->toArray();
109
110
        foreach ($records as $key => $record) {
111
            if (is_null($record->user_id)) {
112
                $output['guests']++;
113
114
                unset($records[$key]);
115
                continue;
116
            } else {
117
                $output['members']++;
118
            }
119
        }
120
121
        //Total visitors.
122
        $output['total'] = $output['guests'] + $output['members'];
123
124
        //Visitor records.
125
        $output['records'] = $records;
126
127
        return $output;
128
    }
129
130
    /**
131
     * Determine if the given user is online or offline.
132
     *
133
     * @param \App\Model\Entity\User $user The user to check.
134
     *
135
     * @return bool
136
     */
137
    public function getOnlineStatus(User $user)
138
    {
139
        $sessions = TableRegistry::get('Sessions');
140
        $online = $sessions
141
            ->find('expires')
142
            ->select(['Sessions.expires', 'Sessions.user_id'])
143
            ->where([
144
                'Sessions.user_id' => $user->id
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Model\Entity\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
145
            ])
146
            ->first();
147
148
        if (!empty($online)) {
149
            return true;
150
        }
151
152
        return false;
153
    }
154
155
    /**
156
     * Get all the sessions online for the given user.
157
     *
158
     * @param int $user The user id.
159
     *
160
     * @return false|array
161
     */
162
    public function getOnlineSessionsForUser($user)
163
    {
164
        if (empty($user) || is_null($user)) {
165
            return false;
166
        }
167
168
        $this->Sessions = TableRegistry::get('Sessions');
0 ignored issues
show
Bug introduced by
The property Sessions does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
169
170
        $sessions = $this->Sessions
171
            ->find('expires')
172
            ->where([
173
                'Sessions.user_id' => $user
174
            ])
175
            ->toArray();
176
177
        return $sessions;
178
    }
179
180
}
181