Completed
Push — 4.x ( f42e95 )
by Akihito
14s queued 11s
created

CsrfToken   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 94.44%

Importance

Changes 8
Bugs 0 Features 2
Metric Value
wmc 6
c 8
b 0
f 2
lcom 1
cbo 2
dl 0
loc 82
ccs 17
cts 18
cp 0.9444
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A isValid() 0 8 2
A getValue() 0 4 1
A regenerateValue() 0 5 1
1
<?php
2
/**
3
 *
4
 * This file is part of Aura for PHP.
5
 *
6
 * @license http://opensource.org/licenses/bsd-license.php BSD
7
 *
8
 */
9
namespace Aura\Session;
10
11
/**
12
 *
13
 * Cross-site request forgery token tools.
14
 *
15
 * @package Aura.Session
16
 *
17
 */
18
class CsrfToken
19
{
20
    /**
21
     *
22
     * A cryptographically-secure random value generator.
23
     *
24
     * @var RandvalInterface
25
     *
26
     */
27
    protected $randval;
28
29
    /**
30
     *
31
     * Session segment for values in this class.
32
     *
33
     * @var Segment
34
     *
35
     */
36
    protected $segment;
37
38
    /**
39
     *
40
     * Constructor.
41
     *
42
     * @param Segment $segment A segment for values in this class.
43
     *
44
     * @param RandvalInterface $randval A cryptographically-secure random
45
     * value generator.
46
     *
47
     */
48 5
    public function __construct(Segment $segment, RandvalInterface $randval)
49
    {
50 5
        $this->segment = $segment;
51 5
        $this->randval = $randval;
52 5
        if (! $this->segment->get('value')) {
53 5
            $this->regenerateValue();
54 5
        }
55 5
    }
56
57
    /**
58
     *
59
     * Checks whether an incoming CSRF token value is valid.
60
     *
61
     * @param string $value The incoming token value.
62
     *
63
     * @return bool True if valid, false if not.
64
     *
65
     */
66 1
    public function isValid($value)
67
    {
68 1
        if (function_exists('hash_equals')) {
69
            return hash_equals($value, $this->getValue());
70
        }
71
72 1
        return $value === $this->getValue();
73 1
    }
74
75
    /**
76
     *
77
     * Gets the value of the outgoing CSRF token.
78
     *
79
     * @return string
80
     *
81
     */
82 3
    public function getValue()
83
    {
84 3
        return $this->segment->get('value');
85
    }
86
87
    /**
88
     *
89
     * Regenerates the value of the outgoing CSRF token.
90
     *
91
     * @return null
92
     *
93
     */
94 5
    public function regenerateValue()
95
    {
96 5
        $hash = hash('sha512', $this->randval->generate());
97 5
        $this->segment->set('value', $hash);
98 5
    }
99
}
100