ClientStorage::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Germania\PermanentAuth;
3
4
use Germania\PermanentAuth\Exceptions\StorageException;
5
6
7
/**
8
 * This Callable stores on the client side a selector and token pair for Permanent Login.
9
 *
10
 * The constructor expects a cookie name, an encrypting Callable and a Cookie setter Callable.
11
 */
12
class ClientStorage
13
{
14
15
    /**
16
     * @var Callable
17
     */
18
    public $encryptor;
19
20
    /**
21
     * @var Callable
22
     */
23
    public $cookie_setter;
24
25
    /**
26
     * @var string
27
     */
28
    public $cookie_name;
29
30
31
    /**
32
     * @param string   $cookie_name   The Login Cookie Name
33
     * @param Callable $encryptor     Any callable that encrypts selector and token pair
34
     * @param Callable $cookie_setter Any callable that accepts cookie name, cookie text and expiration timestamp.
35
     */
36 10
    public function __construct( $cookie_name, Callable $encryptor, Callable $cookie_setter)
37
    {
38 10
        $this->cookie_name   = $cookie_name;
39 10
        $this->encryptor     = $encryptor;
40 10
        $this->cookie_setter = $cookie_setter;
41 10
    }
42
43
44
    /**
45
     * @param  string $selector
46
     * @param  string $token
47
     * @param  int    $valid_until Timestamp
48
     *
49
     * @return mixed  cookie_setter result
50
     *
51
     * @throws StorageException if setting cookie fails.
52
     */
53 10
    public function __invoke( $selector, $token, $valid_until )
54
    {
55
        // Encrypt first
56 10
        $encryptor      = $this->encryptor;
57 10
        $crypted        = $encryptor( $selector, $token);
58
59
        // Set cookie
60 10
        $cookie_setter  = $this->cookie_setter;
61 10
        $storage_result = $cookie_setter(
62 10
            $this->cookie_name,
63 8
            $crypted,
64 6
            $valid_until
65 2
        );
66
67 10
        if (!$storage_result) {
68 5
            throw new StorageException("Could not store persistent login cookie on client: " . $this->cookie_name . " " . $valid_until);
69
        }
70 5
        return $storage_result;
71
    }
72
}
73