Completed
Push — master ( 7a5f39...3a2708 )
by ARCANEDEV
09:08
created

Tracker   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 438
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 99.17%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 32
lcom 1
cbo 6
dl 0
loc 438
rs 9.6
c 1
b 0
f 0
ccs 120
cts 121
cp 0.9917

25 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A config() 0 4 1
A getConfig() 0 4 1
A setRequest() 0 14 1
A getUserAgentParser() 0 4 1
A mergeSessionData() 0 6 1
A mergeSessionActivityData() 0 6 1
A track() 0 15 2
A trackMatchedRoute() 0 12 2
A trackException() 0 8 1
A enable() 0 4 2
A disable() 0 4 2
A isEnabled() 0 4 1
A getSessionId() 0 19 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
A trackIfEnabled() 0 6 3
1
<?php namespace Arcanedev\LaravelTracker;
2
3
use Arcanedev\LaravelTracker\Contracts\Detectors\CrawlerDetector;
4
use Arcanedev\LaravelTracker\Contracts\Tracker as TrackerContract;
5
use Arcanedev\LaravelTracker\Contracts\TrackingManager as TrackingManagerContract;
6
use Illuminate\Contracts\Foundation\Application;
7
use Illuminate\Http\Request;
8
use Illuminate\Routing\Route;
9
10
/**
11
 * Class     Tracker
12
 *
13
 * @package  Arcanedev\LaravelTracker
14
 * @author   ARCANEDEV <[email protected]>
15
 */
