Passed
Push — master ( 6151ba...17a32e )
by Chauncey
52s queued 10s
created

AuthTokenCookieTrait   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 0
dl 0
loc 79
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A sendCookie() 0 15 3
A deleteCookie() 0 14 2
A getTokenDataFromCookie() 0 24 5
isEnabled() 0 1 ?
metadata() 0 1 ?
1
<?php
2
3
namespace Charcoal\User;
4
5
/**
6
 *
7
 */
8
trait AuthTokenCookieTrait
9
{
10
    /**
11
     * @return boolean
12
     */
13
    public function sendCookie()
14
    {
15
        if (!$this->isEnabled()) {
16
            return false;
17
        }
18
19
        $metadata = $this->metadata();
20
21
        $name   = $metadata['tokenName'];
22
        $value  = $this['ident'].';'.$this['token'];
23
        $expiry = isset($this['expiry']) ? $this['expiry']->getTimestamp() : null;
24
        $secure = $metadata['httpsOnly'];
25
26
        return setcookie($name, $value, $expiry, '', '', $secure);
27
    }
28
29
    /**
30
     * @return boolean
31
     */
32
    public function deleteCookie()
33
    {
34
        if (!$this->isEnabled()) {
35
            return false;
36
        }
37
38
        $metadata = $this->metadata();
39
40
        $name   = $metadata['tokenName'];
41
        $expiry = (time() - 1000);
42
        $secure = $metadata['httpsOnly'];
43
44
        return setcookie($name, '', $expiry, '', '', $secure);
45
    }
46
47
    /**
48
     * @return array|null `[ 'ident' => '', 'token' => '' ]
49
     */
50
    public function getTokenDataFromCookie()
51
    {
52
        if (!$this->isEnabled()) {
53
            return null;
54
        }
55
56
        $metadata = $this->metadata();
57
58
        $name = $metadata['tokenName'];
59
        if (!isset($_COOKIE[$name])) {
60
            return null;
61
        }
62
63
        $cookie = $_COOKIE[$name];
64
        $data   = array_pad(explode(';', $cookie), 2, null);
65
        if (!isset($data[0]) || !isset($data[1])) {
66
            return null;
67
        }
68
69
        return [
70
            'ident' => $data[0],
71
            'token' => $data[1],
72
        ];
73
    }
74
75
    /**
76
     * Determine if authentication by token is supported.
77
     *
78
     * @return boolean
79
     */
80
    abstract public function isEnabled();
81
82
    /**
83
     * @return \Charcoal\Model\MetadataInterface
84
     */
85
    abstract public function metadata();
86
}
87