Completed
Pull Request — master (#152)
by Sergey
02:51
created

CsrfParser::parseLineForToken()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
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 13
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
3
namespace seregazhuk\PinterestBot\Helpers;
4
5
class CsrfParser
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
     *
15
     * @return string|null
16
     */
17
    public static function getTokenFromFile($file)
18
    {
19
        if (!file_exists($file)) {
20
            return null;
21
        }
22
23
        foreach (file($file) as $line) {
24
            if ($token = self::parseLineForToken($line)) {
25
                return $token;
26
            }
27
        }
28
29
        return null;
30
    }
31
32
    /**
33
     * @param string $line
34
     *
35
     * @return false|string
36
     */
37
    protected static function parseLineForToken($line)
38
    {
39
        if (empty(strstr($line, self::TOKEN_NAME))) {
40
            return false;
41
        }
42
43
        preg_match('/' . self::TOKEN_NAME . '\s(\w*)/', $line, $matches);
44
        if (!empty($matches)) {
45
            return $matches[1];
46
        }
47
48
        return false;
49
    }
50
}
51