16
class Tracker implements TrackerContract
17
{
18
    /* ------------------------------------------------------------------------------------------------
19
     |  Properties
20
     | ------------------------------------------------------------------------------------------------
21
     */
22
    /**
23
     * The application container.
24
     *
25
     * @var \Illuminate\Contracts\Foundation\Application
26
     */
27
    protected $app;
28
29
    /**
30
     * The request instance.
31
     *
32
     * @var \Illuminate\Http\Request
33
     */
34
    private $request;
35
36
    /**
37
     * The tracking manager.
38
     *
39
     * @var \Arcanedev\LaravelTracker\Contracts\TrackingManager
40
     */
41
    private $manager;
42
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
        'referrer_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
        'referrer_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
     * @param  \Arcanedev\LaravelTracker\Contracts\TrackingManager  $manager
94
     */
95 216
    public function __construct(Application $app, TrackingManagerContract $manager)
96
    {
97 216
        $this->app     = $app;
98 216
        $this->manager = $manager;
99 216
        $this->enabled = $this->getConfig('enabled', $this->enabled);
100 216
    }
101
102
    /* ------------------------------------------------------------------------------------------------
103
     |  Getters & Setters
104
     | ------------------------------------------------------------------------------------------------
105
     */
106
    /**
107
     * Get the config repository.
108
     *
109
     * @return \Illuminate\Contracts\Config\Repository
110
     */
111 216
    private function config()
112
    {
113 216
        return $this->app['config'];
114
    }
115
116
    /**
117
     * Get the tracker config.
118
     *
119
     * @param  string      $key
120
     * @param  mixed|null  $default
121
     *
122
     * @return mixed
123
     */
124 216
    private function getConfig($key, $default = null)
125
    {
126 216
        return $this->config()->get("laravel-tracker.$key", $default);
127
    }
128
129
    /**
130
     * Set the request.
131
     *
132
     * @param  \Illuminate\Http\Request  $request
133
     *
134
     * @return self
135
     */
136 6
    private function setRequest(Request $request)
137
    {
138 6
        $this->mergeSessionActivityData([
139 6
            'method'      => $request->method(),
140 6
            'is_ajax'     => $request->ajax(),
141 6
            'is_secure'   => $request->isSecure(),
142 6
            'is_json'     => $request->isJson(),
143 6
            'wants_json'  => $request->wantsJson(),
144 3
        ]);
145
146 6
        $this->request = $request;
147
148 6
        return $this;
149
    }
150
151
    /**
152
     * Get the user agent parser.
153
     *
154
     * @return \Arcanedev\LaravelTracker\Contracts\Parsers\UserAgentParser
155
     */
156 6
    public function getUserAgentParser()
157
    {
158 6
        return $this->manager->getUserAgentTracker()->getUserAgentParser();
159
    }
160
161
    /**
162
     * Merge session data.
163
     *
164
     * @param  array  $data
165
     *
166
     * @return self
167
     */
168 6
    private function mergeSessionData(array $data)
169
    {
170 6
        $this->sessionData = array_merge($this->sessionData, $data);
171
172 6
        return $this;
173
    }
174
175
    /**
176
     * Merge session activity data.
177
     *
178
     * @param  array  $data
179
     *
180
     * @return self
181
     */
182 10
    private function mergeSessionActivityData(array $data)
183
    {
184 10
        $this->sessionActivityData = array_merge($this->sessionActivityData, $data);
185
186 10
        return $this;
187
    }
188
189
    /* ------------------------------------------------------------------------------------------------
190
     |  Main Functions
191
     | ------------------------------------------------------------------------------------------------
192
     */
193
    /**
194
     * Start the tracking.
195
     *
196
     * @param  \Illuminate\Http\Request $request
197
     */
198 6
    public function track(Request $request)
199
    {
200 6
        if ($this->isEnabled()) {
201 6
            $this->setRequest($request);
202
203 6
            $this->mergeSessionActivityData([
204 6
                'session_id'  => $this->getSessionId(),
205 6
                'path_id'     => $this->getPathId(),
206 6
                'query_id'    => $this->getQueryId(),
207 6
                'referrer_id' => $this->getRefererId(),
208 3
            ]);
209
210 6
            $id = $this->manager->trackActivity($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...
211 3
        }
212 6
    }
213
214
    /**
215
     * Track the matched route.
216
     *
217
     * @param  \Illuminate\Routing\Route  $route
218
     * @param  \Illuminate\Http\Request   $request
219
     */
220 6
    public function trackMatchedRoute(Route $route, Request $request)
221
    {
222 6
        $tracker = $this->manager->getRouteTracker();
223
224 6
        if ($tracker->isTrackable($route)) {
225 6
            $this->mergeSessionActivityData([
226 6
                'route_path_id' => $tracker->track($route, $request),
227 3
            ]);
228 3
        }
229
        else
230
            $this->disable();
231 6
    }
232
233
    /**
234
     * Track the exception.
235
     *
236
     * @param  \Exception  $exception
237
     */
238 4
    public function trackException(\Exception $exception)
239
    {
240
        $id = $this->trackIfEnabled('errors', function () use ($exception) {
241 4
            $this->manager->trackException($exception);
242 4
        });
243
244 4
        $this->mergeSessionActivityData(['error_id' => $id]);
245 4
    }
246
247
    /**
248
     * Enable the tracker.
249
     */
250 6
    public function enable()
251
    {
252 6
        if ( ! $this->isEnabled()) $this->enabled = true;
253 6
    }
254
255
    /**
256
     * Disable the tracker.
257
     */
258 6
    public function disable()
259
    {
260 6
        if ($this->isEnabled()) $this->enabled = false;
261 6
    }
262
263
    /* ------------------------------------------------------------------------------------------------
264
     |  Check Functions
265
     | ------------------------------------------------------------------------------------------------
266
     */
267
    /**
268
     * Check if the tracker is enabled.
269
     *
270
     * @return bool
271
     */
272 28
    public function isEnabled()
273
    {
274 28
        return $this->enabled;
275
    }
276
277
    /* ------------------------------------------------------------------------------------------------
278
     |  Other Functions
279
     | ------------------------------------------------------------------------------------------------
280
     */
281
    /**
282
     * Get the stored session id.
283
     *
284
     * @return int
285
     */
286 6
    private function getSessionId()
287
    {
288 6
        $sessionData = $this->manager->checkSessionData($this->sessionData, [
289 6
            'user_id'      => $this->getUserId(),
290 6
            'device_id'    => $this->getDeviceId(),
291 6
            'client_ip'    => $this->request->getClientIp(),
292 6
            'geoip_id'     => $this->getGeoIpId(),
293 6
            'agent_id'     => $this->getAgentId(),
294 6
            'referrer_id'  => $this->getRefererId(),
295 6
            'cookie_id'    => $this->getCookieId(),
296 6
            'language_id'  => $this->getLanguageId(),
297 6
            'is_robot'     => $this->isRobot(),
298 6
            'user_agent'   => $this->getUserAgentParser()->getOriginalUserAgent(),
299 3
        ]);
300
301 6
        $this->mergeSessionData($sessionData);
302
303 6
        return $this->manager->trackSession($this->sessionData);
304
    }
305
306
    /**
307
     * Track the path.
308
     *
309
     * @return int|null
310
     */
311 6
    private function getPathId()
312
    {
313
        return $this->trackIfEnabled('paths', function () {
314 6
            return $this->manager->trackPath(
315 6
                $this->request->path()
316 3
            );
317 6
        });
318
    }
319
320
    /**
321
     * Track the query.
322
     *
323
     * @return int|null
324
     */
325 6
    private function getQueryId()
326
    {
327
        return $this->trackIfEnabled('path-queries', function () {
328 6
            return $this->manager->trackQuery(
329 6
                $this->request->query()
330 3
            );
331 6
        });
332
    }
333
334
    /**
335
     * Get the user id.
336
     *
337
     * @return int|null
338
     */
339 6
    private function getUserId()
340
    {
341
        return $this->trackIfEnabled('users', function () {
342 6
            return $this->manager->trackUser();
343 6
        });
344
    }
345
346
    /**
347
     * Get the tracked device id.
348
     *
349
     * @return int|null
350
     */
351 6
    private function getDeviceId()
352
    {
353
        return $this->trackIfEnabled('devices', function () {
354 6
            return $this->manager->trackDevice();
355 6
        });
356
    }
357
358
    /**
359
     * Get the tracked ip address ip.
360
     *
361
     * @return int|null
362
     */
363 6
    private function getGeoIpId()
364
    {
365
        return $this->trackIfEnabled('geoip', function () {
366 6
            return $this->manager->trackGeoIp(
367 6
                $this->request->getClientIp()
368 3
            );
369 6
        });
370
    }
371
372
    /**
373
     * Get the tracked user agent id.
374
     *
375
     * @return int|null
376
     */
377 6
    private function getAgentId()
378
    {
379
        return $this->trackIfEnabled('user-agents', function () {
380 6
            return $this->manager->trackUserAgent();
381 6
        });
382
    }
383
384
    /**
385
     * Get the tracked referer id.
386
     *
387
     * @return int|null
388
     */
389 6
    private function getRefererId()
390
    {
391
        return $this->trackIfEnabled('referers', function () {
392 6
            return $this->manager->trackReferer(
393 6
                $this->request->headers->get('referer'),
394 6
                $this->request->url()
395 3
            );
396 6
        });
397
    }
398
399
    /**
400
     * Get the tracked cookie id.
401
     *
402
     * @return int|null
403
     */
404 6
    private function getCookieId()
405
    {
406
        return $this->trackIfEnabled('cookies', function () {
407 6
            return ! is_null($name = $this->getConfig('cookie.name'))
408 3
                ? $this->manager->trackCookie($this->request->cookie($name))
409 6
                : null;
410 6
        });
411
    }
412
413
    /**
414
     * Get the tracked language id.
415
     *
416
     * @return int|null
417
     */
418
    private function getLanguageId()
419
    {
420 6
        return $this->trackIfEnabled('languages', function () {
421 6
            return $this->manager->trackLanguage();
422 6
        });
423
    }
424
425
    /**
426
     * Check if the visitor is a robot.
427
     *
428
     * @return bool
429
     */
430 6
    protected function isRobot()
431
    {
432
        /** @var  \Arcanedev\LaravelTracker\Contracts\Detectors\CrawlerDetector  $crawler */
433 6
        $crawler = $this->app[CrawlerDetector::class];
434
435 6
        return $crawler->isRobot();
436
    }
437
438
    /**
439
     * Track the trackable if enabled.
440
     *
441
     * @param  string      $key
442
     * @param  \Closure    $callback
443
     * @param  mixed|null  $default
444
     *
445
     * @return mixed
446
     */
447 10
    private function trackIfEnabled($key, \Closure $callback, $default = null)
448
    {
449 10
        return $this->isEnabled()
450 10
            ? ($this->getConfig("tracking.$key", false) ? $callback() : $default)
451 10
            : $default;
452
    }
453
}
454