Completed
Push — master ( f77348...ad6f80 )
by Sergey
03:41
created

CsrfHelper::getTokenFromFile()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 9.2
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace seregazhuk\PinterestBot\Helpers;
4
5
class CsrfHelper
6
{
7
    const TOKEN_NAME = 'csrftoken';
8
    const DEFAULT_TOKEN = '1234';
9
10
    /**
11
     * Get a CSRF token from the given cookie file
12
     *
13
     * @param string $file
14
     * @return string|null
15
     */
16
    public static function getTokenFromFile($file)
17
    {
18
        if ( ! file_exists($file)) {
19
            return null;
20
        }
21
22
        foreach (file($file) as $line) {
23
24
            if ($token = self::parseLineForToken($line)) {
25
                return $token;
26
            }
27
        }
28
29
        return null;
30
    }
31
32
    /**
33
     * @param string $line
34
     * @return bool
35
     */
36
    protected static function parseLineForToken($line)
37
    {
38
        if (empty(strstr($line, self::TOKEN_NAME))) {
39
            return false;
40
        }
41
42
        preg_match('/'.self::TOKEN_NAME.'\s(\w*)/', $line, $matches);
43
        if ( ! empty($matches)) {
44
            return $matches[1];
45
        }
46
47
        return false;
48
    }
49
50
    /**
51
     * @return string
52
     */
53
    public static function getDefaultCookie()
54
    {
55
        return 'Cookie: csrftoken='.CsrfHelper::DEFAULT_TOKEN.';';
56
    }
57
58
}
59