AntiCsrf::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
crap 2
1
<?php
2
/**
3
 * This file is part of the Ray.WebFormModule package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace Ray\WebFormModule;
8
9
use Aura\Input\AntiCsrfInterface;
10
use Aura\Input\Fieldset;
11
use Aura\Session\Session;
12
13
final class AntiCsrf implements AntiCsrfInterface
14
{
15
    const TEST_TOKEN = '1234';
16
17
    const TOKEN_KEY = '__csrf_token';
18
19
    /**
20
     * @var bool
21
     */
22
    private $isCli;
23
24
    /**
25
     * @var Session
26
     */
27
    private $session;
28
29
    /**
30
     * @param Session   $session
31
     * @param bool|null $isCli
32
     s     */
33 16
    public function __construct(Session $session, $isCli = null)
34
    {
35 16
        $this->session = $session;
36 16
        $this->isCli = is_bool($isCli) ? $isCli : PHP_SAPI === 'cli';
37 16
    }
38
39 13
    public function setField(Fieldset $fieldset)
40
    {
41 13
        $fieldset->setField(self::TOKEN_KEY, 'hidden')
42 13
                 ->setAttribs(['value' => $this->getToken()]);
43 13
    }
44
45
    /**
46
     * @param array $data
47
     *
48
     * @return bool
49
     */
50 9
    public function isValid(array $data)
51
    {
52 9
        if ($this->isCli) {
53 7
            return true;
54
        }
55
56 2
        return isset($data[self::TOKEN_KEY]) && $data[self::TOKEN_KEY] == $this->getToken();
57
    }
58
59
    /**
60
     * @return string
61
     */
62 14
    private function getToken()
63
    {
64 14
        $value = $this->isCli ? self::TEST_TOKEN : $this->session->getCsrfToken()->getValue();
65
66 14
        return $value;
67
    }
68
}
69