Completed
Push — master ( 243903...9a7d92 )
by ARCANEDEV
9s
created

Tracker   B

Complexity

Total Complexity 33

Size/Duplication

Total Lines 440
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Test Coverage

Coverage 99.18%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 33
c 1
b 0
f 0
lcom 1
cbo 17
dl 0
loc 440
ccs 121
cts 122
cp 0.9918
rs 7.3857

25 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A app() 0 4 1
A config() 0 4 1
A getConfig() 0 4 1
A setRequest() 0 14 1
A trackRequest() 0 15 2
A trackMatchedRoute() 0 14 3
A trackException() 0 8 1
A enable() 0 4 2
A disable() 0 4 2
A isEnabled() 0 4 1
A trackIfEnabled() 0 6 3
A mergeSessionData() 0 6 1
A mergeSessionActivityData() 0 6 1
A getSessionId() 0 20 1
A getPathId() 0 8 1
A getQueryId() 0 8 1
A getUserId() 0 6 1
A getDeviceId() 0 6 1
A getGeoIpId() 0 8 1
A getAgentId() 0 6 1
A getRefererId() 0 9 1
A getCookieId() 0 8 2
A getLanguageId() 0 6 1
A isRobot() 0 7 1
1
<?php namespace Arcanedev\LaravelTracker;
2
3
use Arcanedev\LaravelTracker\Contracts\Tracker as TrackerContract;
4
use Exception;
5
use Illuminate\Contracts\Foundation\Application;
6
use Illuminate\Http\Request;
7
use Illuminate\Routing\Route;
8
9
/**
10
 * Class     Tracker
11
 *
12
 * @package  Arcanedev\LaravelTracker
13
 * @author   ARCANEDEV <[email protected]>
14
 */
