Passed
Push — 2.2 ( 0c4a89...fca7ff )
by Myles
01:41
created

ScwCookie::output()   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 0
dl 0
loc 3
rs 10
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 isEnabled($name)
54
    {
55
        $check = $this->config[$name];
56
        return is_array($check) && isset($check['enabled']) && $check['enabled'];
57
    }
58
59
    public function getCode($name)
60
    {
61
        return isset($this->config[$name]) && isset($this->config[$name]['code'])
62
            ? $this->config[$name]['code']
63
            : false;
64
    }
65
66
    public function output()
67
    {
68
        echo $this->getOutput();
69
    }
70
71
    public function getOutput()
72
    {
73
        $return = [];
74
75
        // Get decision window output
76
        $return[] = $this->getOutputHTML('decision');
77
78
        // Get embed codes
79
        $embedCodes = [
80
            'Google_Analytics' => 'googleAnalytics',
81
            'Smartsupp'        => 'smartsupp',
82
            'Hotjar'           => 'hotjar',
83
            'Tawk.to'          => 'tawkto',
84
        ];
85
        foreach ($embedCodes as $configKey => $embedFile) {
86
            if ($this->config[$configKey]['enabled'] && $this->isAllowed($configKey)) {
87
                $return[] = $this->getOutputHTML($embedFile);
88
            }
89
        }
90
91
        return implode("\n", $return);
92
    }
93
94
    public function getOutputHTML($filename)
95
    {
96
        if (!file_exists(__DIR__.'/output/cookies/'.$filename.'.php')) {
97
            return false;
98
        }
99
        
100
        ob_start();
101
        include __DIR__.'/output/cookies/'.$filename.'.php';
102
        return trim(ob_get_clean());
103
    }
104
105
    public function enabledCookies()
106
    {
107
        $return = [];
108
        foreach ($this->config as $name => $value) {
109
            if (!$this->isEnabled($name)) {
110
                continue;
111
            }
112
            $return[$name] = $value['label'];
113
        }
114
        return $return;
115
    }
116
117
    public static function setCookie(
118
        $name,
119
        $value,
120
        $lifetime = 30,
121
        $lifetimePeriod = 'days',
122
        $domain = '/',
123
        $secure = false
124
    ) {
125
        // Validate parameters
126
        self::validateSetCookieParams($name, $value, $lifetime, $lifetimePeriod, $domain, $secure);
127
128
        // Calculate expiry
129
        $expiry = strtotime('+'.$lifetime.' '.$lifetimePeriod);
130
131
        // Set cookie
132
        return setcookie($name, $value, $expiry, $domain, $secure);
133
    }
134
135
    public static function validateSetCookieParams($name, $value, $lifetime, $lifetimePeriod, $domain, $secure)
136
    {
137
        // Set allowed time periods
138
        $lifetimePeriods = array('minutes', 'hours', 'days', 'weeks');
139
        
140
        // Types of parameters to check
141
        $paramTypes = [
142
            // Type => Array of variables
143
            'string' => [$name, $value, $domain],
144
            'int'    => [$lifetime],
145
            'bool'   => [$secure],
146
        ];
147
148
        // Validate basic parameters
149
        $validParams = self::basicValidationChecks($paramTypes);
150
151
        // More complex validations
152
        $validParams = in_array($lifetimePeriod, $lifetimePeriods) ? $validParams : false;
153
154
        // Ensure parameters are still valid
155
        if (!$validParams) {
156
            // Failed parameter check
157
            header('HTTP/1.0 403 Forbidden');
158
            throw new \Exception("Incorrect parameter passed to Cookie::set");
159
        }
160
161
        return true;
162
    }
163
164
    public static function basicValidationChecks($parameters)
0 ignored issues
show
Unused Code introduced by
The parameter $parameters is not used and could be removed. ( Ignorable by Annotation )

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

164
    public static function basicValidationChecks(/** @scrutinizer ignore-unused */ $parameters)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
165
    {
166
        foreach ($paramTypes as $type => $variables) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $paramTypes seems to be never defined.
Loading history...
167
            $functionName = 'is_'.$type;
168
            foreach ($variables as $variable) {
169
                if (!$functionName($variable)) {
170
                    return false;
171
                }
172
            }
173
        }
174
        return true;
175
    }
176
177
    public static function getCookie($name)
178
    {
179
        // If cookie exists - return it, otherwise return false
180
        return isset($_COOKIE[$name]) ? $_COOKIE[$name] : false;
181
    }
182
183
    public static function destroyCookie($name)
184
    {
185
        // Set cookie expiration to 1 hour ago
186
        return setcookie($name, '', time() - 3600);
187
    }
188
}
189