Passed
Push — 2.2 ( b1819d...0900d1 )
by Myles
01:57
created

ScwCookie::setCookie()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 19
nc 5
nop 6
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace ScwCookie;
4
5
class ScwCookie
6
{
7
    public $config        = [];
8
    private $decisionMade = false;
9
    private $choices      = [];
10
    
11
    public function __construct()
12
    {
13
        $this->config = parse_ini_file("config.ini", true);
14
15
        $this->decisionMade = self::getCookie('scwCookieHidden') == 'true';
16
        $this->choices      = $this->getChoices();
17
    }
18
19
    public function getChoices()
20
    {
21
        if (self::getCookie('scwCookie') !== false) {
22
            $cookie = self::getCookie('scwCookie');
23
            $cookie = self::decrypt($cookie);
24
            return $cookie;
25
        }
26
27
        $return = [];
28
        foreach ($this->enabledCookies() as $name => $label) {
29
            $return[$name] = $this->config['unsetDefault'];
30
        }
31
        return $return;
32
    }
33
34
    public static function encrypt($value)
35
    {
36
        $return = json_encode($value);
37
        return $return;
38
    }
39
40
    public static function decrypt($value)
41
    {
42
        $value = str_replace('\"', '"', $value);
43
        $return = json_decode($value, true);
44
        return $return;
45
    }
46
47
    public function isAllowed($name)
48
    {
49
        $choices = $this->getChoices();
50
        return isset($choices[$name]) && $choices[$name] == 'allowed';
51
    }
52
53
    public function getCode($name)
54
    {
55
        return isset($this->config[$name]) && isset($this->config[$name]['code'])
56
            ? $this->config[$name]['code']
57
            : false;
58
    }
59
60
    public function output()
61
    {
62
        echo $this->getOutput();
63
    }
64
65
    public function getOutput()
66
    {
67
        $return = [];
68
69
        // Get decision window output
70
        $return[] = $this->getOutputHTML('decision');
71
72
        // Get Google Analytics embed code
73
        if ($this->config['Google_Analytics']['enabled'] && $this->isAllowed('Google_Analytics')) {
74
            $return[] = $this->getOutputHTML('googleAnalytics');
75
        }
76
        
77
        // Get Smartsupp embed code
78
        if ($this->config['Smartsupp']['enabled'] && $this->isAllowed('Smartsupp')) {
79
            $return[] = $this->getOutputHTML('smartsupp');
80
        }
81
        
82
        // Get Hotjar embed code
83
        if ($this->config['Hotjar']['enabled'] && $this->isAllowed('Hotjar')) {
84
            $return[] = $this->getOutputHTML('hotjar');
85
        }
86
        
87
        // Get Tawk.to embed code
88
        if ($this->config['Tawk.to']['enabled'] && $this->isAllowed('Tawk.to')) {
89
            $return[] = $this->getOutputHTML('tawkto');
90
        }
91
92
        return implode("\n", $return);
93
    }
94
95
    public function getOutputHTML($filename)
96
    {
97
        if (!file_exists(__DIR__.'/output/cookies/'.$filename.'.php')) {
98
            return false;
99
        }
100
        
101
        ob_start();
102
        include __DIR__.'/output/cookies/'.$filename.'.php';
103
        return trim(ob_get_clean());
104
    }
105
106
    public function enabledCookies()
107
    {
108
        $return = [];
109
        foreach ($this->config as $name => $value) {
110
            if (!is_array($value) || !isset($value['enabled']) || !$value['enabled']) {
111
                continue;
112
            }
113
            $return[$name] = $value['label'];
114
        }
115
        return $return;
116
    }
117
118
    public static function setCookie($name, $value, $lifetime = 30, $lifetimePeriod = 'days', $domain = '/', $secure = false)
119
    {
120
        // Validate parameters
121
        self::validateSetCookieParams($name, $value, $lifetime, $lifetimePeriod, $domain, $secure);
0 ignored issues
show
Bug Best Practice introduced by
The method ScwCookie\ScwCookie::validateSetCookieParams() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

121
        self::/** @scrutinizer ignore-call */ 
122
              validateSetCookieParams($name, $value, $lifetime, $lifetimePeriod, $domain, $secure);
Loading history...
122
123
        // Calculate expiry time
124
        switch ($lifetimePeriod) {
125
            case 'minutes':
126
                $expiry = time() + (60 * $lifetime);     // 60 = 1 minute
127
                break;
128
129
            case 'hours':
130
                $expiry = time() + (3600 * $lifetime);   // 3600 = 1 hour
131
                break;
132
133
            case 'days':
134
                $expiry = time() + (86400 * $lifetime);  // 86400 = 1 day
135
                break;
136
137
            case 'weeks':
138
                $expiry = time() + (604800 * $lifetime); // 604800 = 1 week
139
                break;
140
            
141
            default:
142
                header('HTTP/1.0 403 Forbidden');
143
                throw new \Exception("Lifetime not recognised");
144
                break;
145
        }
146
147
        // Set cookie
148
        return setcookie($name, $value, $expiry, $domain, $secure);
149
    }
150
151
    public function validateSetCookieParams($name, $value, $lifetime, $lifetimePeriod, $domain, $secure)
152
    {
153
        // Set allowed time periods
154
        $lifetimePeriods = array('minutes', 'hours', 'days', 'weeks');
155
156
        // Check values passed
157
        $validParams = is_string($name);
158
        $validParams = is_string($value) ? $validParams : false;
159
        $validParams = is_int($lifetime) ? $validParams : false;
160
        $validParams = in_array($lifetimePeriod, $lifetimePeriods) ? $validParams : false;
161
        $validParams = is_string($domain) ? $validParams : false;
162
        $validParams = is_bool($secure) ? $validParams : false;
163
164
        if (!$validParams) {
165
            // Failed parameter check
166
            header('HTTP/1.0 403 Forbidden');
167
            throw new \Exception("Incorrect parameter passed to Cookie::set");
168
        }
169
170
        return true;
171
    }
172
173
    public static function getCookie($name)
174
    {
175
        // If cookie exists - return it, otherwise return false
176
        return isset($_COOKIE[$name]) ? $_COOKIE[$name] : false;
177
    }
178
179
    public static function destroyCookie($name)
180
    {
181
        // Set cookie expiration to 1 hour ago
182
        return setcookie($name, '', time() - 3600);
183
    }
184
}
185