Completed
Push — master ( 6157a8...e866d1 )
by Michael
07:36
created

TokenService::generate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace Schnittstabil\Csrf\TokenService;
4
5
/**
6
 * A TokenService.
7
 */
8
class TokenService implements TokenServiceInterface
9
{
10
    protected $generator;
11
    protected $validator;
12
13
    /**
14
     * Create a new TokenService.
15
     *
16
     * `$ttl` is used for calculating the expiration time of the tokens, its default value (1440sec === 24min)
17
     * correspond to the default `session.gc_maxlifetime`.
18
     *
19
     * @see http://php.net/manual/en/session.configuration.php Documentation of `session.gc-maxlifetime`.
20
     *
21
     * @param string $key  Shared secret key used for generating token signatures.
22
     * @param int    $ttl  Default Time to Live in seconds.
23
     * @param string $algo Name of hashing algorithm. See hash_algos() for a list of supported algorithms.
24
     */
25
    public function __construct($key, $ttl = 1440, $algo = 'SHA512')
26
    {
27
        $signatory = new TokenSignatory($key, $algo);
28
        $this->generator = new TokenGenerator($signatory, $ttl);
29
        $this->validator = new TokenValidator($signatory);
30
    }
31
32
    /**
33
     * Generate a CSRF token.
34
     *
35
     * @param int $iat The time that the token was issued, defaults to `time()`
36
     * @param int $exp The expiration time, defaults to `$iat + $this->ttl`
37
     *
38
     * @return string
39
     *
40
     * @throws \InvalidArgumentException For invalid $iat and $exp arguments.
41
     */
42
    public function generate($iat = null, $exp = null)
43
    {
44
        $generator = $this->generator;
45
46
        return $generator($iat, $exp);
47
    }
48
49
    /**
50
     * Determine constraint violations of a CSRF tokens.
51
     *
52
     * @param string $token The token to validate.
53
     * @param int    $now   The current time, defaults to `time()`.
54
     *
55
     * @return InvalidArgumentException[] Constraint violations; if $token is valid, an empty array.
56
     */
57
    public function getConstraintViolations($token, $now = null)
58
    {
59
        $validator = $this->validator;
60
61
        return $validator($token, $now);
62
    }
63
64
    /**
65
     * Validate a CSRF token.
66
     *
67
     * @param string $token The token to validate.
68
     * @param int    $now   The current time, defaults to `time()`.
69
     *
70
     * @return bool true iff $token is valid.
71
     */
72
    public function validate($token, $now = null)
73
    {
74
        return count($this->getConstraintViolations($token, $now)) === 0;
75
    }
76
}
77