Completed
Push — master ( 4e8d1d...8d6f18 )
by Philipp
03:00
created

Cookie::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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()) return null;
24
25
        try {
26
            //Somehow I got this error: unserialize(): Error at offset 0 of 2 bytes
27
            //I needed to change decrypt(value, unserialize = false);
28
            return app('encrypter')->decrypt(request()->cookie($this->key), false);
29
        } catch (DecryptException $e) {
30
            //Somehow the middleware for decrypting does not kick in here...
31
            //but it even fails if we use php artisan <something> (weird)
32
            //if it happes we can simply give it normally back
33
            return request()->cookie($this->key);
0 ignored issues
show
Bug Best Practice introduced by
The expression return request()->cookie($this->key) could return the type array which is incompatible with the type-hinted return null|string. Consider adding an additional type-check to rule them out.
Loading history...
34
        } catch (\Exception $e) {
35
            //So I don't return a cookie in that case
36
            return null;
37
        }
38
    }
39
40
    public function has(): bool
41
    {
42
        return request()->hasCookie($this->key);
43
    }
44
}
45