Cookies::getToken()   A
last analyzed

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 seregazhuk\PinterestBot\Helpers;
4
5
class Cookies
6
{
7
    /**
8
     * @var array
9
     */
10
    protected $cookies = [];
11
12
    /**
13
     * @param string $name
14
     * @return mixed
15
     */
16
    public function get($name)
17
    {
18
        if (array_key_exists($name, $this->cookies)) {
19
            return $this->cookies[$name]['value'];
20
        }
21
22
        return null;
23
    }
24
25
    /**
26
     * @return string|null
27
     */
28
    public function getToken()
29
    {
30
        return $this->get('csrftoken');
31
    }
32
33
    /**
34
     * @return array
35
     */
36
    public function all()
37
    {
38
        return $this->cookies;
39
    }
40
41
    /**
42
     * @param string $file
43
     */
44
    public function fill($file)
45
    {
46
        $this->cookies = [];
47
48
        foreach (file($file) as $line) {
49
            if ($cookie = $this->parseCookieLine($line)) {
50
                $this->cookies[$cookie['name']] = $cookie;
51
            }
52
        }
53
    }
54
55
    /**
56
     * @param string $line
57
     * @return bool
58
     */
59
    protected function isHttp($line)
60
    {
61
        return substr($line, 0, 10) == '#HttpOnly_';
62
    }
63
64
    /**
65
     * @param string $line
66
     * @return bool
67
     */
68
    protected function isValidLine($line)
69
    {
70
        return strlen($line) > 0 && $line[0] != '#' && substr_count($line, "\t") == 6;
71
    }
72
73
    /**
74
     * @param string $line
75
     * @return array|bool
76
     */
77
    protected function parseCookieLine($line)
78
    {
79
        // detect http only cookies and remove #HttpOnly prefix
80
        $httpOnly = $this->isHttp($line);
81
82
        if ($httpOnly) {
83
            $line = substr($line, 10);
84
        }
85
86
        if (!$this->isValidLine($line)) {
87
            return false;
88
        }
89
90
        $data = $this->getCookieData($line);
91
92
        $data['httponly'] = $httpOnly;
93
94
        return $data;
95
    }
96
97
    /**
98
     * @param string $line
99
     * @return array
100
     */
101
    protected function getCookieData($line)
102
    {
103
        // execGet tokens in an array
104
        $data = explode("\t", $line);
105
        // trim the tokens
106
        $data =  array_map('trim', $data);
107
108
        return [
109
            'domain'     => $data[0],
110
            'flag'       => $data[1],
111
            'path'       => $data[2],
112
            'secure'     => $data[3],
113
            'name'       => urldecode($data[5]),
114
            'value'      => urldecode($data[6]),
115
            'expiration' => date('Y-m-d h:i:s', $data[4]),
116
        ];
117
    }
118
}
119