15
class Tracker implements TrackerContract
16
{
17
    /* ------------------------------------------------------------------------------------------------
18
     |  Traits
19
     | ------------------------------------------------------------------------------------------------
20
     */
21
    use Traits\TrackersMaker;
22
23
    /* ------------------------------------------------------------------------------------------------
24
     |  Properties
25
     | ------------------------------------------------------------------------------------------------
26
     */
27
    /**
28
     * The application container.
29
     *
30
     * @var \Illuminate\Contracts\Foundation\Application
31
     */
32
    protected $app;
33
34
    /**
35
     * The request instance.
36
     *
37
     * @var \Illuminate\Http\Request
38
     */
39
    private $request;
40
41
    /**
42
     * Tracking enabled status.
43
     *
44
     * @var  bool
45
     */
46
    protected $enabled = false;
47
48
    /**
49
     * The current session data.
50
     *
51
     * @var array
52
     */
53
    protected $sessionData = [
54
        'user_id'     => null,
55
        'device_id'   => null,
56
        'agent_id'    => null,
57
        'geoip_id'    => null,
58
        'referer_id'  => null,
59
        'cookie_id'   => null,
60
        'language_id' => null,
61
        'client_ip'   => '',
62
        'is_robot'    => false,
63
        'user_agent'  => '',
64
    ];
65
66
    /**
67
     * The current session activity data.
68
     *
69
     * @var array
70
     */
71
    protected $sessionActivityData = [
72
        'session_id'    => null,
73
        'path_id'       => null,
74
        'query_id'      => null,
75
        'referer_id'    => null,
76
        'route_path_id' => null,
77
        'error_id'      => null,
78
        'method'        => '',
79
        'is_ajax'       => false,
80
        'is_secure'     => false,
81
        'is_json'       => false,
82
        'wants_json'    => false,
83
    ];
84
85
    /* ------------------------------------------------------------------------------------------------
86
     |  Constructor
87
     | ------------------------------------------------------------------------------------------------
88
     */
89
    /**
90
     * Tracker constructor.
91
     *
92
     * @param  \Illuminate\Contracts\Foundation\Application  $app
93
     */
94 234
    public function __construct(Application $app)
95
    {
96 234
        $this->app     = $app;
97 234
        $this->enabled = $this->getConfig('enabled', $this->enabled);
98 234
    }
99
100
    /* ------------------------------------------------------------------------------------------------
101
     |  Getters & Setters
102
     | ------------------------------------------------------------------------------------------------
103
     */
104
    /**
105
     * Get the application instance.
106
     *
107
     * @return \Illuminate\Contracts\Foundation\Application
108
     */
109 234
    protected function app()
110
    {
111 234
        return $this->app;
112
    }
113
114
    /**
115
     * Get the config repository.
116
     *
117
     * @return \Illuminate\Contracts\Config\Repository
118
     */
119 234
    private function config()
120
    {
121 234
        return $this->make('config');
122
    }
123
124
    /**
125
     * Get the tracker config.
126
     *
127
     * @param  string      $key
128
     * @param  mixed|null  $default
129
     *
130
     * @return mixed
131
     */
132 234
    private function getConfig($key, $default = null)
133
    {
134 234
        return $this->config()->get("laravel-tracker.$key", $default);
135
    }
136
137
    /**
138
     * Set the request.
139
     *
140
     * @param  \Illuminate\Http\Request  $request
141
     *
142
     * @return self
143
     */
144 12
    private function setRequest(Request $request)
145
    {
146 12
        $this->mergeSessionActivityData([
147 12
            'method'      => $request->method(),
148 12
            'is_ajax'     => $request->ajax(),
149 12
            'is_secure'   => $request->isSecure(),
150 12
            'is_json'     => $request->isJson(),
151 12
            'wants_json'  => $request->wantsJson(),
152 6
        ]);
153
154 12
        $this->request = $request;
155
156 12
        return $this;
157
    }
158
159
    /* ------------------------------------------------------------------------------------------------
160
     |  Main Functions
161
     | ------------------------------------------------------------------------------------------------
162
     */
163
    /**
164
     * Start the tracking.
165
     *
166
     * @param  \Illuminate\Http\Request $request
167
     */
168 12
    public function trackRequest(Request $request)
169
    {
170 12
        if ($this->isEnabled()) {
171 12
            $this->setRequest($request);
172
173 12
            $this->mergeSessionActivityData([
174 12
                'session_id' => $this->getSessionId(),
175 12
                'path_id'    => $this->getPathId(),
176 12
                'query_id'   => $this->getQueryId(),
177 12
                'referer_id' => $this->getRefererId(),
178 6
            ]);
179
180 12
            $id = $this->getSessionActivityTracker()->track($this->sessionActivityData);
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
181 6
        }
182 12
    }
183
184
    /**
185
     * Track the matched route.
186
     *
187
     * @param  \Illuminate\Routing\Route  $route
188
     * @param  \Illuminate\Http\Request   $request
189
     */
190 12
    public function trackMatchedRoute(Route $route, Request $request)
191
    {
192 12
        if ( ! $this->isEnabled()) return;
193
194 12
        $tracker = $this->getRouteTracker();
195
196 12
        if ($tracker->isTrackable($route)) {
197 12
            $this->mergeSessionActivityData([
198 12
                'route_path_id' => $tracker->track($route, $request),
199 6
            ]);
200 6
        }
201
        else
202
            $this->disable();
203 12
    }
204
205
    /**
206
     * Track the exception.
207
     *
208
     * @param  \Exception  $exception
209
     */
210 4
    public function trackException(Exception $exception)
211
    {
212
        $id = $this->trackIfEnabled('errors', function () use ($exception) {
213 4
            $this->getErrorTracker()->track($exception);
214 4
        });
215
216 4
        $this->mergeSessionActivityData(['error_id' => $id]);
217 4
    }
218
219
    /**
220
     * Enable the tracking.
221
     */
222 234
    public function enable()
223
    {
224 234
        if ( ! $this->isEnabled()) $this->enabled = true;
225 234
    }
226
227
    /**
228
     * Disable the tracking.
229
     */
230 6
    public function disable()
231
    {
232 6
        if ($this->isEnabled()) $this->enabled = false;
233 6
    }
234
235
    /* ------------------------------------------------------------------------------------------------
236
     |  Check Functions
237
     | ------------------------------------------------------------------------------------------------
238
     */
239
    /**
240
     * Check if the tracker is enabled.
241
     *
242
     * @return bool
243
     */
244 234
    public function isEnabled()
245
    {
246 234
        return $this->enabled;
247
    }
248
249
    /**
250
     * Track the trackable if enabled.
251
     *
252
     * @param  string      $key
253
     * @param  \Closure    $callback
254
     * @param  mixed|null  $default
255
     *
256
     * @return mixed
257
     */
258 16
    private function trackIfEnabled($key, \Closure $callback, $default = null)
259
    {
260 16
        return $this->isEnabled()
261 16
            ? ($this->getConfig("tracking.$key", false) ? $callback() : $default)
262 16
            : $default;
263
    }
264
265
    /* ------------------------------------------------------------------------------------------------
266
     |  Other Functions
267
     | ------------------------------------------------------------------------------------------------
268
     */
269
    /**
270
     * Merge session data.
271
     *
272
     * @param  array  $data
273
     *
274
     * @return self
275
     */
276 12
    private function mergeSessionData(array $data)
277
    {
278 12
        $this->sessionData = array_merge($this->sessionData, $data);
279
280 12
        return $this;
281
    }
282
283
    /**
284
     * Merge session activity data.
285
     *
286
     * @param  array  $data
287
     *
288
     * @return self
289
     */
290 16
    private function mergeSessionActivityData(array $data)
291
    {
292 16
        $this->sessionActivityData = array_merge($this->sessionActivityData, $data);
293
294 16
        return $this;
295
    }
296
297
    /**
298
     * Get the stored session id.
299
     *
300
     * @return int
301
     */
302 12
    private function getSessionId()
303
    {
304 12
        $tracker     = $this->getSessionTracker();
305 12
        $sessionData = $tracker->checkData($this->sessionData, [
306 12
            'user_id'     => $this->getUserId(),
307 12
            'device_id'   => $this->getDeviceId(),
308 12
            'client_ip'   => $this->request->getClientIp(),
309 12
            'geoip_id'    => $this->getGeoIpId(),
310 12
            'agent_id'    => $this->getAgentId(),
311 12
            'referer_id'  => $this->getRefererId(),
312 12
            'cookie_id'   => $this->getCookieId(),
313 12
            'language_id' => $this->getLanguageId(),
314 12
            'is_robot'    => $this->isRobot(),
315 12
            'user_agent'  => $this->getUserAgentTracker()->getUserAgentParser()->getOriginalUserAgent(),
316 6
        ]);
317
318 12
        $this->mergeSessionData($sessionData);
319
320 12
        return $tracker->track($this->sessionData);
321
    }
322
323
    /**
324
     * Track the path.
325
     *
326
     * @return int|null
327
     */
328 12
    private function getPathId()
329
    {
330
        return $this->trackIfEnabled('paths', function () {
331 12
            return $this->getPathTracker()->track(
332 12
                $this->request->path()
333 6
            );
334 12
        });
335
    }
336
337
    /**
338
     * Track the query.
339
     *
340
     * @return int|null
341
     */
342 12
    private function getQueryId()
343
    {
344
        return $this->trackIfEnabled('path-queries', function () {
345 12
            return $this->getQueryTracker()->track(
346 12
                $this->request->query()
347 6
            );
348 12
        });
349
    }
350
351
    /**
352
     * Get the user id.
353
     *
354
     * @return int|null
355
     */
356 12
    private function getUserId()
357
    {
358
        return $this->trackIfEnabled('users', function () {
359 12
            return $this->getUserTracker()->track();
360 12
        });
361
    }
362
363
    /**
364
     * Get the tracked device id.
365
     *
366
     * @return int|null
367
     */
368 12
    private function getDeviceId()
369
    {
370
        return $this->trackIfEnabled('devices', function () {
371 12
            return $this->getDeviceTracker()->track();
372 12
        });
373
    }
374
375
    /**
376
     * Get the tracked ip address ip.
377
     *
378
     * @return int|null
379
     */
380 12
    private function getGeoIpId()
381
    {
382
        return $this->trackIfEnabled('geoip', function () {
383 12
            return $this->getGeoIpTracker()->track(
384 12
                $this->request->getClientIp()
385 6
            );
386 12
        });
387
    }
388
389
    /**
390
     * Get the tracked user agent id.
391
     *
392
     * @return int|null
393
     */
394 12
    private function getAgentId()
395
    {
396
        return $this->trackIfEnabled('user-agents', function () {
397 12
            return $this->getUserAgentTracker()->track();
398 12
        });
399
    }
400
401
    /**
402
     * Get the tracked referer id.
403
     *
404
     * @return int|null
405
     */
406 12
    private function getRefererId()
407
    {
408
        return $this->trackIfEnabled('referers', function () {
409 12
            return $this->getRefererTracker()->track(
410 12
                $this->request->headers->get('referer'),
411 12
                $this->request->url()
412 6
            );
413 12
        });
414
    }
415
416
    /**
417
     * Get the tracked cookie id.
418
     *
419
     * @return int|null
420
     */
421 12
    private function getCookieId()
422
    {
423
        return $this->trackIfEnabled('cookies', function () {
424 12
            return ! is_null($name = $this->getConfig('cookie.name'))
425 6
                ? $this->getCookieTracker()->track($this->request->cookie($name))
426 12
                : null;
427 12
        });
428
    }
429
430
    /**
431
     * Get the tracked language id.
432
     *
433
     * @return int|null
434
     */
435
    private function getLanguageId()
436
    {
437 12
        return $this->trackIfEnabled('languages', function () {
438 12
            return $this->getLanguageTracker()->track();
439 12
        });
440
    }
441
442
    /**
443
     * Check if the visitor is a robot.
444
     *
445
     * @return bool
446
     */
447 12
    protected function isRobot()
448
    {
449
        /** @var  \Arcanedev\LaravelTracker\Contracts\Detectors\CrawlerDetector  $crawler */
450 12
        $crawler = $this->make(\Arcanedev\LaravelTracker\Contracts\Detectors\CrawlerDetector::class);
451
452 12
        return $crawler->isRobot();
453
    }
454
}
455