Completed
Push — master ( 657cce...e75d45 )
by Sebastian
02:38
created

Referer::shouldCapture()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Spatie\Referer;
4
5
use Illuminate\Http\Request;
6
use Spatie\Referer\Helpers\Url;
7
use Illuminate\Contracts\Session\Session;
8
use Spatie\Referer\Exceptions\InvalidConfiguration;
9
10
class Referer
11
{
12
    /** @var string */
13
    protected $key;
14
15
    /** @var \Illuminate\Contracts\Session\Session */
16
    protected $session;
17
18
    public function __construct(string $key, Session $session)
19
    {
20
        if (empty($key)) {
21
            throw InvalidConfiguration::emptyKey();
22
        }
23
24
        $this->key = $key;
25
        $this->session = $session;
26
    }
27
28
    public function get(): string
29
    {
30
        return $this->session->get($this->key, '');
31
    }
32
33
    public function forget()
34
    {
35
        $this->session->forget($this->key);
36
    }
37
38
    public function put(string $referer)
39
    {
40
        return $this->session->put($this->key, $referer);
41
    }
42
43
    public function putFromRequest(Request $request)
44
    {
45
        $referer = $this->determineFromRequest($request);
46
47
        if (! empty($referer)) {
48
            $this->put($referer);
49
        }
50
    }
51
52
    protected function determineFromRequest(Request $request): string
53
    {
54
        if ($this->shouldCapture('utm_source') && $request->has('utm_source')) {
55
            return $request->get('utm_source');
56
        }
57
58
        if (! $this->shouldCapture('referer_header')) {
59
            return '';
60
        }
61
62
        $referer = $request->header('referer', '');
63
64
        if (empty($referer)) {
65
            return '';
66
        }
67
68
        $refererHost = Url::host($referer);
69
70
        if (empty($refererHost)) {
71
            return '';
72
        }
73
74
        if ($refererHost === $request->getHost()) {
75
            return '';
76
        }
77
78
        return $refererHost;
79
    }
80
81
    protected function shouldCapture(string $source): bool
82
    {
83
        return config("referer.sources.{$source}", false);
84
    }
85
}
86