Completed
Push — master ( b5ecd9...b1f901 )
by Philipp
02:41
created

Cookie   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 47
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A save() 0 3 1
A __construct() 0 3 1
A get() 0 18 4
A getCookie() 0 7 2
A has() 0 3 1
1
<?php
2
3
namespace Pmochine\LaravelTongue\Misc;
4
5
use Illuminate\Contracts\Encryption\DecryptException;
6
7
class Cookie
8
{
9
    protected $key;
10
11
    public function __construct(string $cookieKey)
12
    {
13
        $this->key = $cookieKey;
14
    }
15
16
    public function save(string $content): void
17
    {
18
        cookie()->queue(cookie()->forever($this->key, $content));
19
    }
20
21
    public function get(): ?string
22
    {
23
        if (!$this->has()) {
24
            return null;
25
        }
26
27
        try {
28
            //Somehow I got this error: unserialize(): Error at offset 0 of 2 bytes
29
            //I needed to change decrypt(value, unserialize = false);
30
            return app('encrypter')->decrypt($this->getCookie(), false);
31
        } catch (DecryptException $e) {
32
            //Somehow the middleware for decrypting does not kick in here...
33
            //but it even fails if we use php artisan <something> (weird)
34
            //if it happes we can simply give it normally back
35
            return $this->getCookie();
36
        } catch (\Exception $e) {
37
            //So I don't return a cookie in that case
38
            return null;
39
        }
40
    }
41
42
    protected function getCookie(): ?string
43
    {
44
        $result = request()->cookie($this->key);
45
46
        if (is_array($result)) return null;
47
48
        return $result;
49
    }
50
51
    public function has(): bool
52
    {
53
        return request()->hasCookie($this->key);
54
    }
55
}
56