Completed
Push — master ( f328e9...1657f1 )
by ARCANEDEV
13s
created

Tracker::trackMatchedRoute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 9
cp 0.8889
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 2
crap 2.0054
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 198
    public function __construct(Application $app, TrackingManagerContract $manager)
96
    {
97 198
        $this->app     = $app;
98 198
        $this->manager = $manager;
99 198
        $this->enabled = $this->getConfig('enabled', $this->enabled);
100 198
    }
101
102
    /* ------------------------------------------------------------------------------------------------
103
     |  Getters & Setters
104
     | ------------------------------------------------------------------------------------------------
105
     */
106
    /**
107
     * Get the config repository.
108
     *
109
     * @return \Illuminate\Contracts\Config\Repository
110
     */
111 198
    private function config()
112
    {
113 198
        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 198
    private function getConfig($key, $default = null)
125
    {
126 198
        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 6
    private function mergeSessionActivityData(array $data)
183
    {
184 6
        $this->sessionActivityData = array_merge($this->sessionActivityData, $data);
185
186 6
        return $this;
187
    }
188
189
    /* ------------------------------------------------------------------------------------------------
190
     |  Main Functions
191
     | ------------------------------------------------------------------------------------------------
192
     */
193
    /**
194
     * Track the matched route.
195
     *
196
     * @param  \Illuminate\Routing\Route  $route
197
     * @param  \Illuminate\Http\Request   $request
198
     */
199 6
    public function trackMatchedRoute(Route $route, Request $request)
200
    {
201 6
        $tracker = $this->manager->getRouteTracker();
202
203 6
        if ($tracker->isTrackable($route)) {
204 6
            $this->mergeSessionActivityData([
205 6
                'route_path_id' => $tracker->track($route, $request),
206 3
            ]);
207 3
        }
208
        else
209
            $this->disable();
210 6
    }
211
212
    /**
213
     * Start the tracking.
214
     *
215
     * @param  \Illuminate\Http\Request $request
216
     */
217 6
    public function track(Request $request)
218
    {
219 6
        if ($this->isEnabled()) {
220 6
            $this->setRequest($request);
221
222 6
            $this->mergeSessionActivityData([
223 6
                'session_id'  => $this->getSessionId(),
224 6
                'path_id'     => $this->getPathId(),
225 6
                'query_id'    => $this->getQueryId(),
226 6
                'referrer_id' => $this->getRefererId(),
227 3
            ]);
228
229 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...
230 3
        }
231 6
    }
232
233
    /**
234
     * Enable the tracker.
235
     */
236 6
    public function enable()
237
    {
238 6
        if ( ! $this->isEnabled()) $this->enabled = true;
239 6
    }
240
241
    /**
242
     * Disable the tracker.
243
     */
244 6
    public function disable()
245
    {
246 6
        if ($this->isEnabled()) $this->enabled = false;
247 6
    }
248
249
    /* ------------------------------------------------------------------------------------------------
250
     |  Check Functions
251
     | ------------------------------------------------------------------------------------------------
252
     */
253
    /**
254
     * Check if the tracker is enabled.
255
     *
256
     * @return bool
257
     */
258 24
    public function isEnabled()
259
    {
260 24
        return $this->enabled;
261
    }
262
263
    /* ------------------------------------------------------------------------------------------------
264
     |  Other Functions
265
     | ------------------------------------------------------------------------------------------------
266
     */
267
    /**
268
     * Get the stored session id.
269
     *
270
     * @return int
271
     */
272 6
    private function getSessionId()
273
    {
274 6
        $sessionData = $this->manager->checkSessionData($this->sessionData, [
275 6
            'user_id'      => $this->getUserId(),
276 6
            'device_id'    => $this->getDeviceId(),
277 6
            'client_ip'    => $this->request->getClientIp(),
278 6
            'geoip_id'     => $this->getGeoIpId(),
279 6
            'agent_id'     => $this->getAgentId(),
280 6
            'referrer_id'  => $this->getRefererId(),
281 6
            'cookie_id'    => $this->getCookieId(),
282 6
            'language_id'  => $this->getLanguageId(),
283 6
            'is_robot'     => $this->isRobot(),
284 6
            'user_agent'   => $this->getUserAgentParser()->getOriginalUserAgent(),
285 3
        ]);
286
287 6
        $this->mergeSessionData($sessionData);
288
289 6
        return $this->manager->trackSession($this->sessionData);
290
    }
291
292
    /**
293
     * Track the path.
294
     *
295
     * @return int|null
296
     */
297 6
    private function getPathId()
298
    {
299
        return $this->trackIfEnabled('paths', function () {
300 6
            return $this->manager->trackPath(
301 6
                $this->request->path()
302 3
            );
303 6
        });
304
    }
305
306
    /**
307
     * Track the query.
308
     *
309
     * @return int|null
310
     */
311 6
    private function getQueryId()
312
    {
313
        return $this->trackIfEnabled('path-queries', function () {
314 6
            return $this->manager->trackQuery(
315 6
                $this->request->query()
316 3
            );
317 6
        });
318
    }
319
320
    /**
321
     * Get the user id.
322
     *
323
     * @return int|null
324
     */
325 6
    private function getUserId()
326
    {
327
        return $this->trackIfEnabled('users', function () {
328 6
            return $this->manager->trackUser();
329 6
        });
330
    }
331
332
    /**
333
     * Get the tracked device id.
334
     *
335
     * @return int|null
336
     */
337 6
    private function getDeviceId()
338
    {
339
        return $this->trackIfEnabled('devices', function () {
340 6
            return $this->manager->trackDevice();
341 6
        });
342
    }
343
344
    /**
345
     * Get the tracked ip address ip.
346
     *
347
     * @return int|null
348
     */
349 6
    private function getGeoIpId()
350
    {
351
        return $this->trackIfEnabled('geoip', function () {
352 6
            return $this->manager->trackGeoIp(
353 6
                $this->request->getClientIp()
354 3
            );
355 6
        });
356
    }
357
358
    /**
359
     * Get the tracked user agent id.
360
     *
361
     * @return int|null
362
     */
363 6
    private function getAgentId()
364
    {
365
        return $this->trackIfEnabled('user-agents', function () {
366 6
            return $this->manager->trackUserAgent();
367 6
        });
368
    }
369
370
    /**
371
     * Get the tracked referer id.
372
     *
373
     * @return int|null
374
     */
375 6
    private function getRefererId()
376
    {
377
        return $this->trackIfEnabled('referers', function () {
378 6
            return $this->manager->trackReferer(
379 6
                $this->request->headers->get('referer'),
380 6
                $this->request->url()
381 3
            );
382 6
        });
383
    }
384
385
    /**
386
     * Get the tracked cookie id.
387
     *
388
     * @return int|null
389
     */
390 6
    private function getCookieId()
391
    {
392
        return $this->trackIfEnabled('cookies', function () {
393 6
            return $this->manager->trackCookie(
394 6
                $this->request->cookie($this->getConfig('cookie.name'))
395 3
            );
396 6
        });
397
    }
398
399
    /**
400
     * Get the tracked language id.
401
     *
402
     * @return int|null
403
     */
404
    private function getLanguageId()
405
    {
406 6
        return $this->trackIfEnabled('languages', function () {
407 6
            return $this->manager->trackLanguage();
408 6
        });
409
    }
410
411
    /**
412
     * Check if the visitor is a robot.
413
     *
414
     * @return bool
415
     */
416 6
    protected function isRobot()
417
    {
418
        /** @var  \Arcanedev\LaravelTracker\Contracts\Detectors\CrawlerDetector  $crawler */
419 6
        $crawler = $this->app[CrawlerDetector::class];
420
421 6
        return $crawler->isRobot();
422
    }
423
424
    /**
425
     * Track the trackable if enabled.
426
     *
427
     * @param  string      $key
428
     * @param  \Closure    $callback
429
     * @param  mixed|null  $default
430
     *
431
     * @return mixed
432
     */
433 6
    private function trackIfEnabled($key, \Closure $callback, $default = null)
434
    {
435 6
        return $this->getConfig("tracking.$key", false) ? $callback() : $default;
436
    }
437
}
438