Completed
Push — master ( f36413...406191 )
by ARCANEDEV
08:57
created

TrackingManager::trackRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
c 0
b 0
f 0
ccs 12
cts 12
cp 1
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
crap 2
1
<?php namespace Arcanedev\LaravelTracker;
2
3
use Arcanedev\LaravelTracker\Contracts\TrackingManager as TrackingManagerContract;
4
use Illuminate\Contracts\Foundation\Application;
5
use Illuminate\Http\Request;
6
use Illuminate\Routing\Route;
7
8
/**
9
 * Class     TrackingManager
10
 *
11
 * @package  Arcanedev\LaravelTracker
12
 * @author   ARCANEDEV <[email protected]>
13
 */
14
class TrackingManager implements TrackingManagerContract
15
{
16
    /* ------------------------------------------------------------------------------------------------
17
     |  Properties
18
     | ------------------------------------------------------------------------------------------------
19
     */
20
    /**
21
     * The application instance.
22
     *
23
     * @var  \Illuminate\Contracts\Foundation\Application
24
     */
25
    private $app;
26
27
    /**
28
     * The request instance.
29
     *
30
     * @var \Illuminate\Http\Request
31
     */
32
    private $request;
33
34
    /**
35
     * Tracking enabled status.
36
     *
37
     * @var  bool
38
     */
39
    protected $enabled = false;
40
41
    /**
42
     * The current session data.
43
     *
44
     * @var array
45
     */
46
    protected $sessionData = [
47
        'user_id'     => null,
48
        'device_id'   => null,
49
        'agent_id'    => null,
50
        'geoip_id'    => null,
51
        'referrer_id' => null,
52
        'cookie_id'   => null,
53
        'language_id' => null,
54
        'client_ip'   => '',
55
        'is_robot'    => false,
56
        'user_agent'  => '',
57
    ];
58
59
    /**
60
     * The current session activity data.
61
     *
62
     * @var array
63
     */
64
    protected $sessionActivityData = [
65
        'session_id'    => null,
66
        'path_id'       => null,
67
        'query_id'      => null,
68
        'referrer_id'   => null,
69
        'route_path_id' => null,
70
        'error_id'      => null,
71
        'method'        => '',
72
        'is_ajax'       => false,
73
        'is_secure'     => false,
74
        'is_json'       => false,
75
        'wants_json'    => false,
76
    ];
77
78
    /* ------------------------------------------------------------------------------------------------
79
     |  Constructor
80
     | ------------------------------------------------------------------------------------------------
81
     */
82
    /**
83
     * TrackingManager constructor.
84
     *
85
     * @param \Illuminate\Contracts\Foundation\Application $app
86
     */
87 222
    public function __construct(Application $app)
88
    {
89 222
        $this->app     = $app;
90 222
        $this->enabled = $this->getConfig('enabled', $this->enabled);
91 222
    }
92
93
    /* ------------------------------------------------------------------------------------------------
94
     |  Getters & Setters
95
     | ------------------------------------------------------------------------------------------------
96
     */
97
    /**
98
     * Get the config repository.
99
     *
100
     * @return \Illuminate\Contracts\Config\Repository
101
     */
102 222
    private function config()
103
    {
104 222
        return $this->app['config'];
105
    }
106
107
    /**
108
     * Get the tracker config.
109
     *
110
     * @param  string      $key
111
     * @param  mixed|null  $default
112
     *
113
     * @return mixed
114
     */
115 222
    private function getConfig($key, $default = null)
116
    {
117 222
        return $this->config()->get("laravel-tracker.$key", $default);
118
    }
119
120
    /**
121
     * Set the request.
122
     *
123
     * @param  \Illuminate\Http\Request  $request
124
     *
125
     * @return self
126
     */
127 12
    private function setRequest(Request $request)
128
    {
129 12
        $this->mergeSessionActivityData([
130 12
            'method'      => $request->method(),
131 12
            'is_ajax'     => $request->ajax(),
132 12
            'is_secure'   => $request->isSecure(),
133 12
            'is_json'     => $request->isJson(),
134 12
            'wants_json'  => $request->wantsJson(),
135 6
        ]);
136
137 12
        $this->request = $request;
138
139 12
        return $this;
140
    }
141
142
    /**
143
     * Merge session data.
144
     *
145
     * @param  array  $data
146
     *
147
     * @return self
148
     */
149 12
    private function mergeSessionData(array $data)
150
    {
151 12
        $this->sessionData = array_merge($this->sessionData, $data);
152
153 12
        return $this;
154
    }
155
156
    /**
157
     * Merge session activity data.
158
     *
159
     * @param  array  $data
160
     *
161
     * @return self
162
     */
163 16
    private function mergeSessionActivityData(array $data)
164
    {
165 16
        $this->sessionActivityData = array_merge($this->sessionActivityData, $data);
166
167 16
        return $this;
168
    }
169
170
    /**
171
     * Get the cookie tracker.
172
     *
173
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\CookieTracker
174
     */
175
    private function getCookieTracker()
176
    {
177
        return $this->make(Contracts\Trackers\CookieTracker::class);
178
    }
179
180
    /**
181
     * Get the device tracker.
182
     *
183
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\DeviceTracker
184
     */
185 12
    private function getDeviceTracker()
186
    {
187 12
        return $this->make(Contracts\Trackers\DeviceTracker::class);
188
    }
189
190
    /**
191
     * Get the error tracker.
192
     *
193
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\ErrorTracker
194
     */
195 4
    private function getErrorTracker()
196
    {
197 4
        return $this->make(Contracts\Trackers\ErrorTracker::class);
198
    }
199
200
    /**
201
     * Get the geoip tracker.
202
     *
203
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\GeoIpTracker
204
     */
205 12
    private function getGeoIpTracker()
206
    {
207 12
        return $this->make(Contracts\Trackers\GeoIpTracker::class);
208
    }
209
210
    /**
211
     * Get the language tracker.
212
     *
213
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\LanguageTracker
214
     */
215 12
    private function getLanguageTracker()
216
    {
217 12
        return $this->make(Contracts\Trackers\LanguageTracker::class);
218
    }
219
220
    /**
221
     * Get the path tracker.
222
     *
223
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\PathTracker
224
     */
225 12
    private function getPathTracker()
226
    {
227 12
        return $this->make(Contracts\Trackers\PathTracker::class);
228
    }
229
230
    /**
231
     * Get the query tracker.
232
     *
233
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\QueryTracker
234
     */
235 12
    private function getQueryTracker()
236
    {
237 12
        return $this->make(Contracts\Trackers\QueryTracker::class);
238
    }
239
240
    /**
241
     * Get the referer tracker.
242
     *
243
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\RefererTracker
244
     */
245 12
    private function getRefererTracker()
246
    {
247 12
        return $this->make(Contracts\Trackers\RefererTracker::class);
248
    }
249
250
    /**
251
     * Get the session tracker.
252
     *
253
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\SessionTracker
254
     */
255 12
    private function getSessionTracker()
256
    {
257 12
        return $this->make(Contracts\Trackers\SessionTracker::class);
258
    }
259
260
    /**
261
     * Get the session activity tracker.
262
     *
263
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\SessionActivityTracker
264
     */
265 12
    private function getSessionActivityTracker()
266
    {
267 12
        return $this->make(Contracts\Trackers\SessionActivityTracker::class);
268
    }
269
270
    /**
271
     * Get the route tracker.
272
     *
273
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\RouteTracker
274
     */
275 12
    private function getRouteTracker()
276
    {
277 12
        return $this->make(Contracts\Trackers\RouteTracker::class);
278
    }
279
280
    /**
281
     * Get the user agent tracker.
282
     *
283
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\UserAgentTracker
284
     */
285 12
    private function getUserAgentTracker()
286
    {
287 12
        return $this->make(Contracts\Trackers\UserAgentTracker::class);
288
    }
289
290
    /**
291
     * Get the user tracker.
292
     *
293
     * @return \Arcanedev\LaravelTracker\Contracts\Trackers\UserTracker
294
     */
295 12
    private function getUserTracker()
296
    {
297 12
        return $this->make(Contracts\Trackers\UserTracker::class);
298
    }
299
300
    /* ------------------------------------------------------------------------------------------------
301
     |  Main Functions
302
     | ------------------------------------------------------------------------------------------------
303
     */
304
    /**
305
     * Start the tracking.
306
     *
307
     * @param  \Illuminate\Http\Request $request
308
     */
309 12
    public function trackRequest(Request $request)
310
    {
311 12
        if ($this->isEnabled()) {
312 12
            $this->setRequest($request);
313
314 12
            $this->mergeSessionActivityData([
315 12
                'session_id'  => $this->getSessionId(),
316 12
                'path_id'     => $this->getPathId(),
317 12
                'query_id'    => $this->getQueryId(),
318 12
                'referrer_id' => $this->getRefererId(),
319 6
            ]);
320
321 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...
322 6
        }
323 12
    }
324
325
    /**
326
     * Track the matched route.
327
     *
328
     * @param  \Illuminate\Routing\Route  $route
329
     * @param  \Illuminate\Http\Request   $request
330
     */
331 12
    public function trackMatchedRoute(Route $route, Request $request)
332
    {
333 12
        if ( ! $this->isEnabled()) return;
334
335 12
        $tracker = $this->getRouteTracker();
336
337 12
        if ($tracker->isTrackable($route)) {
338 12
            $this->mergeSessionActivityData([
339 12
                'route_path_id' => $tracker->track($route, $request),
340 6
            ]);
341 6
        }
342
        else
343
            $this->disable();
344 12
    }
345
346
    /**
347
     * Track the exception.
348
     *
349
     * @param  \Exception  $exception
350
     */
351 4
    public function trackException(\Exception $exception)
352
    {
353
        $id = $this->trackIfEnabled('errors', function () use ($exception) {
354 4
            $this->getErrorTracker()->track($exception);
355 4
        });
356
357 4
        $this->mergeSessionActivityData(['error_id' => $id]);
358 4
    }
359
360
    /**
361
     * Enable the tracking.
362
     */
363 6
    public function enable()
364
    {
365 6
        if ( ! $this->isEnabled()) $this->enabled = true;
366 6
    }
367
368
    /**
369
     * Disable the tracking.
370
     */
371 6
    public function disable()
372
    {
373 6
        if ($this->isEnabled()) $this->enabled = false;
374 6
    }
375
376
    /* ------------------------------------------------------------------------------------------------
377
     |  Check Functions
378
     | ------------------------------------------------------------------------------------------------
379
     */
380
    /**
381
     * Check if the tracker is enabled.
382
     *
383
     * @return bool
384
     */
385 34
    public function isEnabled()
386
    {
387 34
        return $this->enabled;
388
    }
389
390
    /**
391
     * Track the trackable if enabled.
392
     *
393
     * @param  string      $key
394
     * @param  \Closure    $callback
395
     * @param  mixed|null  $default
396
     *
397
     * @return mixed
398
     */
399 16
    private function trackIfEnabled($key, \Closure $callback, $default = null)
400
    {
401 16
        return $this->isEnabled()
402 16
            ? ($this->getConfig("tracking.$key", false) ? $callback() : $default)
403 16
            : $default;
404
    }
405
406
    /* ------------------------------------------------------------------------------------------------
407
     |  Other Functions
408
     | ------------------------------------------------------------------------------------------------
409
     */
410
    /**
411
     * Get the stored session id.
412
     *
413
     * @return int
414
     */
415 12
    private function getSessionId()
416
    {
417 12
        $tracker     = $this->getSessionTracker();
418 12
        $sessionData = $tracker->checkData($this->sessionData, [
419 12
            'user_id'     => $this->getUserId(),
420 12
            'device_id'   => $this->getDeviceId(),
421 12
            'client_ip'   => $this->request->getClientIp(),
422 12
            'geoip_id'    => $this->getGeoIpId(),
423 12
            'agent_id'    => $this->getAgentId(),
424 12
            'referrer_id' => $this->getRefererId(),
425 12
            'cookie_id'   => $this->getCookieId(),
426 12
            'language_id' => $this->getLanguageId(),
427 12
            'is_robot'    => $this->isRobot(),
428 12
            'user_agent'  => $this->getUserAgentTracker()->getUserAgentParser()->getOriginalUserAgent(),
429 6
        ]);
430
431 12
        $this->mergeSessionData($sessionData);
432
433 12
        return $tracker->track($this->sessionData);
434
    }
435
436
    /**
437
     * Track the path.
438
     *
439
     * @return int|null
440
     */
441 12
    private function getPathId()
442
    {
443
        return $this->trackIfEnabled('paths', function () {
444 12
            return $this->getPathTracker()->track(
445 12
                $this->request->path()
446 6
            );
447 12
        });
448
    }
449
450
    /**
451
     * Track the query.
452
     *
453
     * @return int|null
454
     */
455 12
    private function getQueryId()
456
    {
457
        return $this->trackIfEnabled('path-queries', function () {
458 12
            return $this->getQueryTracker()->track(
459 12
                $this->request->query()
460 6
            );
461 12
        });
462
    }
463
464
    /**
465
     * Get the user id.
466
     *
467
     * @return int|null
468
     */
469 12
    private function getUserId()
470
    {
471
        return $this->trackIfEnabled('users', function () {
472 12
            return $this->getUserTracker()->track();
473 12
        });
474
    }
475
476
    /**
477
     * Get the tracked device id.
478
     *
479
     * @return int|null
480
     */
481 12
    private function getDeviceId()
482
    {
483
        return $this->trackIfEnabled('devices', function () {
484 12
            return $this->getDeviceTracker()->track();
485 12
        });
486
    }
487
488
    /**
489
     * Get the tracked ip address ip.
490
     *
491
     * @return int|null
492
     */
493 12
    private function getGeoIpId()
494
    {
495
        return $this->trackIfEnabled('geoip', function () {
496 12
            return $this->getGeoIpTracker()->track(
497 12
                $this->request->getClientIp()
498 6
            );
499 12
        });
500
    }
501
502
    /**
503
     * Get the tracked user agent id.
504
     *
505
     * @return int|null
506
     */
507 12
    private function getAgentId()
508
    {
509
        return $this->trackIfEnabled('user-agents', function () {
510 12
            return $this->getUserAgentTracker()->track();
511 12
        });
512
    }
513
514
    /**
515
     * Get the tracked referer id.
516
     *
517
     * @return int|null
518
     */
519 12
    private function getRefererId()
520
    {
521
        return $this->trackIfEnabled('referers', function () {
522 12
            return $this->getRefererTracker()->track(
523 12
                $this->request->headers->get('referer'),
524 12
                $this->request->url()
525 6
            );
526 12
        });
527
    }
528
529
    /**
530
     * Get the tracked cookie id.
531
     *
532
     * @return int|null
533
     */
534 12
    private function getCookieId()
535
    {
536
        return $this->trackIfEnabled('cookies', function () {
537 12
            return ! is_null($name = $this->getConfig('cookie.name'))
538 6
                ? $this->getCookieTracker()->track($this->request->cookie($name))
539 12
                : null;
540 12
        });
541
    }
542
543
    /**
544
     * Get the tracked language id.
545
     *
546
     * @return int|null
547
     */
548
    private function getLanguageId()
549
    {
550 12
        return $this->trackIfEnabled('languages', function () {
551 12
            return $this->getLanguageTracker()->track();
552 12
        });
553
    }
554
555
    /**
556
     * Check if the visitor is a robot.
557
     *
558
     * @return bool
559
     */
560 12
    protected function isRobot()
561
    {
562
        /** @var  \Arcanedev\LaravelTracker\Contracts\Detectors\CrawlerDetector  $crawler */
563 12
        $crawler = $this->make(\Arcanedev\LaravelTracker\Contracts\Detectors\CrawlerDetector::class);
564
565 12
        return $crawler->isRobot();
566
    }
567
568
    /**
569
     * Get the tracker instance.
570
     *
571
     * @param  string  $abstract
572
     *
573
     * @return mixed
574
     */
575 16
    private function make($abstract)
576
    {
577 16
        return $this->app->make($abstract);
578
    }
579
}
580